【发布时间】:2017-10-16 15:10:24
【问题描述】:
我是 android 和学习的新手。我的应用程序中有主题更改选项,用户可以从中切换主题。我使用全局变量在应用程序中保存主题编号,但是当应用程序从后台清除时它会丢失。所以我考虑过为此目的使用 SharedPreferences 。我找到了一种从here 存储和检索 SharedPreference 的简单方法。
我的代码如下所示:
public class Keystore {
private static Keystore store;
private SharedPreferences SP;
private static String filename="Keys";
public static int theme=1;
private Keystore(Context context) {
SP = context.getApplicationContext().getSharedPreferences(filename,0);
}
public static Keystore getInstance(Context context) {
if (store == null) {
store = new Keystore(context);
}
return store;
}
public void put(String key, String value) {
SharedPreferences.Editor editor;
editor = SP.edit();
editor.putString(key, value);
editor.apply();
}
public String get(String key) {
return SP.getString(key, null);
}
public int getInt(String key) {
return SP.getInt(key, 0);
}
public void putInt(String key, int num) {
SharedPreferences.Editor editor;
editor = SP.edit();
editor.putInt(key, num);
editor.apply();
}
public void clear(){
SharedPreferences.Editor editor;
editor = SP.edit();
editor.clear();
editor.apply();
}
public void remove(){
SharedPreferences.Editor editor;
editor = SP.edit();
editor.remove(filename);
editor.apply();
}
}
根据原始答案中给出的示例,我正在尝试在我的活动类中使用它来获取价值,如下所示
int theme= store.getInt("theme");
Log.d(getClass().getName(),"theme"+theme);
但它返回的是 0 而不是 1。我也怀疑我在 public static int theme=1; 这样的类中将默认值保存为 1@ 这是在 SharedPreferences 中保存默认值的正确方法吗?
谢谢
【问题讨论】:
-
您在共享偏好中保存的价值在哪里?
-
@VivekMishra 我用它像 public static int theme=1;默认情况下,直到现在还没有提交任何保存。
-
如果您没有保存任何值,那么您从共享偏好中获取什么?它将始终返回整数的默认值,即 0
标签: java android sharedpreferences