Android-在单独的类中使用共享首选项? [英] Android - Using Shared Preferences in separate class?
问题描述
我想使用Android中的共享首选项"保存数据.但是我希望使用单独的类来完成此任务.我已经像下面这样实现了该类,
I want to save data using Shared Preferences in android. But I am looking to use separate class to do this task. I have implemented that class like below,
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
如何解决这个问题?
谢谢
How to solve this?
Thanks
推荐答案
getActivity()
是Fragment
的方法,而不是您的SavePref
的方法.在您的情况下,简单的解决方法是使用作为成员变量保留的上下文来检索SharedPreferences
.方法的另一种选择是避免将上下文保留为成员变量,以某种方式将共享的首选项链接到您的SavePref
类的实例,并使用静态方法
getActivity()
is a method of Fragment
not of your SavePref
. In your case the simple fix is to use the Context you are keeping as member variable to retrieve the SharedPreferences
. An alternative to your approach is to avoid keeping the context as member variable, linking somehow the shared preferences to an instance of of your SavePref
class, and have a static method
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);
.这样,您不需要每次调用 from an 这篇关于Android-在单独的类中使用共享首选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!saveInt
时都实例化SavePref,并且可以避免存储对Context
的引用. Activity
. This way you don't need to instantiate SavePref every time you need to call saveInt
, and you can avoid to store a reference to the Context
.