Marduk
Marduk

Reputation: 129

Attempt to invoke interface method 'SharedPreferences.getString on a null object reference

This is my first activity

@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);
    }

This is the method to save and retrive the 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();
    }

This row launch the exception(String json = mPrefs.getString("STATS", "");) Finally this is the log:

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)

What I wrong?

Upvotes: 0

Views: 856

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006604

You have not initialized mPrefs. You only do that in saveStatsMap(), and you are calling loadStatsMap() first.

Upvotes: 1

Related Questions