【问题标题】:how save sharedpreferences in array如何将共享首选项保存在数组中
【发布时间】:2018-04-15 04:23:16
【问题描述】:

如何将共享首选项保存到数组中,我尝试了几件事,但我做不到,我想将特定键保存到数组中,然后将它们放入文本视图中,然后它就崩溃了. 请大家帮忙。

public String[] fetchAllPreference(){
    SharedPreferences sharedPref = getSharedPreferences("DictionaryInfo", 
    Context.MODE_PRIVATE);
    //here i want the code of making it into array come
    return values;
}
public void loadPicture()
{
    gallery.removeAllViews();
    String[] array =fetchAllPreference();
    for(int i=0;i<array.length;i++)
    {
        TextView iv = new TextView(this);
        LinearLayout.LayoutParams layoutParams=new 
        LinearLayout.LayoutParams(100,100);
        layoutParams.setMargins(10,10,0,0);
        iv.setLayoutParams(layoutParams);
        iv.setText(array[i].toString());
        gallery.addView(iv);
    }
}

【问题讨论】:

标签: android arrays sharedpreferences


【解决方案1】:

我认为你想要的是将 sharedpreference 中的值保存到数组中,在这种情况下

SharedPreferences prefs = getSharedPreferences("myFavs", 0);
    Map<String, String> m = (Map<String, String>) prefs.getAll();

可以将地图转换为集合 (https://developer.android.com/reference/java/util/Map.html) 并且集合可以转换为数组 (https://developer.android.com/reference/java/util/Collection.html)

请看这个,看起来很相似

Getting shared preferences and displaying them in a listview

【讨论】:

    【解决方案2】:

    我知道这不是确切的答案,但可以保存数组的每个元素,索引是关键字或索引与某个字符串是关键字相关联。

    【讨论】:

    • 是的,我知道,已经保存,现在我想将它们放入数组中。
    • 您是否尝试过使用循环将元素放入数组中,当键为 index 时,并使用 getString(String key, String defValue) 将它们复制到 array[index]
    猜你喜欢
    • 1970-01-01
    • 2013-07-27
    • 1970-01-01
    • 1970-01-01
    • 2011-12-18
    • 1970-01-01
    • 2017-04-26
    • 2017-08-19
    • 2020-06-30
    相关资源
    最近更新 更多