在共享偏好中保存arraylist

时间:2015-08-13 10:41:21

标签: android android-fragments arraylist sharedpreferences bundle

我正在JSONArray array = moduleObject.specialForcedConf; // array = [{"deadlines":[{"start":1439539200,"end":1439542800},{"start":1440144000,"end":1440147600},{"start":0,"end":0}]}] JSONArray jArray = array.getJSONObject(0).getJSONArray("deadlines"); for (int i = 0; i < jArray.length(); i++) // assuming your array is jArray { try { JSONObject obj = jArray.getJSONObject(i); String start= obj.getString("start"); // store in an ArrayList String end = obj.getString("end"); //// store in an ArrayList } catch (JSONException e) { // Error } } 存储值并将其传递给使用捆绑到下一个ArrayList,然后我将值设置为Fragment,直到此处它正常工作,现在去另一个页面然后继续访问应用并再次返回到TextView,我的所有数据都会显示,所以我尝试将其存储在偏好设置中,但偏好设置不允许访问Fragment,以下是我的代码

ArrayList

5 个答案:

答案 0 :(得分:3)

在共享偏好中存储和检索arraylist的完整示例:http://blog.nkdroidsolutions.com/arraylist-in-sharedpreferences/

  public void storeFavorites(Context context, List favorites) {
    // used for store arrayList in json format
            SharedPreferences settings;
            Editor editor;
            settings = context.getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
            editor = settings.edit();
            Gson gson = new Gson();
            String jsonFavorites = gson.toJson(favorites);
            editor.putString(FAVORITES, jsonFavorites);
            editor.commit();
        }


        public ArrayList loadFavorites(Context context) {
    // used for retrieving arraylist from json formatted string
            SharedPreferences settings;
            List favorites;
            settings = context.getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
            if (settings.contains(FAVORITES)) {
                String jsonFavorites = settings.getString(FAVORITES, null);
                Gson gson = new Gson();
                BeanSampleList[] favoriteItems = gson.fromJson(jsonFavorites,BeanSampleList[].class);
                favorites = Arrays.asList(favoriteItems);
                favorites = new ArrayList(favorites);
            } else
                return null;
            return (ArrayList) favorites;
        }


        public void addFavorite(Context context, BeanSampleList beanSampleList) {
            List favorites = loadFavorites(context);
            if (favorites == null)
                favorites = new ArrayList();
            favorites.add(beanSampleList);
            storeFavorites(context, favorites);
        }


        public void removeFavorite(Context context, BeanSampleList beanSampleList) {
            ArrayList favorites = loadFavorites(context);
            if (favorites != null) {
                favorites.remove(beanSampleList);
                storeFavorites(context, favorites);
            }
        }

答案 1 :(得分:2)

使用tinydb。检查以下链接,你可能会有所了解。 https://github.com/kcochibili/TinyDB--Android-Shared-Preferences-Turbo

使用tinydb可以将数组存储在本地数据库中。

答案 2 :(得分:0)

首先从下面的链接下载Gson.jar,然后将其添加到项目的libs文件夹中

http://www.java2s.com/Code/Jar/g/Downloadgson17jar.htm

然后将ArrayList放在Class中并创建该类的对象,然后将该对象保存到SharedPreferences,如下所示

public static void save_User_To_Shared_Prefs(Context context, User _USER) {
    SharedPreferences appSharedPrefs = PreferenceManager
            .getDefaultSharedPreferences(context.getApplicationContext());
    SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();
    Gson gson = new Gson();
    String json = gson.toJson(_USER);
    prefsEditor.putString("user", json);
    prefsEditor.commit();

 }

上面的代码是一个示例_USER objext包含ArrayList

要阅读对象,请看下面的代码

 public static User get_User_From_Shared_Prefs(Context context) {

    SharedPreferences appSharedPrefs = PreferenceManager
            .getDefaultSharedPreferences(context.getApplicationContext());
    Gson gson = new Gson();
    String json = appSharedPrefs.getString("user", "");


    User user = gson.fromJson(json, User.class);
    return user;
} 

现在当你想让_USER对象调用上面的函数时,结果你将拥有该对象,并且你将拥有ArrayList

答案 3 :(得分:0)

另一种解决方案(只是想到它):

如果您有一个名为addtos的数组,并且您希望将数组添加到共享首选项,因为该变量在字典中表示为String,您可以将数组索引附加到该字符串的末尾。

例如 -

<强>存储

for(int i = 0; i<addtos.size(); i++)
    prefsEditor.putString("addtos"+i, addtos.get(i));

<强>接收

int i = 0;
while(true){
    if(prefs.getString("addtos"+i, "")!=""){  // or whatever the default dict value is
        // do something with it
        i++;
    }else{break;}
}

对我来说似乎没问题,如果有人发现此问题,请告诉我。

此外,不需要ArrayLists

答案 4 :(得分:0)

您可以使用gson:

保存首选项:

 public void save_User_To_Shared_Prefs(Context context, List<User> users) {
        SharedPreferences settings;
        Editor editor;

        settings = context.getSharedPreferences(PREFS_NAME,
                Context.MODE_PRIVATE);
        editor = settings.edit();

        Gson gson = new Gson();
        String jsonUsers = gson.toJson(users);

        editor.putString(USERS, jsonUsers);

        editor.commit();
    }

获取首选项:

public ArrayList<User> getUsers(Context context) {
        SharedPreferences settings;
        List<User> users;

        settings = context.getSharedPreferences(PREFS_NAME,
                Context.MODE_PRIVATE);

        if (settings.contains(USERS)) {
            String jsonUsers = settings.getString(USERS, null);
            Gson gson = new Gson();
            User[] userItems = gson.fromJson(jsonUsers,
                    User[].class);

            users = Arrays.asList(userItems);
            users= new ArrayList<User>(users);
        } else
            return null;

        return (ArrayList<User>) users;
    }

添加用户:

public void addUser(Context context, User user) {
        List<Product> favorites = getUsers(context);
        if (users == null)
            users = new ArrayList<User>();
        users.add(user);
        save_User_To_Shared_Prefs(context, users);
    }