how to append data in Shared Preference in Android - android

I tried to append the data in shared preference file by using
SharedPreferences sharedPreferences = getSharedPreferences("myData", MODE_APPEND);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("name", userName.getText().toString());
editor.putString("password", password.getText().toString());
editor.commit();
But I found that new value overwrites the old value. Will you help me to fix this issue?

MODE_APPEND doesn't mean that you add multiple values for each key. It means that if the file already exists it is appended to and not erased . We usually used MODE_PRIVATE.
As for saving multiple names and passwords, you can take a look at putStringSet(string key Set<String> values Method.
You can save the for each key a set of string values. You can separate the username and password by some special character or string. You may even serialize an object to json.
So basically what you need to do is:
Get the list of values from Shared Preferences
Append the current value to the list.
Save the List back to Shared Preferences.

Related

SharedPreferences saving string [duplicate]

This question already has answers here:
Shared preferences for creating one time activity
(14 answers)
Closed 4 years ago.
I read about SharedPreferences but did not understand where i need to put the saving data and where to put the get objects.
In my app i get the full name when i open it in the first time by dialog.
I need to save the full name for ever (until the user will delete the app or something).
Where and what should i write to save the data(in onDestroy)?
Like :
// Create object of SharedPreferences.
SharedPreferences sharedPref= getSharedPreferences("mypref", 0);
//now get Editor
SharedPreferences.Editor editor= sharedPref.edit();
//put your value
editor.putString("name", strName);
editor.commit();
SharedPreferences sharedPref= getSharedPreferences("mypref", 0);
String name = sharedPref.getString("name", "");
And where and what should i write to get the data(in onCreate)?
You don't have to to anything in onDestroy(). If your app gets uninstalled your data in shared preferences will be removed as well.
editor.putString("name", strName);
The first parameter is the key and the second one ist the value.
if you want to save the user's name, you pass the first parameter "name" and for the second parameter, the user's name.
when you want to read the user's name later you use
String name = sharedPref.getString("name", "");
Again, the first parameter is the key. You want to read the user's name so you use "name" and the second parameter is the default value, if there hasn't been saved a value, yet.

Android, SharedPreferences default values not set if there is no pref

String getString(String name, String defValue){...}
This is the definition of getString(...) method of SharedPreferences so I think it's possible if I run code below, it returns 1 two times:
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
Timber.e(pref.getString("new", "1"));
Timber.e(pref.getString("new", "100"));
because at the first time its empty, so "1" will store, after that because of it has value ("1"), it will return it's value ("1") not default value ("100")
but it returns "1" and "100" and "new" does not store in my pref file (located in data/data/...)
Am I understanding it wrong or something goes wrong in this code?
Use can only get The data using getString.
to store data use Editor.commit();
Editor editor = settings.edit();
editor.putString("someKey", "someVal");
editor.commit();
only after that you can get this value.
String value = settings.getString("someKey", "someDefaultValueIfThisKeyNotUsedBefore");
In this example, you will recieve "someVal" if commit is used beforehand.
You must put"Something" to SharedPreferences.Editor, and commit them.
pref.getString wont store anything.
Refer to the links below:
https://developer.android.com/reference/android/content/SharedPreferences.html
https://developer.android.com/reference/android/content/SharedPreferences.Editor.html

Android> file vs SQLite

I have to save my application's settings, but I don't know if I should use a file or a table. I don't need to share them with other application and these settings are just 3-4 booleans used to remember the application to execute an action in a way or in another one. Is it a good idea to create a table just for 3-4 values? Or should I use a file instead small?
If its a question of storing the 3-4 values in application then i would suggest to use the SharedPreference.
You can store and retrieve the Sharedpreferences as below:
Application shared preferences can be fetched using getSharedPreferences() method.The following code can be used to get application shared preferences.
SharedPreferences pref = getApplicationContext().getSharedPreferences(
"any_prefname", MODE_PRIVATE);
Available mode for shared preference:
MODE_WORLD_READABLE
MODE_WORLD_WRITEABLE
MODE_PRIVATE
To edit sharedpreference value, we need editor to edit and save the changes in shared preferences.
Editor editor = pref.edit();
and to save data commit() is used.
Editor.commit();
You can save data into shared preferences using editor. All the primitive data types like booleans, floats, ints, longs, and strings are supported. Call editor.commit() in order to save changes to shared preferences.
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.putInt("key_name", "int value"); // Storing integer
editor.putFloat("key_name", "float value"); // Storing float
editor.putLong("key_name", "long value"); // Storing long
editor.commit(); // commit changes
Get data from Shared Preference:
Data can be retrived from saved preferences by calling getString() (For string) method.For boolean getBoolean() Remember this method should be called on Shared Preferences not on Editor.
// returns stored preference value
// If value is not present return second param value - In this case null
pref.getString("key_name", null); // getting String
pref.getInt("key_name", null); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean
Delete data from shared preference and delete sharedpreference:
To delete data from shared preferences we can use remove(“key_name”).If we want to delete all the data, call clear()
editor.remove("student_name");//will delete student_name
editor.commit();
Following will clear all the data from shared preferences
editor.clear();
editor.commit();
You will get the details here -http://developer.android.com/guide/topics/data/data-storage.html
Use sharedPref to save the app settings instead of file and sqLite.

Does SharedPreferences work in Eclipse emulator?

I am attempting to save a user id using SharedPreferences. Do values saved as SharePreferences persist across all Activities in my application so I can access the userid from any application? Below is my code for saving the userid.
userid = result.substring(3, result.length());
Log.d("userid at onpostexecute", userid);
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit(); // to update userid
editor.putString("userid", userid);
editor.commit();
And here is the code for accessing the userid from the SharedPreferences in another activity.
SharedPreferences prefs = getPreferences(MODE_PRIVATE); // to access userid
String userid = prefs.getString("userid", "");
Log.d("shared prefs userid", userid);
What is strange is that the above code is in my onCreate method but it doesn't show up in the Logcat even though other log data is displayed before and after this code. So is there something wrong with my code that I can't even get it to display in my logcat? I can't even tell if it is being updated.
Values saved as sharedPreferences can be shared between activities if you tell it to. Right now you are creating a preference that is only accessible to that same activity. You need to use:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
Like this you are creating a sharedPreference between your application. There is a lot of explanation on the topic in the accepted answer to another question. Link to question
As discussed in the answer the way you are using to save the preference will only work in the same activity that saved it.
I assume you mean can you access them from any Activity, yes, they do persist even when you leave your app and come back. From the Docs
The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).
If this Log.d("userid at onpostexecute", userid); doesn't even show up then I would put a breakpoint there and make sure you have a value for userid. I would also check your logcat filters to make sure that you are getting all logs. Just make sure that the type in the spinner is set to "verbose" just to be sure

Store Arraylist of custom objects

I have saved ArrayList of custom objects in the shared preferences like this:
SharedPreferences prefs = context.getSharedPreferences("prefName", Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putStringSet("myList", new Gson().toJson(arraylist).toString());
editor.apply();
By doing this, once values are saved but when i exit from the app and relaunch and try to save new values then the old values are gone.
Any idea how can i save old values and append new ones?
I want to keep all values in the same array and keep array saved to show values every time when the app loads.
Read myList from prefName, append arraylist to what was already saved in the preferences, write back myList to preferences.
This code may be work for you.
SharedPreferences setting=context.getSharedPreferences("prefName", Activity.MODE_PRIVATE);
SharedPreferences.Editor edit=setting.edit();
edit.putStringSet("myList", new Gson().toJson(arraylist).toString());
edit.commit();
I hav faced this problem earlier... Use generics it will append the value rather than replacing the old datas....

Categories

Resources