Store ArrayList <CustomClass> in SharedPreferences

I have an ArrayList 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 to SharedPreferences .. I read that this can be done by translating it to Set .. But I don’t know how to do it.

Is there any way to do this? Or any other way to store data, not 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(); 
+5
source share
8 answers

You cannot save the Context object exactly, and there is no point in saving it. My suggestion would be to override toString to return a JSONObject that stores the information you want to keep in 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 a SharedPreference. When you read it, you need to analyze and build Task objects

+1
source

Save the entire ArrayList array for custom objects, as for SharedPreferences

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

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

Download here

Using this library, we can convert the object to a JSON String , and then save it to SharedPrefrences , and then pull out the JSON string and convert it back to Object.

However, if you want to keep the custom class ArrayList , you will need to do something like the following,

Define 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(); 

Get a string and convert it to an object

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

If order doesn't matter, you can use

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

to convert your list to a set. Then the sets can be saved in SharedPreferences.

Edit: Ok, it seems to work only for a list of strings.

+1
source

You can also save the array as the global value of the application.

You need to create a class with your arraylist as an attribute similar to 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 should declare this class in the manifest file as follows:

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

To install and get an array, you need to use:

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

The above suggestions about general preferences should also work.

Hope this helps.

+1
source

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

0
source

Using ObjectMapper, you can do this. Just look at the code below.

 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 analyze dataMap and get the 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); } 

Reliability above code will help you!

0
source

You must pass it using putParcelableArrayList (). must work

0
source

 **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:)* 
0
source

Source: https://habr.com/ru/post/1209090/


All Articles