0

The SharedPreferencesCompat class is used in android,

but i can't use it in javafx.

So, I want to know how to rewrite it in javafx?

Could some one help me? Thanks.

/** * Reflection utils to call SharedPreferences$Editor.apply when possible, * falling back to commit when apply isn't available. */

public class SharedPreferencesCompat {
    private static final Method sApplyMethod = findApplyMethod();

    @SuppressWarnings({ "unchecked", "rawtypes" })
    private static Method findApplyMethod() {
        try {
            Class cls = SharedPreferences.Editor.class;
            return cls.getMethod("apply");
        } catch (NoSuchMethodException unused) {
            // fall through
        }
        return null;
    }

    public static void apply(SharedPreferences.Editor editor) {
        if (sApplyMethod != null) {
            try {
                sApplyMethod.invoke(editor);
                return;
            } catch (InvocationTargetException unused) {
                // fall through
            } catch (IllegalAccessException unused) {
                // fall through
            }
        }
        editor.commit();
    }



public class SharedPreferencesUtils {

    public static void setStringArrayPref(SharedPreferences prefs, String key, ArrayList<String> values) {
        SharedPreferences.Editor editor = prefs.edit();
        JSONArray a = new JSONArray();
        for (int i = 0; i < values.size(); i++) {
            a.put(values.get(i));
        }
        if (!values.isEmpty()) {
            editor.putString(key, a.toString());
        } else {
            editor.putString(key, null);
        }
        SharedPreferencesCompat.apply(editor);
    }

    public static ArrayList<String> getStringArrayPref(SharedPreferences prefs, String key) {
        String json = prefs.getString(key, null);
        ArrayList<String> values = new ArrayList<String>();
        if (json != null) {
            try {
                JSONArray a = new JSONArray(json);
                for (int i = 0; i < a.length(); i++) {
                    String val = a.optString(i);
                    values.add(val);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return values;
    }

}
吳東興
  • 1
  • 3
  • Are you writing an Android app or a desktop application? What is the functionality you need? Have you considered using the [Preferences API](http://docs.oracle.com/javase/8/docs/technotes/guides/preferences/overview.html) – Itai Jan 10 '16 at 12:26
  • I have written an Android app. but i need desktop application now. I try it, thanks. – 吳東興 Jan 10 '16 at 12:48
  • It's work now,thanks. – 吳東興 Jan 10 '16 at 16:38

0 Answers0