Search code examples
androidnullpointerexceptionpreferencessharedpreferences

Shared preferences in another activity/class


I wrote a class to handle the shared preferences:

import android.preference.PreferenceManager;
import android.util.Log;
import android.content.Context;
import android.content.SharedPreferences;

public class PreferenceHandler {
    
     Context mContext = null;

        public PreferenceHandler (Context context) {
            mContext = context;
        }
       
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext);
         
        public void NewGamePrefs(){
             int GameTime=(Integer.parseInt(mContext.getString(R.string.gametime)));
             int Trivianten=(Integer.parseInt(mContext.getString(R.string.trivialocations)));
             SharedPreferences.Editor memory = preferences.edit();
             memory.putInt("GameTime" , GameTime);
             memory.putInt("Score", 0);
             GPSHandler MyGPS=new GPSHandler(mContext);
             memory.putString("StartLocation", MyGPS.getStartLocationID());
             memory.putString("NextLocation", MyGPS.getStartLocationID());
             memory.putString("EndLocation", MyGPS.getEndLocationID());
        commit();
            }
        
        public String getPreferenceString(String KEY){
            return preferences.getString(KEY, "nodata");
        }
        
        public int getPreferenceValue(String KEY){
            return preferences.getInt(KEY, -1);
        }

If I call this class from the activity file:

PreferenceHandler GameMemory=new PreferenceHandler(this);

GameMemory.NewGamePrefs();

I get a nullpointer exception, anybody any idea why and how to solve this?

Thanks a lot!


Solution

  • You never initialize preferences. Change preferences and your constructor to this:

    SharedPreferences preferences;
    
    public PreferenceHandler (Context context) {
        mContext = context;
        preferences = PreferenceManager.getDefaultSharedPreferences(mContext);
    }