Retrieving and Updating values using Sharedpreferences - android

I need to know how can shared preference can be used to keep my data persistent and also update the values.I have written some code.
MainActivity.java
SharedPreferences sPrefs= this.getSharedPreferences(mypreference, Context.MODE_PRIVATE);
if(sPrefs.contains("userData"))
{
retreivepreviousdata=gson.fromJson(sPrefs.getString("userData",""),DataStore.class);
userDataStore.getDataStore().addAll(retreivepreviousdata.getDataRetrieve());
}
userDataStore.getDataStore().add(usrData);
SharedPreferences.Editor prefEditor = getSharedPreferences(mypreference, Context.MODE_PRIVATE).edit();
String saveData = gson.toJson(userDataStore);
prefEditor.putString("userData", saveData);
prefEditor.apply();
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();`
SecondActivity.java
String mypreference="user_data";
SharedPreferences sPrefs= this.getSharedPreferences(mypreference, Context.MODE_PRIVATE);
DataStore dataPull=new DataStore();
Gson gson=new Gson();
String pull=sPrefs.getString("userData","");
dataPull=gson.fromJson(pull,DataStore.class);
System.out.println(dataPull.getDataStore().get(0).toString());
RecyclerView recyclerView=(RecyclerView)findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
MyRecyclerAdapter mAdapter=new MyRecyclerAdapter(dataPull);
recyclerView.setAdapter(mAdapter);
The problem with this code is the values entered are saved and persistent.But when i close,reopen the app and enter values the previous data gets override.

For Storing the value into SharedPreferences
SharedPreferences shared = getSharedPreferences("user_Info", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
editor.putString("key", value);
editor.commit();
For retrieving values from SharedPreferences just use this
SharedPreferences sharedPref = getSharedPreferences("user_Info", Context.MODE_PRIVATE);
String value = sharedPref.getString("key", "defaultValue");

If you want to store an ArrayList inside SharedPreferences, just convert it to a string. Then, you can "deconvert" it. E.G.
String toSave;
// Object is for your object type. Just get your objects converted to string, that's the point.
for(Object obj : arrayList){
toSave += obj.toString() + "\n";
}
SharedPreferences prefs = getSharedPreferences("PREFS_NAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("key", toSave);
editor.apply();
and...
SharedPreferences prefs = getSharedPreferences("PREFS_NAME",Context.MODE_PRIVATE);
String toGet = prefs.getString("key", "");
String[] parts = toGet.split("\n");
for(String s : parts){
arrayList.add(s); // or do whatever conversion you want to get your Object type
}

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

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.

Multiple SharedPreferences in an android app

SharedPreferences pref = getSharedPreferences("user1", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("firstName", firstnameString);
editor.commit();
SharedPreferences pref = getSharedPreferences("user2", Context.MODE_PRIVATE);
...
I am trying to create multiple sharedpreferences using the above code and trying to access all the sharedpreference names i.e user1,user2 etc using the code below.
But i am getting a NULLPointerException while accessing even though the sharedpreference is created.
Map<String,?> allsharedpref = pref.getAll();
if(allsharedpref!=null){
for(Map.Entry<String, ?> entry : allsharedpref.entrySet()){
Toast.makeText(this, entry.getKey()+"\n", Toast.LENGTH_LONG).show();
}
To get values from all SharedPreferences which you have created. you will need to read file names from shared_prefs :
File prefsdir = new File(getApplicationInfo().dataDir,"shared_prefs");
String[] list = prefsdir.list();
String[] preflist = new String[list.length()];
for(int i=0;i<list.length(),i++){
String preffile = list[i].substring(0, list[i].length()-4);
preflist[i]=preffile;
}
Now use preflist to get values from all SharedPreferences:
for(int index=0;index<preflist.length(),index++){
SharedPreferences spPref = getSharedPreferences(preflist[index], MODE_PRIVATE);
Map<String,?> allsharedpref = spPref.getAll();
if(allsharedpref!=null){
for(Map.Entry<String, ?> entry : allsharedpref.entrySet()){
Toast.makeText(this, entry.getKey()+"\n", Toast.LENGTH_LONG).show();
}
}
getSharedPreferences() can only be called after onCreate() has been called on an Activity.

Android Shared Preferences Won't Save

I'm trying out shared preferences, but I can't get my changes to save persistently.
SharedPreferences prefs;
SharedPreferences.Editor prefsEditor;
String lastPlayerPref = "LAST_PLAYER";
public void onCreate(Bundle savedInstanceState) {
prefs = this.getSharedPreferences("myPrefs", MODE_PRIVATE);
prefsEditor = prefs.edit();
String lastPlayer = prefs.getString(lastPlayerPref, "test");
System.err.println(lastPlayer); //always outputs "test" no matter what I do
prefsEditor.putString(lastPlayerPref, "me");
prefsEditor.commit();
...
}
When I run this initially, I would expect the output "test". When I run it after that, I expect it to output "me". But it always outputs "test". Isn't that argument just a default in the event that no preference has been saved?
Sorry for the confusion. Thanks!
I think you forgot to add .putString(lastPlayerPref, "player1");
prefs = ProgressBarActivity.this.getSharedPreferences("myPrefs", MODE_PRIVATE);
prefsEditor = prefs.edit().putString(lastPlayerPref, "player1");
prefsEditor.commit();
String lastPlayer = prefs.getString(lastPlayerPref, "test");
System.err.println(lastPlayer);
prefsEditor = prefs.edit().putString(lastPlayerPref, "player2");
prefsEditor.commit();
lastPlayer = prefs.getString(lastPlayerPref, "test");
System.err.println(lastPlayer);
if you try above you will see it will change

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