【问题标题】:Android - Storing/retrieving strings with shared preferencesAndroid - 使用共享首选项存储/检索字符串
【发布时间】:2012-08-22 13:22:01
【问题描述】:

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

【问题讨论】:

  • 有一个不错的library,如果您只存储和恢复一个特定活动中的值,它可以为您节省一些锅炉代码
  • 使用 apply() 代替; commit() 是同步的,而 apply() 是异步的。 apply() 将在后台处理。

标签: android sharedpreferences


【解决方案1】:

保存到首选项:

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() 的时候是需要返回值,这种情况非常少见。

【讨论】:

  • @dinosaur 如果在活动中,您可能只需将context 替换为getBaseContext() 或类似方法。如果您在某个对象类中,您可能使用content 参数对其进行了初始化,您可以在其中将其声明为创建时的全局变量并在此处使用它。
  • 嗯。显然有些东西我只是没有得到。我试过写: PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit().putString(tal, pathtilsave).commit();并且我尝试将我的方法更改为: private void savepath(Context context, String pathtilsave, int i) 上下文为“this”作为参数。还是不行。做错了吗?
  • @dinosaur 能走多远?你确定这个pathtilsave 不是空的吗?尝试像我的示例中那样对变量进行硬编码,看看它是否有效。如果是,那它一定是你的参数。
  • 不。同样的事情又发生了。没关系。将尝试其他一些建议,看看是否有效。非常感谢您的帮助。
【解决方案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");
}

【讨论】:

  • SharedPreferences settings = c.getSharedPreferences(PREFS_NAME, 0); settings = c.getSharedPreferences(PREFS_NAME, 0); 第二行不是多余的吗?顺便说一句,我现在编辑了它
  • @eRaisedToX 你是绝对正确的。您的编辑不知何故被拒绝了,所以我继续自己编辑了答案,并进行了更多改进。
【解决方案3】:

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

【讨论】:

    【解决方案4】:

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

    【讨论】:

      【解决方案5】:

      结合上下文试试:

      final SharedPreferences settings = context.getSharedPreferences(
                  PREFS_NAME, 0);
      
      return settings.getString(key, null);
      

      【讨论】:

      • 这似乎适用于检索部分,但由于我没有存储任何东西,所以很难确定。存储部分仍然有问题。不过谢谢你!
      【解决方案6】:

      如果你不关心 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() 将阻塞,直到所有异步提交以及提交本身都完成。

      【讨论】:

        【解决方案7】:

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

        【讨论】:

        • 那么如何使用 setText() 将其设置为 Textview; ??
        猜你喜欢
        • 2019-12-17
        • 2017-07-29
        • 1970-01-01
        • 2021-11-08
        • 1970-01-01
        • 1970-01-01
        • 2023-03-12
        • 1970-01-01
        • 2015-06-11
        相关资源
        最近更新 更多