Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shared Preference returns always the default value

Here is code I am Using to create and store value in Preference. outgoing is String variable.

SharedPreferences sp = getSharedPreferences(outgoing, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();                
editor.putString("PhoneNo","Hi");
editor.commit();

Here is the code to get value from SharedPreference.

SharedPreferences sp 
=getSharedPreferences(outgoing,Activity.MODE_PRIVATE);
String calln = sp.getString("PhoneNo","0");
Toast.makeText(mContext, "SHARED"+calln,Toast.LENGTH_LONG).show();
like image 411
Vikram Avatar asked Sep 16 '14 13:09

Vikram


1 Answers

You should probably call the getSharedPreferences on the context from which you are accessing them.

Source

Therefore, depending on how you can access your context, if you pass it to some other activity or in an asynchronous task, here are some examples of usage:

this.getSharedPreferences(outgoing, Activity.MODE_PRIVATE);

context.getSharedPreferences(outgoing, Activity.MODE_PRIVATE);

getApplicationContext().getSharedPreferences(outgoing, Activity.MODE_PRIVATE);

Also, one way you can test your stuff is to use a listener when SharedPreferences get changed:

onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)

Called when a shared preference is changed, added, or removed.

here is how to do that

You can also use the Preference Manager to obtain the SharedPreferences:

PreferenceManager.getSharedPreferences(YOUR_CONTEXT).getString(
                    "PhoneNo", "0");

Or to store them:

PreferenceManager.getSharedPreferences(YOUR_CONTEXT).edit().putString(
                    "PhoneNo", "Hi").commit();
like image 156
nem035 Avatar answered Nov 11 '22 22:11

nem035