Save custom object array to Shared Preferences - android

Can I save my own object array to the SharedPreferences, like in the post below?
Android ArrayList of custom objects - Save to SharedPreferences - Serializable?
But there he doesn't save an array, so is there a possibility to save a custom object array to SharedPreferences like in the post of the link?

You can use gson to serialize class objects and store them into SharedPreferences. You can downlaod this jar from here https://code.google.com/p/google-gson/downloads/list
SharedPreferences mPrefs = getPreferences(Context.MODE_PRIVATE);
To Save:
Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(MyObject);
prefsEditor.putString("MyObject", json);
prefsEditor.commit();
To Retreive:
Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject obj = gson.fromJson(json, MyObject.class);

Related

How to create array of classes in android

I have a list of classes that i would like to store in an Array or any data structure that would suite my problem. The array should be available across all the package and each element of the classes should be accessible from within the array. Its an Android app.
In Kotlin:
val class1 = Class1()
val class2 = Class2()
val list = ArrayList<Any>()
list.add(class1)
list.add(class2)
Any means you can store any type of object in it. Kotlin SmartCast allows you to check from ArrayList as well
In Java:
Class1 class1 = new Class1()
Class2 class2 = new Class2()
ArrayList list = new ArrayList<Object>()
list.add(class1)
list.add(class2)
You can store ArrayList in SharedPreferences and can use it in the whole application.
Here is sample code (You can optimize it)
public void saveArrayList(ArrayList<Object> list, String key){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
SharedPreferences.Editor editor = prefs.edit();
Gson gson = new Gson();
String json = gson.toJson(list);
editor.putString(key, json);
editor.apply(); // This line is IMPORTANT !!!
}
public ArrayList<Object> getArrayList(String key){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
Gson gson = new Gson();
String json = prefs.getString(key, null);
Type type = new TypeToken<ArrayList<Object>>() {}.getType();
return gson.fromJson(json, type);
}
Here you fetch the object from ArrayList:
ArrayList list = getArrayList("some key");
for (int counter = 0; counter < list.size(); counter++) {
if(list[counter] instance of class1) {
// you have class1 object
}
if(list[counter] instance of class2){
// you have class2 object
}
}
if you don't need to persist the list, i think it will be better to use a singelton that contains a class list

Wanted to store this custom listview text using shared preference on user click

