@Override public boolean importValue(JSONObject json, String key, SharedPreferences.Editor editor) { final Preference preference = supportedMap.get(key); if (preference == null || !preference.exportable()) return false; switch (preference.type()) { case BOOLEAN: editor.putBoolean(key, json.optBoolean(key, preference.defaultBoolean())); break; case INT: editor.putInt(key, json.optInt(key, preference.defaultInt())); break; case LONG: editor.putLong(key, json.optLong(key, preference.defaultLong())); break; case FLOAT: editor.putFloat(key, (float) json.optDouble(key, preference.defaultFloat())); break; case STRING: editor.putString(key, json.optString(key, preference.defaultString())); break; default: break; } return true; }
@Override public boolean exportValue(JSONObject json, String key, SharedPreferences preferences) { final Preference preference = supportedMap.get(key); if (preference == null || !preference.exportable()) return false; try { switch (preference.type()) { case BOOLEAN: json.put(key, preferences.getBoolean(key, preference.defaultBoolean())); break; case INT: json.put(key, preferences.getInt(key, preference.defaultInt())); break; case LONG: json.put(key, preferences.getLong(key, preference.defaultLong())); break; case FLOAT: json.put(key, preferences.getFloat(key, preference.defaultFloat())); break; case STRING: json.put(key, preferences.getString(key, preference.defaultString())); break; default: break; } } catch (JSONException e) { return false; } return true; }
public static HashMap<String, Preference> getSupportedPreferencesMap(Class cls) { final Field[] fields = cls.getDeclaredFields(); final HashMap<String, Preference> supportedPrefsMap = new HashMap<>(); for (final Field field : fields) { final Preference annotation = field.getAnnotation(Preference.class); if (Modifier.isStatic(field.getModifiers()) && CompareUtils.classEquals(field.getType(), String.class) && annotation != null && annotation.exportable() && annotation.type() != INVALID) { try { supportedPrefsMap.put((String) field.get(null), annotation); } catch (final IllegalAccessException | IllegalArgumentException e) { Log.w(LOGTAG, e); } } } return supportedPrefsMap; }