How to create array of classes in android - 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

Related

How to save/load arraylist that contains double values?

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

How can I save and load from preferences the entries of a listview that has multiple types of entries?

I have a listview that displays a list of interfaces, where the interface is implemented by two types of classes:
1) An entry with a date
2) A header that break up the entries by day
My issue is being able to save and load the list of interfaces into preferences when the app is opened/closed. From what I understand, I need to use an interface adapter to serialize/deserialize the list of interfaces.
I tried following the tutorial but I'm getting an error
Caused by: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
from the line "gson.fromJson(json, type)" in the "loadCLEntries" function below. Below is my relevant code.
Interface:
public interface CallLogListViewItem {
//These are so the list view can tell if an entry is a header or an entry
public int getViewType();
public View getView(LayoutInflater inflater, View convertView);
}
List being displayed in listview:
private static List<CallLogListViewItem> callLogEntries = new ArrayList<>();
Code that loads the entries + headers from preferences when app is opened:
private static ArrayList<CallLogListViewItem> loadCLEntries() {
SharedPreferences pref = App.getApp().getSharedPreferences("info", MODE_PRIVATE);
String json = pref.getString("CallLogEntries", "[]");
Type type = new TypeToken<ArrayList<CallLogListViewItem>>(){}.getType();
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(CallLogListViewItem.class, new InterfaceAdapter<>());
Gson gson = builder.create();
return gson.fromJson(json, type);
}
Code to save the headers + entries when app is closed:
private static void saveCLEntries() {
//Save entries
SharedPreferences pref = App.getApp().getSharedPreferences("info", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
Gson gson = new Gson();
String json = gson.toJson(callLogEntries, CallLogListViewItem.class);
editor.putString("CallLogEntries", json);
editor.apply();
}
It turns out the problem is that I'm saving the list of interfaces incorrectly.
When serializing the list, I need to also use the interface adapter:
private static void saveCLEntries() {
//Save entries
SharedPreferences pref = App.getApp().getSharedPreferences("info", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
Type type = new TypeToken<ArrayList<CallLogListViewItem>>(){}.getType();
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(CallLogListViewItem.class, new InterfaceAdapter<>());
Gson gson = builder.create();
String json = gson.toJson(callLogEntries, type);
editor.putString("CallLogEntries", json);
editor.apply();
}
And that was it.

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.

Adding an item to arralist which is already saved in shared preferences in android

I am having an array list which is already stored in shared preferences.I want to add another item in array list.
Whenever i am trying to add an item in array list it is removing all the previous data stored in arraylist
How can i add item without removing the previous data in shared preferences
ArrayList<String> cartArrayListID,cartArrayListName,cartArrayListPrice,cartArrayListImage;
String cartID,cartName,cartPrice,cartImage;
cartArrayListID=new ArrayList<>();
cartArrayListName=new ArrayList<>();
cartArrayListPrice=new ArrayList<>();
cartArrayListImage=new ArrayList<>();
cartArrayListID.add(cartID);
cartArrayListName.add(cartName);
cartArrayListPrice.add(cartPrice);
cartArrayListImage.add(cartImage);
SharedPreferences sprefCart=getSharedPreferences("CARTINFO", Context.MODE_PRIVATE);
SharedPreferences.Editor editorCart=sprefCart.edit();
Gson gson = new Gson();
String id_=gson.toJson(cartArrayListID);
String name_=gson.toJson(cartArrayListName);
String price_=gson.toJson(cartArrayListPrice);
String image_=gson.toJson(cartArrayListImage);
editorCart.putString("ID", id_);
editorCart.putString("NAME", name_);
editorCart.putString("PRICE", price_);
editorCart.putString("IMAGE", image_);
editorCart.apply();
Toast.makeText(ProductActivity.this, "Added to cart", Toast.LENGTH_SHORT).show();
as I see in your code, you create a whole new ArrayLists cartArrayListID, cartArrayListName , ..etc everytime, and then you put the new value into it, after that you save it in SharedPreferences which in turn will replace the old one saved in it with your new one, so you have to:
get the corresponding ArrayList from Shared preferences at first.(for ex. cartArrayListName)
save it in a new array called cartArrayListID.
put the new values in this new array.
save it back in SharedPreferences.
You cannot get an ArrayList from SharedPreferences.
You can get a Set using getStringSet. Notice that the jdoc states that
Note that you must not modify the set instance returned by this call.
so do something like:
Set<String> mySet = new HashSet(yourPrefDataCollection);
mySet.add("some string");
sp.edit().putStringSet("your set key", mySet).commit();
Use GSON to get ArrayList from the String.
Add some items.
Try this example to save ArrayList to String, so you can store to SharedPreferences.
If your ArrayList has some special type (not String), use this construction:
ArrayList<Foo> list = new Gson().fromJson(
gsonString, new TypeToken<List<Foo>>(){}.getType());
The best way to accomplish this is by storing your array as a String in JSON format. You have to create a simple POJO to store your array and the rest is simple. See example below;
public void saveArray(List<String> yourArray) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("YOUR_ARRAY_KEY", new Gson().toJson(new ArrayListHolder(yourArray)));
editor.apply();
}
public List<String> getArray() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String arrayJson = sharedPreferences.getString("YOUR_ARRAY_KEY", null);
if (arrayJson != null) {
return new Gson().fromJson(arrayJson, ArrayListHolder.class).getYourArray();
}
return null;
}
private class ArrayListHolder {
private List<String> yourArray;
public ArrayListHolder(List<String> yourArray) {
this.yourArray = yourArray;
}
public List<String> getYourArray() {
return yourArray;
}
public void setYourArray(List<String> yourArray) {
this.yourArray = yourArray;
}
}

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