How to read from SharedPreference file android - android

In my MainActivity, I have written some code which I assume creates a file and saves a value in that file.
public static final String WHAT_I_WROTE = null;
public void sendMessage(View view) {
EditText editText = (EditText) findViewById(R.id.editText);
String message = editText.getText().toString();
//creates new SharedPreference?
SharedPreferences saver = getSharedPreferences("saved_text", Context.MODE_PRIVATE);
//writes to the preferences file called saved_text?
SharedPreferences.Editor writer = saver.edit();
writer.putString(WHAT_I_WROTE, message);
writer.commit();
}
In another activity, I want to be able to read the message and display it but when I try this, it cannot resolve the symbol "saver".
String text_for_display = saver.getString(WHAT_I_WROTE);
What is the mistake I have made here and how do I correct it to read the saved string?
Thanks.

In another activity you have to again initalize the Shared preference.
SharedPreferences saver = getSharedPreferences("saved_text", Context.MODE_PRIVATE);
String text_for_display = saver.getString(WHAT_I_WROTE),"any_default_value";
WHAT_WROTE = "anyText"

Add this to the other activity you have:
SharedPreferences saver = getSharedPreferences("saved_text", Context.MODE_PRIVATE);
then read it like this
String myValue = saver.getString("saved_text", "default_value");

Setting values in preference is like,
SharedPreferences.Editor editor = getSharedPreferences("saved_text", MODE_PRIVATE).edit();
editor.putString("WHAT_I_WROTE", message);
editor.commit();
Retrieve the data like,
SharedPreferences prefs = getSharedPreferences("saved_text", MODE_PRIVATE);
String text_for_display = prefs.getString("WHAT_I_WROTE", null);

Don't forget to put "context" before "getSharedPreferences" if necessary.

Related

Unable to get data from shared preferences

