Android - Storing/retrieving strings with shared preferences

shared preference login example in android
how to get data from shared preference in android
shared preference in android kotlin example
how to use shared preference in android between activities
where shared preferences are stored in android
android login with database using shared preferences
how to store multiple values in sharedpreferences in android
sharedpreferences deprecated

As the title says, I want to save and retrieve certain strings. But my code won't pass through the first line neither in retrieve or store. I tried to follow this link: http://developer.android.com/guide/topics/data/data-storage.html

private void savepath(String pathtilsave, int i) {
    String tal = null;
    // doesn't go past the line below
    SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
    tal = String.valueOf(i);
    editor.putString(tal, pathtilsave);
    editor.commit();
}

and my retrieve method:

public void getpaths() {
    String tal = null;
    // doesn't go past the line below
    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    for (int i = 1; i <= lydliste.length - 1; i++) {
        tal = String.valueOf(i);
        String restoredText = settings.getString(tal, null);
        if (restoredText != null) {
            lydliste[i] = restoredText;
        }
    }
}

lydliste is a static string array. PREFS_NAME is

public static final String PREFS_NAME = "MyPrefsFile";

To save to preferences:

PreferenceManager.getDefaultSharedPreferences(context).edit().putString("MYLABEL", "myStringToSave").apply();  

To get a stored preference:

PreferenceManager.getDefaultSharedPreferences(context).getString("MYLABEL", "defaultStringIfNothingFound"); 

Where context is your Context.


If you are getting multiple values, it may be more efficient to reuse the same instance.

 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
 String myStrValue = prefs.getString("MYSTRLABEL", "defaultStringIfNothingFound");
 Boolean myBoolValue = prefs.getBoolean("MYBOOLLABEL", false);
 int myIntValue = prefs.getInt("MYINTLABEL", 1);

And if you are saving multiple values:

Editor prefEditor = PreferenceManager.getDefaultSharedPreferences(context).edit();
prefEditor.putString("MYSTRLABEL", "myStringToSave");
prefEditor.putBoolean("MYBOOLLABEL", true);
prefEditor.putInt("MYINTLABEL", 99);
prefEditor.apply();  

Note: Saving with apply() is better than using commit(). The only time you need commit() is if you require the return value, which is very rare.

Save key-value data, Interface used for modifying values in a SharedPreferences object. interface Retrieve a set of String values from the preferences. abstract void of its contents. The consistency of your stored data is not guaranteed if you do. Storing and Retrieving Data Using Shared Preferences | in this tutorial, we will learn how to store and retrieve data using Shared Preferences in android.. The primary purpose of using Shared Preferences in android is to store user specific details, such as user specific settings (eg: – username), when a user logged into the application.

private static final String PREFS_NAME = "preferenceName";

public static boolean setPreference(Context context, String key, String value) {
    SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = settings.edit();
    editor.putString(key, value);
    return editor.commit();
}

public static String getPreference(Context context, String key) {
    SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    return settings.getString(key, "defaultValue");
}

SharedPreferences, In order to store data to the SharedPreferences you need to first instantiate an The string Settings is the name of the preference file you wish to access. Once you have stored some data to your SharedPrefrences you may retrieve this value​  Android provides many ways of storing data of an application. One of this way is called Shared Preferences. Shared Preferences allow you to save and retrieve data in the form of key,value pair. In order to use shared preferences, you have to call a method getSharedPreferences() that returns a SharedPreference instance

I solved it! It didn't work when I called the methods from within the class! I had to call it from another class for some reason, and write "classname.this" as Context parameter. Here's the final working:

SharedPreferences settings = ctx.getSharedPreferences(PREFS_NAME, 0);
    settings = ctx.getSharedPreferences(PREFS_NAME, 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putString(tal, pathtilsave);
     editor.commit(); 

Storing and Accessing SharedPreferences, It's a good practice to store these key strings in strings.xml of your app and retrieve them using getString(R.string. How to use Shared Preferences to save more than one values | in this tutorial, we will learn how to store and retrieve multiple values using Shared Preferences in android. I have already discussed Storing and Retrieving data Using Shared Preferences tutorial for storing and retrieving single value using Shared Preference in android.

If you do not care about the return value of commit() better use apply() as it being asynchronous is faster that commit().

final SharedPreferences prefs =  context.getSharedPreferences("PREFERENCE_NAME",
                Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("key", "value");
editor.apply();

As per docs

Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on this SharedPreferences does a regular commit() while a apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself.

Using Shared Preferences to save data locally in Android, 1 Android Shared Preferences Overview; 2 Initialization; 3 Storing Data; 4 Retrieving Data; 5 Clearing getSharedPreferences (String PREFS_NAME, int mode) Data can be retrieved from saved preferences by calling getString() as follows:. Shared Preferences allows activities and applications to keep preferences, in the form of key-value pairs similar to a Map that will persist even when the user closes the application. Android stores Shared Preferences settings as XML file in shared_prefs folder under DATA/data/{application package} directory.

try it with context:

final SharedPreferences settings = context.getSharedPreferences(
            PREFS_NAME, 0);

return settings.getString(key, null);

Android Shared Preferences Example Tutorial, SharedPreferences class allows you to save and retrieve primitive data instance of SharedPreferences use the getSharedPreferences(String,  In this Android tutorial we are going to see how to use Android SharedPreferences class to store and retrieve application specific persistent data. Android SharedPreferences Tutorial. Android SharedPreferences allows us to store private primitive application data in the form of key-value pair.

Writing and Reading from SharedPreferences – Android Research , Shared Preferences is the way in which one can store and retrieve small The data stored using shared preferences are kept private within the scope of the public abstract SharedPreferences getSharedPreferences (String name, int mode​). With the SharedPreference instance one can retrieve the int value of the any preference with the getInt(String key, int defVal). The preference we are interested in this case is counter . In our case, we can modify the SharedPreference instance in our case using the edit() and use the putInt(String key,

Shared Preferences in Android with Examples, For saving and retrieving an array: ArrayList<String> mOrderList = new ArrayList<​String>();Preferences.setArrayPrefs("OrderList",mOrderList,context); The Developer Preview for Android 11 is now available; test it out and share your feedback . If you have a relatively small collection of key-values that you'd like to save, you should use the SharedPreferences APIs. A SharedPreferences object points to a file containing key-value pairs and provides simple methods to read and write them.

Using Shared Preferences for Strings & Arrays in Android the easy , Shared Preferences is one of data storage options provided by Android. It allows Android developers to Here, I've shown how to insert and retrieve a String. One of the most Interesting Data Storage option Android provides its users is Shared Preferences. Shared Preferences is the way in which one can store and retrieve small amounts of primitive data as key/value pairs to a file on the device storage such as String, int, float, Boolean that make up your preferences in an XML file inside the app on the device storage.

Comments
  • Look at this . stackoverflow.com/a/11894634/614807
  • There is a nice library which saves you some boilercode, if you only store and restore the values in one particular activity
  • Use apply() instead; commit() is synchronous, whereas apply() is asynchronous. apply() will handle in the background.
  • @dinosaur You Can probably just replace context with getBaseContext() or similar methods if within an activity. If your within some object class, You probably initialised it with content parameter, in which you can declare it as a global varialble on creation and use it here.
  • Hmm. There's apparently something I'm just not getting. I've tried to write: PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit().putString(tal, pathtilsave).commit(); and I've tried to change my method to: private void savepath(Context context, String pathtilsave, int i) with context being "this" as parameter. Still doesn't work. Doing it wrong?
  • @dinosaur How far does it get? Are you sure this pathtilsave isnt null? Try hardcoding the variables like in my example, and see if it works. If it does, it must be your parameters.
  • img1.uploadscreenshot.com/images/main/8/23400324057.jpg If I debug further it'll crash and write: img1.uploadscreenshot.com/images/main/8/23400333032.jpg I'm pretty new at this, so sorry if I'm missing something essential.
  • Nope. Same thing happened again. It's alright. Gonna try some of the other suggestions and see if that works. Your help was really appreciated.
  • SharedPreferences settings = c.getSharedPreferences(PREFS_NAME, 0); settings = c.getSharedPreferences(PREFS_NAME, 0); Isn't the second line redundant? BTW , I edited it now
  • @eRaisedToX you're absolutely correct. Your edit was somehow rejected, so I went ahead and edited the answer myself, and made some more improvements.
  • this seem to work for the retrieve-part, but it's kinda hard to know for sure since i haven't stored anything. still having trouble with storing-part. thanks for this though!
  • how then do you set it to a Textview using setText(); ??