Android: string value is not getting in Shared Preference - android

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.

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

Similar like Php session for Android Studio

I'm newbie for Android Studio & Java, i'm PHP user.
Just want to know how to do like PHP session in Android Studio.
No matter which Activity i go to, i can easily get the session value example like the User ID. (session["USERID"])
now the method i using is putting extra everytime i call for another activity.
i'm sure there will be a better way to do this.
anyone have any good suggestion?
PS: I google around and it keep return me PHP session tutorial/example/etc but not for Android Studio....(may be i enter work #keyword or sentence)
Thank You Very Much
Thanks to fillobotto & Arshid KV
here is my code
first_main activity
sharedpreference = getSharedPreferences(BIZInfo, Context.MODE_PRIVATE);
sharedpreference.edit().putString(userid, "12345");
sharedpreference.edit().commit();
second_main activity
sharedpreference = PreferenceManager.getDefaultSharedPreferences(this);
String restoredText = sharedpreference.getString("text", null);
if (restoredText != null) {
sp_name = sharedpreference.getString("userid", "No name defined");
}
Log.i("TAG", "onCreate: [" + sp_name + "]");
log show empty value/nothing...
what went wrong!?
You can use SharedPreferences as session in php
Demo code :-
Setting values in Preference:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Arshid");
editor.putInt("Age", 22);
editor.commit();
Retrieve data from preference:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int Age = prefs.getInt("Age", 0); //0 is the default value.
}
You were really near to the solution. This is what I use:
public static String getSession(Activity context) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
return sharedPreferences.getString("session", null);
}
public static void setSession(Activity context, String session) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("session", session);
editor.apply();
}
I'm actually passing the Activityto get SharedPreferences, but in this way you will obtain an instance of the object which is not activity-related.

Remove Shared preferences key/value pairs

I store some payment values in one Activity
SharedPreferences spreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
productId = spreferences.getString("productId", "");
purchaseToken = spreferences.getString("purchaseToken", "");
orderId = spreferences.getString("orderId", "");
Now I retrieve them in another one as
SharedPreferences spreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
productId = spreferences.getString("productId", "");
purchaseToken = spreferences.getString("purchaseToken", "");
orderId = spreferences.getString("orderId", "");
My question is to delete them in the second Activity after retrieving them.Thanks.
Use SharedPreferences.Editor remove (String key) to do the same.
where it marks in the editor that a preference value should be
removed, which will be done in the actual preferences once commit() is
called.
Note that when committing back to the preferences, all removals are
done first, regardless of whether you called remove before or after
put methods on this editor.
So in your case you can use it like
SharedPreferences.Editor editor = spreferences.edit();
editor.remove("productId");
editor.remove("purchaseToken");
editor.remove("orderId");
editor.commit();
To store values in SharedPreference, use below code:
SharedPreferences spreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Editor spreferencesEditor = spreferences.edit();
spreferencesEditor.putString("productId", "value of prodId");
spreferencesEditor.putString("purchaseToken", "value of purchaseToken");
spreferencesEditor.putString("orderId", "value of orderId");
spreferencesEditor.commit();
To remove specific value from SharedPreference, use below code:
SharedPreferences spreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Editor spreferencesEditor = spreferences.edit();
spreferencesEditor.remove("productId"); //we are removing prodId by key
spreferencesEditor.commit();
To remove All values from SharedPreference, use below code:
SharedPreferences spreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Editor spreferencesEditor = spreferences.edit();
spreferencesEditor.clear();
spreferencesEditor.commit();
To clear the SharedPreferences, use the SharedPreferences Editor
In your case:
SharedPreferences spreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = spreferences.edit();
editor.clear();
editor.commit();
You can remove any values associated with a specific key using this,
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = prefs.edit();
editor.remove("your_key");
editor.commit();
or
SharedPreferences prefs = context.getSharedPreferences(name, mode);
SharedPreferences.Editor editor = prefs.edit();
editor.remove(your_key)
editor.commit();
SharedPreferences spreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor=spreferences.edit();
editor.remove("productId");
editor.remove("purchaseToken");
editor.remove("orderId");
editor.commit();
// you can also use editor.apply(); instead of editor.commit(); using apply will handle the removing in the background
You need to do same like I am removing my preferences.
SharedPreferences preferences = contextAct.getSharedPreferences("PREF_KEY", 0);
preferences.edit().remove("productId").commit();
preferences.edit().remove("purchaseToken").commit();
preferences.edit().remove("orderId").commit();
Format : preferences.edit().remove("Your Key").commit();
This will clear your preferences.

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

Saving and retrieving values with SharedPreferences

I want to save two values using shared preferences and get those values in other classes. Can any one please give me information about how to set shared preferences and getting value from shared preferences.
I am using following code:
SharedPreferences settings =
getSharedPreferences("MyGamePreferences", MODE_WORLD_READABLE);
SharedPreferences gameSettings = getSharedPreferences("MyGamePreferences", MODE_WORLD_READABLE);
SharedPreferences.Editor prefEditor = gameSettings.edit();
prefEditor.putString("KEY", "e6c77c29021c9b3bd55aa0e9b7687ad9");
prefEditor.putString("SECRET", "ca85fa3fe86edaf2");
prefEditor.commit();
Try this,
SharedPreferences button1;
String name1="",name2="";
button1=this.getSharedPreferences("MyGamePreferences",MODE_WORLD_WRITEABLE);
name1=button1.getString("KEY", "");
name2=button1.getString("SECRET", "");
SharedPreferences.Editor prefEditor = button1.edit();
prefEditor.putString("KEY","e6c77c29021c9b3bd55aa0e9b7687ad9");
prefEditor.putString("SECRET", "ca85fa3fe86edaf2");
prefEditor.commit();
now stored two values.
SharedPreferences myPrefs = this.getSharedPreferences("prefEditor ", MODE_WORLD_READABLE);
String key = myPrefs.getString(KEY, "nothing");
String secret = myPrefs.getString(SECRET, "nothing");
you can retrieve the values, using the getString method by passing the Key and a default value.
http://developer.android.com/reference/android/content/SharedPreferences.html
my problem was how to retrieve these stored values in another file. it was cleared
my code is
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
String key = sharedPreferences.getString("key", "");
String secret = sharedPreferences.getString("secret", "");
Thanks .

Categories

Resources