Store ArrayList<CustomClass> into SharedPreferences

醉酒当歌 提交于 2019-12-23 11:46:00

问题


I have an ArrayList of custom class Task

public class Task {

    String name,desc;
    Date date;
    Context context;

    public Task(String name, String desc, Date date, Context context) {
        this.name = name;
        this.desc = desc;
        this.date = date;
        this.context = context;

    }
}

I want to save it in SharedPreferences.. I read that can be done by converting it to Set.. But I don't know how to do this..

Is there a way to do this? Or any other way to store data rather than SharedPreferences?

Thanks :)

EDIT:

String s = prefs.getString("tasks", null);

    if (tasks.size() == 0 && s != null) {
        tasks = new Gson().fromJson(s, listOfObjects);
        Toast.makeText(MainActivity.this, "Got Tasks: " + tasks, Toast.LENGTH_LONG)
                .show();
    }

protected void onPause() {
    super.onPause();
    Editor editPrefs = prefs.edit();
    Gson gson = new Gson();
    String s = null;
    if(tasks.size() > 0) {
        s = gson.toJson(tasks, Task.class);
        Toast.makeText(MainActivity.this, "Tasks: " + s, Toast.LENGTH_LONG)
                .show();
    }
    editPrefs.putString("tasks", s);
    editPrefs.commit();

回答1:


You can't save for sure the Context object, and it does not make sense to save it. My suggestion would be to override toString to return a JSONObject that holds the information you want to store in the SharedPreference.

public String toString() {
   JSONObject obj = new JSONObject();
   try {
      obj.put("name", name);
      obj.put("desc", desc);
      obj.put("date", date.getTime());
  catch (JSONException e) {
        Log.e(getClass().getSimpleName(), e.toString());
   }
   return obj.toString();
}

and write this json object in the SharedPreference. When you read it back you have to parse and construct your Task objects




回答2:


Store whole ArrayList of Custom Objects as it is to SharedPreferences

We cannot store ArrayList or any other Objects directly to SharedPrefrences.

There is a workaround for the same. We can use GSON library for the same.

Download From Here

Using this library we can convert the object to JSON String and then store it in SharedPrefrences and then later on retrieve the JSON String and convert it back to Object.

However if you want to save the ArrayList of Custom Class then you will have to do something like the following,

Define the type

Type listOfObjects = new TypeToken<List<CUSTOM_CLASS>>(){}.getType();

Then convert it to String and save to Shared Preferences

String strObject = gson.toJson(list, listOfObjects); // Here list is your List<CUSTOM_CLASS> object
SharedPreferences  myPrefs = getSharedPreferences(YOUR_PREFS_NAME, Context.MODE_PRIVATE);
Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("MyList", strObject);
prefsEditor.commit();

Retrieve String and convert it back to Object

String json = myPrefs.getString("MyList", "");
List<CUSTOM_CLASS> list2 = gson.fromJson(json, listOfObjects);



回答3:


You can also store the array as a global application value.

You have to create a a class with your arraylist as the attribute like this:

public class MyApplication extends Application {

    private ArrayList<Task> someVariable;

    public ArrayList<Task> getSomeVariable() {
        return someVariable;
    }

    public void setSomeVariable(ArrayList<Task> someVariable) {
        this.someVariable = someVariable;
    }
}

and you have to declare this class in your manifest file like this:

<application android:name="MyApplication" android:icon="@drawable/icon" android:label="@string/app_name">

To set and get your array you need to use:

((MyApplication) this.getApplication()).setSomeVariable(tasks);

tasks = ((MyApplication) this.getApplication()).getSomeVariable();

The above suggestions about shared preferences should also work.

Hope this helps.




回答4:


If the order doesn't matter, you could use

ArrayList arrayList = new ArrayList();
...
Set set = new HashSet(arrayList);

to convert your list to a set. Sets can then be saved in SharedPreferences.

Edit: Ok, seems only to work for List of Strings.




回答5:


SharedPreferences supports a set of strings but that does not solve your problem. If you need to store custom objects you could serialize them to a string and deserialize them again. But that does not work with your context variable - which I would not store anyway because it is by design temporary. What you can also do is to have your class implement serializable, write it to a file and then store the path to that file in your preferences.




回答6:


Using ObjectMapper you can do it. Just look at below code.

public List<CustomClass> getCustomClass() {
            List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
            ObjectMapper objectMapper = new ObjectMapper();
            String value = getString(CUSTOM_CLASS, null);
            if (null != value) {
                try {
                    mapList = objectMapper.readValue(value, List.class);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("cutoms", mapList);
            return dataMap
        }

you need to parse dataMap and get values and

public void setCutomClass(List<CustomClass> cutoms) {
    ObjectMapper objectMapper = new ObjectMapper();
    String value = null;
    try {
        value = objectMapper.writeValueAsString(cutoms);
    } catch (IOException e) {
        e.printStackTrace();
    }
    setString(CUSTOM_CLASS, value);
}

Hope above code will help you!!!




回答7:


You should be able to pass it in using putParcelableArrayList(). should work




回答8:


**To save Arraylist values to SharedPreferences**

*Beneath code for Store values.*

       SharedPreferences SelectedId = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
       SharedPreferences.Editor editor = SelectedId.edit();
       editor.putString("DeviceToken", TextUtils.join(",", limits)); // Add Array list elements to shared preferences
       editor.commit();
       
       Toast.makeText(getApplicationContext(), "Dash_Agil" + t, Toast.LENGTH_SHORT).show();


**To Retrieve** 

  SharedPreferences tt = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
  String ss = tt.getString("DeviceToken", "");
  List<String> list1 = new LinkedList (Arrays.asList(TextUtils.split(ss, ",")));
  Toast.makeText(getApplicationContext(),""+list1, Toast.LENGTH_SHORT).show();
  TextView t = (TextView) findViewById(R.id.list_items_id);
  t.setText(ss);



*Hope this will help u:)*

 


来源:https://stackoverflow.com/questions/27483321/store-arraylistcustomclass-into-sharedpreferences

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!