Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
853 views
in Technique[技术] by (71.8m points)

sharedpreferences - Android - Storing/retrieving strings with shared preferences

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";
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...