Reputation: 1282
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();
Upvotes: 5
Views: 5923
Reputation: 2805
To store Arraylist values into SharedPreferences
To Save :
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 Fetch :
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);
Upvotes: 1
Reputation: 1811
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.
Upvotes: 1
Reputation: 15333
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.
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);
Upvotes: 10
Reputation: 614
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.
Upvotes: 2
Reputation: 307
You should be able to pass it in using putParcelableArrayList(). should work
Upvotes: 0
Reputation: 2690
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!!!
Upvotes: 0
Reputation: 806
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.
Upvotes: 0
Reputation: 157447
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
Upvotes: 1