user6062547
user6062547

Reputation:

android shared preference is null

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

Answers (3)

vivek
vivek

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

Pavan Bilagi
Pavan Bilagi

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

Emre Tekin
Emre Tekin

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

Related Questions