【问题标题】:Shared Preferences for ArraylistArraylist 的共享首选项
【发布时间】:2015-09-20 13:44:36
【问题描述】:

我在一个数组列表中有一堆字符串。

我想将一些字符串保存在共享首选项中。

如果用户选择索引为 3 的字符串,我想将该特定字符串存储在共享首选项中。

有可能吗?

请告诉我。

【问题讨论】:

标签: android arraylist sharedpreferences


【解决方案1】:

希望这段代码能帮助你理解

int id = selectedItemNum;

ArrayList<String> list = new ArrayList<String>();
list.add("Item1");
list.add("Item2");
list.add("Item3");
list.add("Item4");
String selectedString = list.get(id);

String APP_PREFERENCES = "savedStrings"; 
SharedPreferences mySharedPreferences = getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE);
Editor editor = mySharedPreferences.edit();
editor.putString("savedString"+id, selectedString);
editor.apply();

【讨论】:

    【解决方案2】:

    要将数据保存到 SharedPreferences:

        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    
       for(int i=0; i<arraylist.size(); i++){
          sharedPreferences.edit().putString("TAG" +  Integer.toString(i)
                                             ,arraylist.get(i)).apply();
        }
    

    从 SharedPreferences 获取数据:

       sharedPreferences.getString("TAG" + "x", null); x is a number position in array list
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-02
      • 2015-11-29
      • 2013-07-27
      • 1970-01-01
      • 2016-04-04
      • 1970-01-01
      相关资源
      最近更新 更多