I am saving phone no. in shared preference and in another activity I am trying to get phone no. from shared preference.
private static final String KEY_PHONE = "keyphone";
SharedPreferences sharedPreferences = getSharedPreferences("simplifiedcodingsharedpref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(KEY_PHONE, "3454534565");
editor.apply();
In another activity I am using something like this:
SharedPreferences sp = getSharedPreferences("simplifiedcodingsharedpref", Context.MODE_PRIVATE);
String phone_id = sp.getString("keyphone","");
Toast.makeText(getApplicationContext(), phone_id, Toast.LENGTH_SHORT).show();
My problem is here I am not getting phone no in toast message and I am getting empty toast.
Someone please let me know how can I get phone no in another activity.Any help would be appreciated.
THANKS
The Main Problem is in here : editor.putString(KEY_PHONE, "3454534565");
To Write:
SharedPreferences preferences = getSharedPreferences("simplifiedcodingsharedpref", Context.MODE_WORLD_WRITEABLE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("KEY_PHONE", "3454534565");
editor.apply();
To Read:
SharedPreferences prfs = getSharedPreferences("simplifiedcodingsharedpref", Context.MODE_PRIVATE);
String phone_id= prfs.getString("KEY_PHONE", "");
Toast.makeText(getApplicationContext(), phone_id, Toast.LENGTH_SHORT).show();
You did everything right except one thing.
When retrieving a String value you cannot just set the value field to "".
When retrieving a String, the default value is null, when retrieving boolean, default value is false and when retrieving a boolean, the default value is false.
So instead of using
String phone_id = sp.getString("keyphone","");
you need to use
String phone_id = sp.getString("keyphone", null);
You can use this to store a value in Shared Preferences:
SharedPreferences sharedPreferences =
getSharedPreferences("simplifiedcodingsharedpref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor =
sharedPreferences.edit();
editor.putString("keyphone", "3454534565");
editor.apply();
And then this to retrieve it:
SharedPreferences sp = getSharedPreferences("simplifiedcodingsharedpref",
Context.MODE_PRIVATE);
String phone_id = sp.getString("keyphone","");
Toast.makeText(getApplicationContext(), phone_id, Toast.LENGTH_SHORT).show();

Cannot load string from Fragment's shared preferences

I am trying to save and load a string value from a fragment's shared preferences. However, the string I am committing to the preferences does not load back from the preferences. Here is my code.
// Prefs string handle
String NAME = "myPref";
// Get default prefs for the fragment
SharedPreferences defaultPrefs =
PreferenceManager.getDefaultSharedPreferences(getActivity());
// Commit a string to prefs
defaultPrefs.edit().putString(NAME, "Hello world!");
defaultPrefs.edit().commit();
// Load the string just commited to prefs
String commitedString = defaultPrefs.getString(NAME,"defaultString");
// Print the loaded string
// logs defaultString
// does not log Hello world!
Log.v(TAG,"commitedString value is "+commitedString);
You are editing, putting a String, not committing, then editing again, putting nothing, and then committing.
Change
defaultPrefs.edit().putString(NAME, "Hello world!");
defaultPrefs.edit().commit();
To
defaultPrefs.edit().putString(NAME, "Hello world!").commit();
change this
defaultPrefs.edit().putString(NAME, "Hello world!");
defaultPrefs.edit().commit();
to this:
SharedPreferences.Editor editor = defaultPrefs.edit();
editor.putString(NAME, "Hello world!");
editor.commit();
and it should work
//This always seemed to work for me
Context context = YourFragmentName.this;
String NAME = "";
SharedPreferences share = context.getSharedPreferences("prefs", 0);
share.getString(NAME, NAME);
SharedPreferences.Editor editor = share.edit();
editor.putString(NAME, "myPref");
editor.apply();
//then get your string
String commitedString = share.getString(NAME, "");

Access to SharedPreferences from different activity

In first (MainActivity) I save data trough SharedPreferences:
Editor editor = mGameSettings.edit();
editor.putString(GAME_PREFERENCES_SHOP, Shops.get(lv.getCheckedItemPosition()));
editor.commit();
And I can read this data from MainActivity after restart application:
if (mGameSettings.contains(GAME_PREFERENCES_SHOP))
Tv2.setText(mGameSettings.getString(GAME_PREFERENCES_SHOP, ""));
But how to read and edit this SharedPreferences from other activity?
Write the Below code in your another activity:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
if (sp.contains(MainActivity.GAME_PREFERENCES_SHOP)) //hoping that GAME_PREFERENCES_SHOP is a static constant defined in MainActivity
Tv2.setText(sp.getString(MainActivity.GAME_PREFERENCES_SHOP, ""));
You can use below code for getting the preference value from different Application
Context launcherContext = null;
try {
final int flags = Context.CONTEXT_IGNORE_SECURITY | Context.CONTEXT_INCLUDE_CODE;
launcherContext = getApplicationContext().createPackageContext("com.another.package", flags);
} catch (final NameNotFoundException e) {
return ;
}
final SharedPreferences pref = launcherContext.getSharedPreferences(
"prefname",
Context.MODE_WORLD_READABLE | Context.MODE_MULTI_PROCESS);
final String prefValue = pref.getString("prefname", null);
Log.i("test", prefValue);
You can read and edit with the same code. You just have to use the same Prefs file name and key for the required value.
You can declare your Pref File name as public static final String PREFS_NAME = "MyPrefsFile"; in the main activity and then access it from anywhere in the application.
Example, in other Activity:
SharedPreferences mGameSettings = getSharedPreferences(MainActivity.PREFS_NAME, MODE_PRIVATE);
if (mGameSettings.contains(MainActivity.GAME_PREFERENCES_SHOP))
Tv2.setText(mGameSettings.getString(MainActivity.GAME_PREFERENCES_SHOP, ""));

SharedPreferences keep getting default value

I keep Getting the Default value either my UI will display null or if I use integers it displays that default value as well here it is in the string form plz help
//putting the information in shared preferences
TextView pScore1=(TextView)findViewById(R.id.pScore1f);
SharedPreferences peepsScores2= PreferenceManager.getDefaultSharedPreferences(GamePlayFirst.this);
SharedPreferences.Editor editor2 =peepsScores2.edit();
String userScore11 = pScore1.getText().toString();
editor2.putString("userScore11",userScore11);
editor2.commit();
//getting it and editing it
SharedPreferences peepsScores2 = PreferenceManager.getDefaultSharedPreferences(this);
int u;
int one =1;
int newUsrScore1=1;
String userScore11 = peepsScores2.getString("userScore11",null);
u=Integer.parseInt(userScore11);
newUsrScore1 = u+one;
String newUserScore1 = Integer.toString(newUsrScore1);
SharedPreferences.Editor editor = peepsScores2.edit();
editor.putString(newUserScore1, NewUserScore1);
editor.commit();
//getting it and displaying it on the UI
SharedPreferences peepsScores2 = PreferenceManager.getDefaultSharedPreferences(this);
String userScore11 = peepsScores2.getString("NewuserScore1",null);
pScore1.setText(" "+userScore11);
I have added some comment to you code please check:
//putting the information in shared preferences
TextView pScore1=(TextView)findViewById(R.id.pScore1f);
SharedPreferences peepsScores2=
PreferenceManager.getDefaultSharedPreferences(GamePlayFirst.this);
SharedPreferences.Editor editor2 =peepsScores2.edit();
String userScore11 = pScore1.getText().toString();
editor2.putString("userScore11",userScore11);
editor2.commit();
//getting it and editing it
SharedPreferences peepsScores2 = PreferenceManager.getDefaultSharedPreferences(this);
int u;
int one =1;
int newUsrScore1=1;
String userScore11 = peepsScores2.getString("userScore11",null);
u=Integer.parseInt(userScore11);
newUsrScore1 = u+one;
String newUserScore1 = Integer.toString(newUsrScore1);
SharedPreferences.Editor editor = peepsScores2.edit();
//#Praful: here newUserScore1 seems to be integer value and you are storing
//null here. I think it it should be
//`editor.putString("NewuserScore1", newUsrScore1);`
editor.putString(newUserScore1, null);
//#Praful: call commit here
editor.commit;
//getting it and displaying it on the UI
SharedPreferences peepsScores2 = PreferenceManager.getDefaultSharedPreferences(this);
String userScore11 = peepsScores2.getString("NewuserScore1",null);
pScore1.setText(" "+userScore11);
This line
editor.putString(newUserScore1, null);
should be
editor.putString("NewuserScore1",newUserScore1);
and also don't forget to commit your changes using editor.commit();
Whenever you working with SharedPreference never forget to call commit() to save your changes.
SharedPreferences.Editor editor = peepsScores2.edit();
editor.putString("NewuserScore1", newUserScore1);
editor.commit();

Android: string value is not getting in Shared Preference

I have created a shared preference for a boolean value and for a string value. The boolean value is gotten in another activity. But for the string I am only getting default value.
Home.class
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor spe = prefs.edit();
spe.putBoolean("flag", true);
spe.putString("user", "hello");
spe.commit();
welcome.class
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean flag= prefs.getBoolean("flag", false);
String user=prefs.getString("user","Nothing");
TextView tv = new TextView(this);
tv.setText("Flag : "+flag+(" User : "+user);
For 'user', only 'Nothing' is displaying. Where should I correct my code?
Try using:
SharedPreferences settings = getSharedPreferences(appName,0);
settings.getBoolean("flag", true);
settings.getString("user", "hello");
And to put:
SharedPreferences settings = getSharedPreferences(appName,0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("flag",true);
editor.putString("user","hello");
editor.commit();
This is what I use in my application, and it shares booleans/ints/strings accrossed many many Classes
Note: appName doesn't have to be the app name, like in the official tutorial.

Categories

Resources