-1

This Is The Code When I save My Value

 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();

This Is The Code When i Want to Get Value

         try{
      sharedpreferences  = getSharedPreferences(MyPREFERENCES,Context.MODE_PRIVATE);
      sharedpreferences.getString("pickLoc" ,"");
      sharedpreferences.getString("dropLoc","");
  }catch (Exception e){
      e.printStackTrace();
  }

Then it Throws the Exception :

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference

Thanks In Advance For Helping Me

  • 2
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Goku Nov 14 '17 at 09:03
  • Is the Context null? Can you debug and check which variable is null? – pri Nov 14 '17 at 09:06
  • We need to see the surrounding class for the code that's crashing. – Mike M. Nov 14 '17 at 09:46

1 Answers1

0

Check this

The Context in your activity may be null

SharedPreference without PreferenceManager !!!

Check this sample

To save urValue in SharedPreferences:

SharedPreferences sharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(this);
        Editor editor = sharedPreferences.edit();
        editor.putString(key, urValue);
        editor.apply();

To get name from SharedPreferences:

SharedPreferences sharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(this);
        String urValue = sharedPreferences.getString(key, "default value");

For more check this link

Arnold Brown
  • 1,330
  • 13
  • 28