Sharedpreference only saves latest string after app restart - android

I am currently trying to save chatnames locally but only the latest preference is saved. Below is how I'm saving the string to a specific key.
public void saveSettings(Context context, String key, String value){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(key, value).apply();
This is how I retrieve the string:
public String getString(Context context, String key, String defaultValue){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key,defaultValue);
}
The problem is that it will only return the last saved string, rest of the keys will return defaultvalue. E.g I'm saving 3 different strings with 3 different keys with the first method. When trying to retrieve the strings with getString()
It will only return the string for the last saved key.

Maybe i am wrong but , i can't see a commit here , on editor...

The way you formally save preferences is using the commit() method, like the following:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(key, value);
editor.commit();

Related

Android SharedPref not saving on restart

In my Android app I can display a popup when the app is updated (Based on versionCode). In the popup I have put a checkbox saying "dont show me again". When I click on that, it will save in the sharedpref the versionCode and wont display the popup anymore.
I have run against something odd behaviours where when I have saving the new Set<String>, it did indeed was saving it but when my app restarts the settings is lost.
Set<String> readAnnouncement = getReadAnnouncement(this);
readAnnouncement.add(String.valueOf(versionCode));
PreferenceManager.getDefaultSharedPreferences(this).edit().putStringSet(KEY_READ_ANN, readAnnouncement).apply();
If I break point on readAnnouncement.add, I can set for example the list having 2 items. When I execute the PreferenceManager.getDefaultSharedPrefer... and then execute getReadAnnouncement(this); the value is there, all good.
If I restart the app and check again getReadAnnouncement(this); the new value is gone.
By clearing the cache the problem disappeared... Why was is not saving? Is it possible the SharedPreference were full?
Try like this.
import android.content.Context;
import android.content.SharedPreferences;
/**
* #author VIVEK
* This class deals in with setting Cache value for complete app.
*/
public class SharedPrefUtil{
/*Set Boolean value in shared preferences */
public static void setSharedPref(Context context, String key, boolean value) {
// save token in preference
SharedPreferences sharedPreferences = context.getSharedPreferences("usb", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
/*get Boolean value in shared preferences */
public static boolean getSharedPref(Context context, String key, boolean defaultVal) {
boolean prefToken = defaultVal;
SharedPreferences sharedPreferences = context.getSharedPreferences("usb", 0);
prefToken = sharedPreferences.getBoolean(key, false);
return prefToken;
}
/*Set String value in shared preferences */
public static void setSharedPref(Context context, String key, String value) {
// save token in preference
SharedPreferences sharedPreferences = context.getSharedPreferences("usb", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
/*get String value in shared preferences */
public static String getSharedPref(Context context, String key, String defaultVal) {
String value = defaultVal;
SharedPreferences sharedPreferences = context.getSharedPreferences("usb", 0);
value = sharedPreferences.getString(key, defaultVal);
return value;
}
public static void cleanSharedPrefFile(Context context) {
// save token in preference
SharedPreferences sharedPreferences = context.getSharedPreferences("usb", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
}
} // End of main class over here ...
Now you want to set some value in Shared Pref then set like this
SharedPrefUtil.setSharedPref(MainActivity.this, "test", storeBuff);
Now when you need to get value from shared Pref then call like this
SharedPrefUtil.getSharedPref(MainActivity.this, "test", "default value");
In place of editor.commit() , use editor.apply()
BASICS:
getDefaultSharedPreferences() uses a default preference-file name. This default is set per application, so all activities in the same app context can access it easily as in the following example:
SharedPreferences spref = PreferenceManager.getDefaultSharedPreferences(this);
if (spref.contains("email")) {
String sEmailAddr = spref.getString("email", "");
}
The preferences are usually stored at /data/data/com.package.name/shared_prefs/com.package.name_preferences.xml
The alternative method - getSharedPreferences(name,mode) requires to indicate a specific preference (file) name and an operation mode (e.g. private, world_readable, etc.), which allow to have better access over your SharedPref file.

Declaring a android Global Variable that changes time to time

I am creating a location tracking application where I want the email-id of the logged in person as a global variable. As the email will keep changing depending on who logs in, i have a little confusion on how to go about with.
Thanku :)
Instead of creating Global variables please, Shared preferences and save them. Now, you can access them across the app or even after when user come back to app after closing App. Just as following :
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("email", test#gmail.com);
editor.commit();
//to read shared prefere
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
String defaultValue = "test#gmail.com"; //this is default email, so if you don't have values in preferences then it will be returned
String email= sharedPref.getString("email", defaultValue );
For details, Please follow Tutorial at: Official doc : SharedPreferences - Saving Key-Value Sets
As Kunu recomended, SharedPreferences are for these cases.
public static String PREFS_NAME = "loginDetails";
public static String LOGGED_EMAIL = "Email";
To edit your email:
public static void editEmail(String email)
{
Context context = getAppContext();
SharedPreferences.Editor editor = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit();
editor.putString(LOGGED_EMAIL , email);
editor.apply();
}
For more details about SharedPreferences check this answer.

How to use SharedPreference to save score and name in a game?

I am creating my first android app and I don’t have enough knowledge in programming unlike other here. So please help me with this matter. I want to save player’s name and score. I’ve searched and read a lot about SharedPreference but was unable to understand it very well especially when I am already applying the codes on my activity. I have tried it twice and everytime I run it, it shows”Not Responding” message and closes. But when the codes for sharedpreference are not indicated there it works fine. So here’s how I want to do with these. On the first game, the very first score should be saved after the time is over (the user will be typing their name and click save). So when another user or player plays the game the Top Score should be indicated in the screen using a textview, below this Top Score textview is the Current Score textview. If the Current Score is greater than the Top Score then it should overwrite the score. If not then the Top Score should stay the same. How can I achieve this?
P.S. I have 3 different activities that needs this SharedPreferences but with the same functionalities. Thanks in advance. And please explain it more clearly (coz sometimes I can’t understand some words) thank you :)
This is the code i use, i put it in Oncreate
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("name", name);
editor.putInt("score", score);
editor.commit();
I think following link will surely help you out SharedPreferences Explained in detail
.
Try this
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sp.edit();
editor.putString(key, value); //similar way you can push integer values
editor.commit();
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
sp.getString(key, null); //default value will be null in this case, if there is no such key
You can write a Utility class to reuse this methods wher you want. like below
public class PreferenceUtility {
public static void saveString(Activity activity, String key, String value){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(activity.getApplicationContext());
SharedPreferences.Editor editor = sp.edit();
editor.putString(key, value);
editor.commit();
}
public static String readString(Activity activity, String key, String defaultValue){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(activity.getApplicationContext());
return sp.getString(key, defaultValue);
}
}
static SharedPreferences sh_Pref;
public static String Preference_Name = "AppData";
public static String getPreference(String key, String Default,
Activity activity)
{
sh_Pref = activity.getSharedPreferences(Preference_Name, Context.MODE_PRIVATE);
return sh_Pref.getString(key, Default);
}
public static void setPreference(String key, String value, Activity activity)
{
if (value != null)
{
sh_Pref = activity.getSharedPreferences(Preference_Name, Context.MODE_PRIVATE);
Editor editor = sh_Pref.edit();
editor.putString(key, value);
editor.commit();
}
}
}
** Here a set and get value from SharedPreferences**

sharedPreferences in Fragment

I know this has been asked before, but i can't seem to figure it out
i am trying to get my preferences by this:
SharedPreferences preferences = this.getActivity().getSharedPreferences("storedName", Context.MODE_PRIVATE);
String loginemail = preferences.getString("storedName", "");
but this doesn't seem to work, i have multiple sharedPreferences which i need to get in my fragment what is the correct way to do it?
As getDefaulSharedPreferences(this) doesn't work.
i store my prefs like so:
savePreferences("shareUniqePass", uniqePassIds.getText().toString());
savePreferences("storedName", inputEmail.getText().toString());
savePreferences("Storedpass", inputPassword.getText().toString());
private void savePreferences(String key, boolean value){
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor checkbox = sharedPreferences.edit();
checkbox.putBoolean(key, value);
checkbox.commit();
}
private void savePreferences(String key, String value){
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor names = sharedPreferences.edit();
names.putString(key, value);
names.commit();
}
Instead of getting it from getSharedPreferences use the getDefaultSharedPreferences.
As getDefaulSharedPreferences(this) doesn't work.
You used getDefaultSharedPreferences for saving the data and therefore you must use getDefaultSharedPreferences to get the data that was saved.
this mean the instance of your fragment instead use the getActivity() to get the instance of context from your activity.
sample:
String loginemail = PreferenceManager.getDefaultSharedPreferences(getActivity()).getString(PREF_USER_NAME, "");;
You need to make sure that your saving and loading the data from the same shared preferences. If you're only accessing it from the one activity / fragment, you should use getDefaulSharedPreferences(this).
If, however, you're going to use it from several different activities / fragments, you should use:
private void savePreferences(String key, boolean value){
SharedPreferences prefs = getActivity().getSharedPreferences("storedName", Context.MODE_PRIVATE);
Editor checkbox = sharedPreferences.edit();
checkbox.putBoolean(key, value);
checkbox.commit();
}

Android - How Do I Set A Preference In Code

I have an Android application in which I have my preferences in an XML file, which works fine. I now want to set one of the preferences using code instead of displaying the entire preference screen, how would I go about doing this?
I assume by preferences you are referring to your application's preferences and not Android phone settings.
To store preferences between runs of you application you need to do the following
Create a SharedPreferences object
SharedPreferences settings = getSharedPreferences(String n, MODE_PRIVATE);
String n identifies your preferences and the second argument is the mode they'll be accessed
Instantiate an Editor object
SharedPreferences.Editor editor = settings.edit();
Note: do not try settings.editor.edit(), this will not make a persistent object and the code below will not work
Write your preferences to the buffer
editor.put...(String, value)
There are numerous put function, putString, putBoolean, etc. The String is the key ("version", "good run") and the value is the value ("1.5.2", true)
Flush the buffer
editor.commit();
This actually writes you put to the preferences. If your app crashes before this line then the preferences will not be written. There is also a documented bug: commit() is supposed to return a boolean indicating success or failure. Last I checked it always returned false.
These preferences will by stored on the phone and will only be accessible to your application.
More documentation is here
I tried this but didn't work:
SharedPreferences settings = getSharedPreferences(String n, MODE_PRIVATE);
Try this instead:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
You can save something in the sharedpreferences by using below code
public static void save(String valueKey, String value) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
SharedPreferences.Editor edit = prefs.edit();
edit.putString(valueKey, value);
edit.commit();
}
To read preferences:
public static String read(String valueKey, String valueDefault) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
return prefs.getString(valueKey, valueDefault);
}

Categories

Resources