这是我的第一个活动
@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)
我错了什么?
答案 0 :(得分:1)
您尚未初始化TextRange
。您只能在mPrefs
中执行该操作,并且首先调用saveStatsMap()
。