I want to store this custom listview text using shared preference when user will click on that star image (P.S - I don't want to use a database for this) and also wants to retrieve that text(all selected text as an ArrayList) in another activity.
Now I am able to store this text as an ArrayList in my shared preference I but inside my getView() method of custom adapter my ArrayList get reinitialize again and again can anyone help me out
Like this demo example
when user will click on this star image
and in favorite activity will retrieve ArrayList from shared preference
You have to write your arraylist as a json into Sharedpreference
public void saveArrayList(ArrayList<String> list, String key){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
SharedPreferences.Editor editor = prefs.edit();
Gson gson = new Gson();
String json = gson.toJson(list);
editor.putString(key, json);
editor.apply();
}
public ArrayList<String> getArrayList(String key){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
Gson gson = new Gson();
String json = prefs.getString(key, null);
Type type = new TypeToken<ArrayList<String>>() {}.getType();
return gson.fromJson(json, type);
}
https://freakycoder.com/android-notes-40-how-to-save-and-get-arraylist-into-sharedpreference-7d1f044bc79a

How to save Java Object in shared preference

I get JSON from a service, i save it in preference, and when user needs to check session or fetch data, he uses this method getProfileObject(), and it returns ArrayList in return.
This is my method that is responsible to get Json from preference and generate ArrayList by using Gson
SharedPreferences sharedPreferences=ApplicationContext.getAppContext().getSharedPreferences(USER_DATA_PREFERENCE, ApplicationContext.MODE_PRIVATE);
profileObject= sharedPreferences.getString(PROFILE_OBJECT, "");
if(!profileObject.isEmpty()) {
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
this.dataList = Arrays.asList(gson.fromJson(profileObject, Profile.class));
return dataList;
}
Now i want to avoid this Gson step each time, I want to store arrayList is shared preference, Is it possible to store java array list in shared preference.
Try using View Model class which will save it globally through out the activity life cycle.
hope this helps :
https://developer.android.com/topic/libraries/architecture/viewmodel#implement
public static void setArrayListPreference(Context context, ArrayList<String> list, String key){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
Gson gson = new Gson();
String json = gson.toJson(list);
editor.putString(key, json);
editor.apply();
}
public static ArrayList<String> getArrayListPreference(Context context, String key){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
Gson gson = new Gson();
String json = prefs.getString(key, null);
Type type = new TypeToken<ArrayList<String>>() {}.getType();
return gson.fromJson(json, type);
}
Try this way..
Store Array list as serializable object like below ..
editor.putString("key", ObjectSerializer.serialize(currentTasks));// define arrayList
retrive the value.
currentTasks=(ArrayList<task>)ObjectSerializer.deserialize(prefs.getString(TASKS, ObjectSerializer.serialize(new ArrayList<task>())));
Gson dataJson = new Gson();
String userObject = dataJson.toJson(response.body());
after that it store sharedpreference userObject and get data.

How to store and retrieve an object from Gson in android? [duplicate]

This question already has answers here:
Gson - convert from Json to a typed ArrayList<T>
(9 answers)
Closed 6 years ago.
In my activity, the user has an array of images he picks, and then I want to store them in preferences. Then the user leaves the activity, and comes back, I want those images still loaded into an ImageView. I'm trying to use Gson to accomplish this, but am having trouble and can't see what I'm doing wrong.
Hoping external insight may help me with this obvious answer I'm just not seeing.
Thank you.
Here is my code so far.
private void savePreferencesForImages(String key, ArrayList<Image> imageList)
{
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(imageList);
editor.putString(key,json);
editor.commit();
}
//Storing Local data.
private void loadPreferences()
{
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
Gson gson = new Gson();
String gsonString = sharedPreferences.getString("userImages", "");
ArrayList<Image> images = gson.fromJson(gsonString, Image.class);//Ask StackOverflow tomorrow.
}
In the part of retrieving the data you will need a type that deserialize the String into a List of Images...
like:
private void loadPreferences()
{
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
Gson gson = new Gson();
Type type = new TypeToken<List<Image>>() {}.getType();
String gsonString = sharedPreferences.getString("userImages", "");
List<Image> images = gson.fromJson(gsonString, type);
}
One thing you can do is save the images individually and then load them into an ArrayList upon retrieval.
private void savePreferencesForImages(ArrayList<Image> imageList)
{
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
int imgKey = 0;
for (Image img: imageList) {
String json = gson.toJson(imageList);
editor.putString("" + imgKey,json);
editor.commit();
imgKey++;
}
}
private ArrayList<Image> loadPreferences()
{
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
Gson gson = new Gson();
Map<String, ?> allPrefs = sharedPreferences.getAll();
String gsonString = sharedPreferences.getString("userImages", "");
ArrayList<Image> images = new ArrayList<Image>();
if (!allPrefs.isEmpty()) {
for (Map.Entry<String, ?> entry : allPrefs.entrySet()) {
String json = entry.getValue().toString();
Image temp = gson.fromJson(json, Image.class);
images.add(temp);
}
}
return images;
}
This is potentially the most over-complicated way to go about this but it is the first thing I could think of. You could also just make your own ImageManager class or something and emulate the behavior of an ArrayList, with a getImage(key) method and so on. This would eliminate the complications that are brought about when trying to save an ArrayList.

How to save Arraylist of Objects from Fragment class into SharedPreferencess

I saw similar questions in stackoverflow ( LINK , LINK ) and other websites . They are doing everything from an Activity hence they didn't get problem.
I have an Activity and Fragment class. I am trying to save ArrayList of Object into shared preferences from a Fragment. Below is what i tried
SharedPreferences prefs = getActivity().getSharedPreferences("SHARED_PREFS_FILE", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
try {
editor.putString("taggedFriends",ObjectSerializer.serialize(taggableFriends));
} catch (IOException e) {
e.printStackTrace();
Its showing error at ObjectSerializer
**Cannot resolve symbom 'ObjectSerializer'**
I tried
getActivity.ObjectSerializer.serialize(..);
But error didn't go. Help me what can i do now.
Thankyou for spending time for me.
Try this:
Last edit:
In this case:
static class YourObject
{
private String _name;
public YourObject(String name)
{
this._name = name;
}
}
YourObject yourObject = new YourObject(myName);
ArrayList<YourObject> foo = new ArrayList<YourObject>();
foo.add(yourObject);
convert an ArrayList to JSONArray:
JSONArray mJSONArray = new JSONArray(foo);
Then save the JSONArray:
SharedPreferences.Editor editor = prefs.edit();
editor.putString("yourStringName", mJSONArray.toString());
String to JSONArray:
SharedPreferences prefs = getSharedPreferences("SHARED_PREFS_FILE", Context.MODE_PRIVATE);
String myJSONArrayString = prefs.getString("yourStringName", "");
JSONArray jsonArray = new JSONArray(myJSONArrayString);
JSONArray to ArrayList:
ArrayList<String> list = new ArrayList<String>();
for (int i=0;i<jsonArray.length();i++){
list.add(jsonArray.get(i).toString());
}
I hope this solve your question.
First add Gson to your gradle:
compile 'com.google.code.gson:gson:2.2.4'
Convert your list to Json String like below:
List<String> foo = new ArrayList<String>();
foo.add("Item1");
foo.add("Item2");
foo.add("Item3");
String json = new Gson().toJson(foo );
And save it to shared pref like below:
SharedPreferences.Editor mEditor = mPrefs.edit();
mEditor.putString("yourKey", json);
And when you want to use read your saved json string from pref:
String json = mPrefs.getString("yourKey", "");
Convert your Json String to list of your objects like below. In example i used String.
ArrayList<String> foo = (ArrayList<String>) new Gson().fromJson(json,
new TypeToken<ArrayList<String>>() {
}.getType());

Categories

Resources