如何在android中存储和检索ArrayListObject到共享首选项?

时间:2017-07-10 08:38:07

标签: android listview

我有和app包含listview和适配器。在listview中,我将数据存储在ArrayList中,并希望将此ArrayList对象存储在sharedpreference中,并在下一个活动中检索它并在listview中填充数据。我该怎么做?

代码: -

listViewHolder.switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                new AlertDialog.Builder(mContext, R.style.AppCompatAlertDialogStyle).setTitle("Warning").setMessage("You want to whiteList this application?").setPositiveButton("YES", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //here i am adding items to another arraylist
                        List<WhiteListModel> res = new ArrayList<WhiteListModel>();
                        WhiteListModel whiteListModel = new WhiteListModel();
                        whiteListModel.setName(listStorage.get(position).getName());
                        whiteListModel.setPackName(listStorage.get(position).getPackName());
                        whiteListModel.setIcon(listStorage.get(position).getIcon());
                        res.add(whiteListModel);

                        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);
                        SharedPreferences.Editor editor = sharedPrefs.edit();
                        Gson gson = new Gson();
                        String json = gson.toJson(res);
                        editor.putString("WhiteList", json);
                        editor.apply();


                        listStorage.remove(position);
                        notifyDataSetChanged();
                        listViewHolder.switchCompat.setChecked(false);

                    }
                }).setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        listViewHolder.switchCompat.setChecked(false);
                    }
                }).show();
            }
        }
    });

7 个答案:

答案 0 :(得分:0)

您可以使用Gson将您的ArrayList转换为字符串格式的JSON,然后在将该字符串放入共享首选项后,在下一个屏幕中,您必须从该JSON字符串中创建一个数组列表。

答案 1 :(得分:0)

实现所要求的最佳方法是使用名为的库 Gson,将其包含在您的代码中:

import com.google.gson.Gson;

使用它,您将能够将数组列表或任何数据集转换为Json格式,将其存储到共享首选项,然后检索它们。

这样做的一个简单示例很简单易行,HERE

答案 2 :(得分:0)

如果您想将项目从一个活动传递到另一个活动,则应使用Parcelable

您的班级WhiteListModel应该像文档建议的那样实施Parcelable。然后你可以做这样的事情来编写arraylist:

Intent intent = new Intent(<context>, <targetActivity>);
intent.putParcelableArrayListExtra("key", whiteListModel);

要获得arraylist,您可以:

whiteListModel = getIntent().getParcelableArrayListExtra("key");

您还可以将模型类包装到另一个类中,并使其成为可分割的类。

答案 3 :(得分:0)

在build.gradle

中的依赖项中添加此行
compile 'com.google.code.gson:gson:2.7' 

<强> UserObj.class

public UserObj {
   String firstName,lastName;

   public String getFirstName() {
      return firstName;
   }

   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }

   public String getLastName() {
      return lastName;
   }

   public void setLastName(String lastName) {
      this.lastName = lastName;
   }   
}

保存对象

preferences.putString("user", new GsonBuilder().create().toJson(user));

加载对象

String str = preferences.getString("user", "");
if (!str.isEmpty()) {
    user = new GsonBuilder()
           .serializeNulls()
           .create()
           .fromJson(userString, UserObj.class);
}

答案 4 :(得分:0)

public static void saveUserLoginDetail(Context context, LoginResponse response) {
    Gson gson = new Gson();
    String jsonString = gson.toJson(response);      
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    if (preferences != null) {
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(key, jsonString);
        editor.commit();
    }
}

public static LoginResponse getUserLoginDetail(Context mContext) {
    LoginResponse loginResponse = new LoginResponse();
    String jsonString = getStringPreference(mContext, PREF_LOGIN_RESPONSE);
    loginResponse = new Gson().fromJson(jsonString, LoginResponse.class);
    return loginResponse;
}
  

如果要返回类型为LoginResponse的任何对象的Array List,请使用:

Type type = new TypeToken<List<LoginResponse>>(){}.getType();
List<LoginResponse> loginResponse= gson.fromJson(json, type);

答案 5 :(得分:0)

如果数据不需要有序排列且不包含重复元素,您可以尝试text-align: rightSharedPreferences.Editor

答案 6 :(得分:0)

  1. 将值添加到列表

               Set<String> set = new HashSet<String>();
                set.add("11122");
                set.add("222");
    
  2. 使用saveSharePrefaraceArrayList方法保存到shareprefarance设置值

    saveSharePrefaraceArrayList(set);
    
  3. SharedPreference保存方法以保存值列表

     void saveSharePrefaraceArrayList( Set<String> setList){
    
        SharedPreferences  prefs=this.getSharedPreferences("yourPrefsKey",Context.MODE_PRIVATE);
       Editor edit=prefs.edit();
    
      Set<String> set = new HashSet<String>();
       set.addAll(setList);
      edit.putStringSet("myshareprekey", set);
      edit.commit();
     }
    
  4. 最后从shareprefarance获取列表值

    SharedPreferences prefs=this.getSharedPreferences("yourPrefsKey",Context.MODE_PRIVATE);
    SharedPreferences.Editor edit=prefs.edit();
    Set<String> set = prefs.getStringSet("myshareprekey", null);
    ArrayList<String> arraylistValues = new ArrayList<String>(set);