在另一项活动/课程中共享偏好
我编写了一个类来处理共享首选项:
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();
我遇到空指针异常,有人知道为什么以及如何解决这个问题吗?
多谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您永远不会初始化
首选项
。将preferences
和构造函数更改为:You never initialize
preferences
. Changepreferences
and your constructor to this: