Android - 存储/检索具有共享首选项的字符串

问题描述 投票:39回答:7

正如标题所说,我想保存并检索某些字符串。但我的代码不会在检索或存储中通过第一行。我试着按照这个链接: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();
}

和我的检索方法:

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是一个静态字符串数组。 PREFS_NAME

public static final String PREFS_NAME = "MyPrefsFile";
android sharedpreferences
7个回答
80
投票

要保存到首选项:

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

要获得存储的首选项:

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

context是你的背景。


如果您获得多个值,则重用相同实例可能更有效。

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

如果您要保存多个值:

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

注意:使用apply()保存比使用commit()更好。你需要commit()的唯一时间是你需要返回值,这是非常罕见的。


8
投票
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");
}

4
投票

我解决了!当我在课堂上调用这些方法时,它不起作用!我不得不出于某种原因从另一个类调用它,并将“classname.this”写为Context参数。这是最后的工作:

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

3
投票

如果你不关心commit()的返回值,最好使用apply(),因为异步比commit()更快。

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

根据docs

与commit()同步地将其首选项写入持久存储,apply()会立即将其更改提交到内存中的SharedPreferences,但会启动异步提交到磁盘,并且不会通知您任何失败。如果此SharedPreferences上的另一个编辑器在apply()尚未完成时执行常规commit(),则commit()将阻塞,直到完成所有异步提交以及提交本身。


2
投票

尝试上下文:

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

return settings.getString(key, null);

1
投票

使用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);
}

0
投票

SharedPreferences类允许您保存特定于Android应用程序的首选项。

API版本11引入了方法putStringSet和getStringSet,它们允许开发人员分别存储字符串值列表并检索字符串值列表。

使用SharedPreferences存储字符串数组的示例可以这样完成:

// 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();
© www.soinside.com 2019 - 2024. All rights reserved.