我写了一个类来处理共享首选项:
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);
}
如果我从活动文件中调用此类:
PreferenceHandler GameMemory = new PreferenceHandler(this);
GameMemory.NewGamePrefs();
我得到一个nullpointer异常,任何人都知道为什么以及如何解决这个问题?
非常感谢!
答案 0 :(得分:3)
您永远不会初始化preferences
。将preferences
和您的构造函数更改为:
SharedPreferences preferences;
public PreferenceHandler (Context context) {
mContext = context;
preferences = PreferenceManager.getDefaultSharedPreferences(mContext);
}