我想在 android 中使用共享首选项保存数据。但我希望使用单独的类来完成这项任务。我已经像下面那样实现了那个类,
import android.content.Context;
import android.content.SharedPreferences;
public class SavePref {
private Context context;
public SavePref(Context context){
this.context = context;
}
public void saveInt(String key, int value) {
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(key, value);
editor.commit();
}
}
但是getActivity()
有错误,
The method getActivity() is undefined for the type SavePref
如何解决?
谢谢
最佳答案
getActivity()
是 Fragment
的方法,不是您的 SavePref
的方法。在您的情况下,简单的解决方法是使用您保留为成员变量的上下文来检索 SharedPreferences
。另一种方法是避免将上下文保留为成员变量,以某种方式将共享首选项链接到 SavePref
类的实例,并使用静态方法
public static void saveInt(Context context, String key, int value) {
SharedPreferences sharedPref = context.getDefaultSharedPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(key, value);
editor.commit();
}
并像这样解决方法:
SavePref.saveInt(getActivity(), key, value);
来自 Fragment
或
SavePref.saveInt(this, key, value);
来自 Activity
。这样你就不需要每次调用saveInt
时都实例化SavePref,并且可以避免存储对Context
的引用。
关于java - Android - 在单独的类中使用共享首选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29047777/