尝试在空对象引用上调用接口方法'SharedPreferences.getString

时间:2016-09-09 15:19:25

标签: android sharedpreferences

这是我的第一个活动

@Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        prefs = getSharedPreferences("APPA", MODE_PRIVATE);
        bool = isFirstTime();
        if (!bool) {
            stats = new HashMap<>();
            this.addStats();
        } else {
            stats = DataHelper.getInstance().loadStatsMap(getApplicationContext());
            DataHelper.getInstance().saveStatsMap(getApplicationContext(), stats);
        }

        //other code for launch another activity

    private void addStats() {
        for(String s:classes){
            stats.put(s,0);
        }
        DataHelper.getInstance().saveStatsMap(getApplicationContext(),stats);
        bool = true;
        prefs.edit().putBoolean("first", bool).commit();
    }


    public boolean isFirstTime() {
        return prefs.getBoolean("first",false);
    }

这是保存和检索HashMap的方法

public HashMap<String, Integer> loadStatsMap(Context context) {
        Gson gson = new Gson();
        String json = mPrefs.getString("STATS", "");
        HashMap<String, Integer> obj = gson.fromJson(json, HashMap.class);
        return this.stats = obj;
    }

    public void saveStatsMap(Context context, HashMap<String, Integer> stats) {
        mPrefs = context.getSharedPreferences("APPA", Context.MODE_PRIVATE);
        SharedPreferences.Editor prefsEditor = mPrefs.edit();
        Gson gson = new Gson();
        String json = gson.toJson(stats);
        prefsEditor.putString("STATS", json);
        prefsEditor.commit();
    }

此行启动异常(String json = mPrefs.getString(“STATS”,“”);) 最后这是日志:

Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String android.content.SharedPreferences.getString(java.lang.String, java.lang.String)' on a null object reference                                                                          at rp.com.theconverter.Controller.DataHelper.loadStatsMap(DataHelper.java:30)

我错了什么?

1 个答案:

答案 0 :(得分:1)

您尚未初始化TextRange。您只能在mPrefs中执行该操作,并且首先调用saveStatsMap()