当我想从共享偏好中获取价值时,我会出错

When I Want to Take Value From Shared Preferance then i Get Error

这是我保存我的值时的代码

 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: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference

在此先感谢您对我的帮助

检查这个

您的 activity 中的上下文可能为空

SharedPreference 没有 PreferenceManager !!!

检查这个样本

要在 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