【问题标题】:Gather all Strings from SharedPreference getAll() Method?从 SharedPreference getAll() 方法收集所有字符串?
【发布时间】:2014-09-03 07:58:44
【问题描述】:

我试图弄清楚如何使用 getAll() 方法从我的应用程序的 SharedPreferences 中设置每个字符串和键名称,以便我可以使用这些值来命名填充按钮并将这些按钮分配给访问 sharedpreferences 中的正确字符串在文本视图中显示。

问题是我不知道如何将这些值保存到字符串或字符串数​​组,因为我以前从未处理过地图。

如果有人可以帮助我将我的 SharedPreferences 键和字符串值存储到一个字符串数组中以便在我的片段中使用,那将不胜感激。

这是我目前所拥有的:

String[] arrayToStoreStrings;

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    SharedPreferences sp = (SharedPreferences) MadlibsSaved.this.getActivity();
    Map<String,?> keys = sp.getAll();

    for(Map.Entry<String,?> entry : keys.entrySet()){
        Log.d("map values",entry.getKey() + ": " + 
                               entry.getValue().toString());            
}

更加努力地更新但仍然出现错误:

BootstrapButton[] loadButtons;

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    SharedPreferences sp = null;
    Map<String,?> keys = sp.MadlibsSaved.this.getActivity().getAll();

    for(Map.Entry<String,?> entry : keys.entrySet()){
        Log.d("map values",entry.getKey() + ": " + 
                               entry.getValue().toString());

        while(!(values[i].matches(null))){
            values[i] = entry.getValue().toString();
            i++;
        }
        while(!(key[i].matches(null))){
            key[i] = entry.getKey().toString();
            i++;
        }

 }

    loadButtons = new BootstrapButton[20];

    loadButtons[0] = new BootstrapButton(getActivity());
    loadButtons[0].setText(values[i]);

【问题讨论】:

    标签: android string map fragment sharedpreferences


    【解决方案1】:

    如果你只想要字符串值:

    ArrayList<String> strings = new ArrayList<String>();
    for(Map.Entry<String,?> entry : keys.entrySet()){
        if (entry.getValue() instanceof String) {
            strings.add((String) entry.getValue());
        }
    }
    arrayToStoreStrings = strings.toArray(new String[strings.size()]);
    

    如果您想将每个值转换为字符串

    ArrayList<String> strings = new ArrayList<String>();
    for(Map.Entry<String,?> entry : keys.entrySet()){
        strings.add(entry.getValue().toString());
    }
    arrayToStoreStrings = strings.toArray(new String[strings.size()]);
    

    您可以对单独数组中的映射键(而不是映射值)执行类似的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-20
      • 1970-01-01
      • 2016-08-29
      • 2016-05-15
      • 1970-01-01
      相关资源
      最近更新 更多