Skip to content

Instantly share code, notes, and snippets.

@npu3pak
Last active January 25, 2017 15:11
Show Gist options
  • Save npu3pak/71bad593c0f26aae409f9f99c372b6d7 to your computer and use it in GitHub Desktop.
Save npu3pak/71bad593c0f26aae409f9f99c372b6d7 to your computer and use it in GitHub Desktop.
Android. Удобная реализация SharedPreferences. В примере используется библиотека Gson
import android.content.Context;
import android.content.SharedPreferences;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
public final class Preferences {
private static final String PREFS_KEY = "my.app.shared.preferences.key";
private static final String PREFS_JSON_KEY = "json.key";
/*
Настройки
*/
@SerializedName("value1")
public String value1;
@SerializedName("value2")
public Integer value2;
/*
Механизм
*/
private static Preferences instance;
private Preferences() {
}
public synchronized void save(Context context) {
String json;
try {
json = new Gson().toJson(this);
} catch (Exception e) {
e.printStackTrace();
return;
}
SharedPreferences preferences = context.getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(PREFS_JSON_KEY, json);
editor.apply();
}
public void reset(Context context) {
Preferences oldPreferences = Preferences.load(context);
Preferences newPreferences = new Preferences();
//Переносим значения, если нужно. Например стоит перенести идентификатор GCM
newPreferences.save(context);
instance = newPreferences;
}
public static synchronized Preferences load(Context context) {
if (instance != null) {
return instance;
}
SharedPreferences preferences = context.getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE);
if (!preferences.contains(PREFS_JSON_KEY)) return new Preferences();
String json = preferences.getString(PREFS_JSON_KEY, null);
try {
instance = new Gson().fromJson(json, Preferences.class);
return instance;
} catch (Exception e) {
e.printStackTrace();
instance = new Preferences();
return instance;
}
}
}
@npu3pak
Copy link
Author

npu3pak commented Jan 25, 2017

Пример использования:

Preferences initial = Preferences.load(context);
initial.value1 = "123";
initial.value2 = 123;
initial.save(this);

Preferences restored = Preferences.load(context);
Log.i(TAG, restored.value1);
Log.i(TAG, "" + restored.value2);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment