The question:
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";
The Solutions:
Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.
Method 1
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.
Method 2
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");
}
Method 3
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();
Method 4
Simple steps to save a String with SharedPreferences:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences prefs = this.getSharedPreferences("com.example.nec.myapplication", Context.MODE_PRIVATE);
prefs.edit().putString("userName", "NEC").apply();
String name = prefs.getString("userName", "");
Log.i("saved string", name);
}
Method 5
try it with context:
final SharedPreferences settings = context.getSharedPreferences(
PREFS_NAME, 0);
return settings.getString(key, null);
Method 6
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.
Method 7
The SharedPreferences class allows you to save preferences specific to an android Application.
API version 11 introduced methods putStringSet and getStringSet which allows the developer to store a list of string values and retrieve a list of string values, respectively.
An example of storing an array of strings using SharedPreferences can be done like so:
// Get the current list.
SharedPreferences settings = this.getSharedPreferences("YourActivityPreferences", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
Set<String> myStrings = settings.getStringSet("myStrings", new HashSet<String>());
// Add the new value.
myStrings.add("Another string");
// Save the list.
editor.putStringSet("myStrings", myStrings); editor.commit();
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0