Reputation:
i am using shared preference
in android but it return null,
i saw a lot of code example for this and i can't see any error in my code
SharedPreferences sp =this.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
Log.v("sharedpref",""+username+": "+password);
editor.putString("email", username);
editor.putString("pass",password);
editor.apply();
and here i am retrieving the data from shared preference (in another activity)
SharedPreferences sp =this.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Log.v("shersend",""+sp.getString("email", "Empty")+": "+sp.getString("pass", "Empty"));
String email = sp.getString("email", "Empty");
String pass = sp.getString("pass", "Empty");
so is there any problem with my code? and is there a better to write this?
Upvotes: 1
Views: 1681
Reputation: 198
You are saving the preference in one Activity say A, And accessing in another activity say B, and context of both activities are different and so preferences values cannot be accessed as mode is private.
try
this.getApplicationContext().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Upvotes: 4
Reputation: 1617
Use getApplicationContext()
SharedPreferences sp =getApplicationContext().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
Log.v("sharedpref",""+username+": "+password);
editor.putString("email", username);
editor.putString("pass",password);
editor.commit();
Upvotes: 0
Reputation: 472
Please try that way, Change this code block
SharedPreferences sp =this.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
to this code block
SharedPreferences sp= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Upvotes: 3