Android - 使用共享首选项存储/检索字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12074156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 09:40:01  来源:igfitidea点击:

Android - Storing/retrieving strings with shared preferences

androidsharedpreferences

提问by Rad

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

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

lydliste 是一个静态字符串数组。PREFS_NAME

public static final String PREFS_NAME = "MyPrefsFile";

采纳答案by Rad

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:

我解决了!当我从类中调用方法时,它不起作用!由于某种原因,我不得不从另一个类调用它,并将“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(); 

回答by Doomsknight

To save to preferences:

要保存到首选项:

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

To get a stored preference:

要获取存储的首选项:

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

Where contextis your Context.

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.

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

回答by Benito Bertoli

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

回答by Stefan Beike

try it with context:

尝试使用上下文:

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

return settings.getString(key, null);

回答by Aniket Thakur

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

如果你不关心 commit() 的返回值,最好使用 apply() 因为它是异步的,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.

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

回答by NEC

Simple steps to save a String with SharedPreferences:

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

回答by Jabbir Basha

The SharedPreferences class allows you to save preferences specific to an android Application.

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

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.

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

An example of storing an array of strings using SharedPreferences can be done like so:

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