首页 > 解决方案 > 如何在 Listview android 中显示 sharepreferences 项

问题描述

我只想检索从 sharedpreferences 中保存的数据并将其显示在列表视图中。目前我只设法在我的 SecondActivity 中显示只有一行的数据。我想要的是在列表视图中分别显示这些数据,有没有专家如何解决这个问题提前谢谢

从 sharedpref 中检索数据

我的共享偏好

我的共享偏好

MainActivity 保存 sharedpref

public void save_append_list_tosharefpref (String data){

    List<String> favorites = new ArrayList<String>();
    SharedPreferences settings;
    SharedPreferences.Editor editor;
    settings =   PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    editor = settings.edit();

    Map<String, ?> allPrefs = settings.getAll(); //my existing sharedPreference
    Set<String> set = allPrefs.keySet();

    if (allPrefs.toString() =="{}" || allPrefs.toString() =="[]"){
        favorites.add(data);
    }
    else {
        for(String s : set){
            favorites.add(data);
            favorites.add(allPrefs.get(s).toString());
            Log.d(TAG,"bagona"+allPrefs.get(s).toString());
        }

    }
    editor.putString(FAVORITES, favorites.toString());
    editor.commit();
}

第二活动

public void view_from_shared_preferences(){
    SharedPreferences settings;
    SharedPreferences.Editor editor;
    settings =   PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    editor = settings.edit();

    Map<String, ?> allPrefs = settings.getAll(); //your sharedPreference
    Set<String> set = allPrefs.keySet();

    for(String s : set){
        Log.d(TAG,"This is all data "+allPrefs.get(s).toString());

        String rep =allPrefs.get(s).toString();
        String seps = rep.replace("]", "");
        String seps1 = seps.replace("[", "");
        Log.d(TAG,"final data "+seps1);
        arrayAdapter.add(seps1);



    }
}

标签: android

解决方案


得到字符串后,使用

List<String> elephantList = Arrays.asList(str.split(","));

获取 ArrayList 并使用它来设置 listview


推荐阅读