Jak*_*son 39 android sharedpreferences
如何在非Activity类中使用SharedPreferences?我尝试制作一个通用的Preferences实用程序类并导入android.content.Context但Eclipse仍然不允许我使用getSharedPreferences().
San*_*dor 49
SharedPreferences与上下文相关.您只能通过上下文引用它.
您只需将上下文作为参数传递给您的类.例如在构造函数中.
在你的活动中做:
MyClass myClass = new MyClass(this);
Run Code Online (Sandbox Code Playgroud)
San*_*nti 44
我发现的解决方案是:
1 - 在MainActivity类中(即在获取项目中的任何上下文之前始终启动)为上下文创建静态变量:
public static Context contextOfApplication;
2 - 在此类的importante方法(如onCreate,构造函数等)中使用getApplicationContext方法初始化此变量:
public void onCreate() {
contextOfApplication = getApplicationContext();
}
Run Code Online (Sandbox Code Playgroud)
3 - 在同一个类中为此变量创建一个"getter"方法(它也必须是静态的):
public static Context getContextOfApplication(){
return contextOfApplication;
}
Run Code Online (Sandbox Code Playgroud)
4-在非活动类中通过静态调用created方法获取上下文:
Context applicationContext = MyActivityClass.getContextOfApplication();
5 - 使用PreferenceManager类获取SharedPreferences变量:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext);
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你.
| 归档时间: |
|
| 查看次数: |
47967 次 |
| 最近记录: |