自定义类扩展了Singleton目的的应用程序

时间:2015-09-22 08:17:23

标签: android nullpointerexception android-sharedpreferences

我尝试创建自定义类以从SharedPreferences中获取一些值。 我的目标是从任何阶级达到这些价值观。

我在

上得到空指针异常
 SharedPreferences prefs = getApplicationContext().getSharedPreferences("UserFile", MODE_PRIVATE);

我的代码如下;

public class UserInfo extends Application {

    private String token;
    private String SAVED_USERNAME;

    public UserInfo() {
        SharedPreferences prefs = getApplicationContext().getSharedPreferences("UserFile", MODE_PRIVATE);
        token = prefs.getString("Token", null);
    }

    public String getToken() {
        return token;
    }
}

可能出错了什么?

5 个答案:

答案 0 :(得分:1)

通常,Android组件在其生命周期中进行初始化。在这种特殊情况下,您无法访问应用ContextSharedPreferences,因为它们尚未初始化。

第二个问题可能是(感谢我的结晶球)您没有将Application添加到AndroidManifest

因此,您首先想到的可能是将初始化代码从构造函数移动到onCreate。这将解决这个特殊问题。

但是,做你正在做的事情是不好的做法。因为每个应用程序只能有1 Application个组件。这将限制你每个应用程序1个这样的单身人士。考虑使用Application将应用程序Context作为单例并创建另一个单例以提供UserInfo。

没有例子,请自己锻炼。

答案 1 :(得分:1)

在util类中使用此方法。无需延长申请。

public static String getToken(Context context) {
   return PreferenceManager.getDefaultSharedPreferences(context).getString("Token", null);
}

答案 2 :(得分:0)

android中有一条规则 - 不要使用app组件的构造函数:Activity / Fragment / Application / Service ...有onCreate()方法,因为在你的构造函数上下文中将为null。所以将代码移动到onCreate()。您还需要在Manifest中将UserInfo设置为应用程序。

答案 3 :(得分:0)

确保您已在AndroidManifest.XML文件中注册此课程。

<application android:name=".UserInfo"
    ...
/>

注意:您访问共享偏好设置的方式似乎不太好。我宁愿自己声明一个名为PreferencesHelper的类,并将所有首选项放在那里。

public class PreferencesHelper{
    private SharedPreferences mPrefs;

    public PreferencesHelper(Context context){
        this.mPrefs = context.getSharedPreferences("name", Context.MODE_PRIVATE);
    }

    public getToken() {
        return mPrefs.getString("Token", null);
    }

    public String setToken(String token) {
        mPrefs.edit().putString("Token", token).apply();
    }
}

答案 4 :(得分:0)

public class MyApp extends Application {


 private static MyApp _instance;

@Override
public void onCreate() {
    super.onCreate();
   _instance = this;
}
public static MyApp getInstance(){
   return _instance;
}

public String getToken() {
    return getSharedPreferences("UserFile", MODE_PRIVATE).getString("Token",  null);
}
}

在你的清单中:

<application
    android:name="your.package.MyApp"
   >

如果您使用:

String token = MyApp.getInstance().getToken();
相关问题