当我保存我的价值时,这是代码
public static final String
MyPREFERENCES = "MyPrefs" ;
public SharedPreferences sharedpreferences;
public static final String p = "pickLoc";
public static final String Phone = "dropLoc";
String pickLoc = pickupEt.getText().toString().trim();
String dropLoc = dropEt.getText().toString().trim();
sharedpreferences = getSharedPreferences(BookMyRide.this.MyPREFERENCES,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(p, pickLoc);
editor.putString(Phone, dropLoc);
editor.commit();
当我想获得价值时,这是代码
try{
sharedpreferences = getSharedPreferences(MyPREFERENCES,Context.MODE_PRIVATE);
sharedpreferences.getString("pickLoc" ,"");
sharedpreferences.getString("dropLoc","");
}catch (Exception e){
e.printStackTrace();
}
然后它抛出异常:
java.lang.NullPointerException:尝试调用虚方法' android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String,int)'在空对象引用上
提前感谢帮助我
答案 0 :(得分:0)
检查
您活动中的上下文可能为空
没有 PreferenceManager 的SharedPreference !!!
检查此示例
在SharedPreferences中保存 urValue :
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
editor.putString(key, urValue);
editor.apply();
从SharedPreferences获取名称:
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
String urValue = sharedPreferences.getString(key, "default value");
有关详情,请查看此link