How to save/load arraylist that contains double values? - android

I have 5 arrayLists created that have double values
public ArrayList<Double> arrayList1 = new ArrayList<Double>();
public ArrayList<Double> arrayList2 = new ArrayList<Double>();
public ArrayList<Double> arrayList3 = new ArrayList<Double>();
public ArrayList<Double> arrayList4 = new ArrayList<Double>();
public ArrayList<Double> arrayList5 = new ArrayList<Double>();
I am trying to save them after the user enters values in an editText and clicks a submit button
if(spinnerPosition==1){
arrayList1.add(Double.parseDouble(enterText.getText().toString()));
}
Then I would like to load arrayList and use the values inside arrayList to calculate an average. I have the method to calculate the average, just need to know how to load arrayList to calculate average every time a new value is entered
public String arrayList1AverageResults(){
double sum=0.0;
if(arrayList1.size() > 0){
for ( int i=0; i < arrayList1.size() ; i++) {
sum += arrayList1.get(i);
}
arrayList1Avg = sum / arrayList1.size();
}
return arrayList1Avg;
}

There are a number of ways to persist the data when the App close.
You could serialise them to a file.
You could serialise them to shared preferences.
Save ArrayList to SharedPreferences
Or probably must better store them to a database (Android has various ways to store them to a database like SQLite
Reference https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase
Tutorial for one method https://www.tutorialspoint.com/android/android_sqlite_database.htm
Or the more "Android" way with https://developer.android.com/training/data-storage/room/

I would persist the ArrayList using SharedPreferences using GSON library like so:
Save
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = sharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(arrayList1);
editor.putString("ARRAY_LIST_1", json);
editor.commit();
Read
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Gson gson = new Gson();
String json = sharedPrefs.getString("ARRAY_LIST_1", "");
arrayList1 = Arrays.asList(gson.fromJson(json, Double[].class));

This is what worked for me
private void saveArrayList1(){
SharedPreferences sharePref= getActivity().getSharedPreferences("ArrayList1",MODE_PRIVATE);
SharedPreferences.Editor editor= sharePref.edit();
Gson gson= new Gson();
String json= gson.toJson(arrayList1);
editor.putString("Array1",json);
editor.apply();
}
private void loadArray(){
SharedPreferences sharePref= getActivity().getSharedPreferences("ArrayList1",MODE_PRIVATE);
Gson gson= new Gson();
String json = sharePref.getString("Array1",null);
Type type = new TypeToken<ArrayList<Double>>(){}.getType();
arrayList1=gson.fromJson(json,type);
if (arrayList1 == null) {
arrayList1 = new ArrayList<>();
}
}

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

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 Integer Hashset in SharedPreference?

It says wrong 2nd argument type required set String.
Set<Integer> hs = pref.getStringSet("set", new HashSet<Integer>());
hs.add(String.valueOf(hs.size()+1));
SharedPreferences.Editor edit = pref.edit();
edit.putStringSet("set", hs);
edit.commit();
You can do the conversion and store it in SharedPreferences like this,
SharedPreferences preferences = context.getSharedPreferences("preferences", Context.MODE_PRIVATE);
Set<Integer> integerHashSet = new HashSet<>();
integerHashSet.add(1);
integerHashSet.add(2);
//convert String HashSet to Integer HashSet
Set<String> stringHashSet = new HashSet<>();
for (Integer i : integerHashSet) {
stringHashSet.add(String.valueOf(i));
}
preferences.edit().putStringSet("set", stringHashSet).commit();
Set<String> stringSet = preferences.getStringSet("set", new HashSet<String>());
Set<Integer> integerSet = new HashSet<>();
//Convert it back
for (String str : stringSet) {
integerSet.add(Integer.parseInt(str));
}
//now user integerSet
Use Gson
implementation 'com.google.code.gson:gson:2.8.5'
Gson helps to convert custom object to string & string to custom object.
So you can convert set to string save to shared pref. And later get string from shared pref and convert to set.
To save
Set<Integer> mySet = new HashSet<>();
String json = new Gson().toJson(mySet);
//Save json to shared pref
Then to retrieve
//get json from shared preference saved earlier
Set<Integer> mySet2 = new Gson().fromJson(json, new TypeToken<Set<Integer>>() {
}.getType());
It says wrong 2nd argument type required set String.
It's because you're incorrectly using the getStringSet with the following code:
Set<Integer> hs = pref.getStringSet("set", new HashSet<Integer>());
it should be like this:
Set<String> hs = pref.getStringSet("set", new HashSet<String>());
You should recognize the method signature which is clearly telling that the method is giving you a string set with getStringSet.

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