如何在应用程序中获得共享首选项?
我试图调用应用getSharedPreferences
...如何在应用程序中获得共享首选项?
public class App extends Application{
public App() {
SharedPreferences prefs = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
}
}
...但我得到了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
我也尝试这样做,得到了同样的异常:
Context con = getApplicationContext();
我该如何拨打getSharedPreferences
?
覆盖onCreate()
,在您的应用程序,
@Override
public void onCreate() {
super.onCreate();
,做它。不要忘记在AndroidManifest
中申报您的Application
子类。例如。
<application
android:name="App"
完美答案。 –
获取SharedPreferences对象中onCreate()
方法,而不是在构造函数
您正在得到一个空指针,因为您是从构造函数调用它。此时应用程序上下文尚未创建。 尝试从Application类的onCreate()方法调用它。
Application
是Android类,它有自己的生命周期。你不能在那里发起或做任何其他与SharedPreference
相关的操作。因为它需要Context
和Application
的Context
尚未使用其自己的生命周期进行初始化。因此,最好的做法是在onCreate
方法中启动任何操作。
另外一个建议,使你的Application
类单身。
您不能在应用程序的构造函数中创建共享偏好对象,而不是在应用程序类的onCreate方法中创建它。下面是代码
public class App extends Application{
public App() {
}
@Override
public void onCreate(){
SharedPreferences prefs = getApplicationContext().getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
}
}
块我觉得ATLEAST你可以尝试这样的;
public class MyApplicationclass extends Application {
Context context;
public MyApplicationclass() {
}
public MyApplicationclass(Context context) {
this.context = context;
}
}
现在你有了上下文; 所以可以很容易地创建和使用sharedpreferences
public class Preferences {
private static Preferences preferences = null;
private SharedPreferences.Editor editor;
private String userName;
private String token;
private String password;
private Preferences(Context context) {
editor = getCurrent(context).edit();
}
public static synchronized Preferences getInstance(Context context) {
if (preferences == null) {
preferences = new Preferences(context);
}
return preferences;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getDefaults(String key, Context context) {
return getCurrent(context).getString(key, null);
}
public void store(String key, String value) {
editor.putString(key, value);
editor.apply();
}
public void remove(String key) {
editor.remove(key);
editor.apply();
}
private SharedPreferences getCurrent(Context context) {
return context.getSharedPreferences("app_preference_key"), Context.MODE_PRIVATE);
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
这是一个单独实现的喜好。
http://stackoverflow.com/a/10818234/3395198 –