如何在应用程序中获取SharedPreferences? [英] How to getSharedPreferences in Application?
本文介绍了如何在应用程序中获取SharedPreferences?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在应用程序中调用 getSharedPreferences
...
I tried to call getSharedPreferences
in Application...
public class App extends Application{
public App() {
SharedPreferences prefs = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
}
}
...但我得到了一个 NullPointerException
:
...but I got a NullPointerException
:
java.lang.NullPointerException: Attempt to invoke virtual method
'android.content.SharedPreferences
android.content.Context.getSharedPreferences(java.lang.String, int)'
on a null object reference
我也试过这个,但得到了同样的异常:
I also tried this and got same exception:
Context con = getApplicationContext();
如何调用 getSharedPreferences
?
推荐答案
覆盖 onCreate()
,在你的应用中,
Override onCreate()
, in your app,
@Override
public void onCreate() {
super.onCreate();
然后在那里做.不要忘记在 AndroidManifest
中声明你的 Application
子类.例如
and do it there. Don't forget to declare your Application
subclass in the AndroidManifest
as well. E.g.
<application
android:name="App"
这篇关于如何在应用程序中获取SharedPreferences?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文