1

how to save arraylist after the app is closed. This is my global class

public class GlobalClass extends Application {

ArrayList<Trip> allTrips = new ArrayList<>();

public ArrayList<String> allTripsString() {
    ArrayList<String> allTripsString = new ArrayList<String>();
    for (Trip trip : allTrips){
        allTripsString.add(trip.getName());
    }
    return allTripsString;
    }
}

This is my trip class

public class Trip {

/** A map with category as key and the associed list of items as value */
Map<String,List<Item>> expanses;

private String name;
public ArrayList<String> ExpensesCategory = new ArrayList<>();
public ArrayList<String> Adults = new ArrayList<>();
public ArrayList<String> Children = new ArrayList<>();
public ArrayList<String> ShoppingName = new ArrayList<>();
public ArrayList<Double> ShoppingPrice = new ArrayList<>();
public ArrayList<String> ShoppingCategory = new ArrayList<>();
public double budget = 0;

/** An item in the expanses list */
static class Item {
    final String name;
    final double cost;
    final String Category;
    public Item(String name, double cost, String Category) {
        this.name = name;
        this.cost = cost;
        this.Category = Category;
    }
    @Override public String toString() {
        return this.name + " (" + this.cost + "$)";
    }
    public String getName(){
        return name;
    }
    public String getCategory(){
        return Category;
    }
    public double getCost(){
        return cost;
    }
}

public Trip(String name) {
    this.name = name;
    this.expanses = new HashMap<String,List<Item>>();
    for (String cat: ExpensesCategory) { // init the categories with empty lists
        this.expanses.put(cat, new ArrayList<Item>());
    }
}

public String getName(){
    return name;
}

/** Register a new expanse to the trip. */
public void add(String item, double cost, String category) {
    List<Item> list = this.expanses.get(category);
    if (list == null)
        throw new IllegalArgumentException("Category '"+category+"' does not exist.");
    list.add( new Item(item, cost, category) );
}

/** Get the expanses, given a category.
 * @return  a fresh ArrayList containing the category elements, or null if the category does not exists
 */
public List<Item> getItems(String category) {
    List<Item> list = this.expanses.get(category);
    if (list == null)
        return null;
    return new ArrayList<Item>(list);
}

/** Get the expanses, given a category.
 * @return  a fresh ArrayList containing all the elements
 */
public List<Item> getItems() {
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    return list;
}

public ArrayList<String> getItemsString() {
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    ArrayList<String> listString = new ArrayList<String>();
    for (Item item : list){
        listString.add(item.getName());
    }
    return listString;
}

public ArrayList<Double> getItemsCost(){
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    ArrayList<Double> listDouble = new ArrayList<>();
    for (Item item : list){
        listDouble.add(item.getCost());
    }
    return listDouble;
}

public ArrayList<String> getItemsCategory() {
    List<Item> list = new ArrayList<Item>();
    for (List<Item> l: this.expanses.values()) // fill with each category items
        list.addAll(l);
    ArrayList<String> listString = new ArrayList<String>();
    for (Item item : list){
        listString.add(item.getCategory());
    }
    return listString;
}

/** Get the total cost, given a category. */
public double getCost(String category) {
    List<Item> list = this.expanses.get(category);
    if (list == null)
        return -1;
    double cost = 0;
    for (Item item: list)
        cost += item.cost;
    return cost;
}

/** Get the total cost. */
public double getCost() {
    double cost = 0;
    for (List<Item> l: this.expanses.values())
        for (Item item: l)
            cost += item.cost;
    cost *= 1000;
    cost = (int)(cost);
    cost /= 1000;
    return cost;
    }
}

I want to save the array list and when I close and open the app the array list (alltrips) is saved. How to do this?

I want to use shared preferences but I don't know how to do this because it is not a string it array list with Trip. Can anyone help me to save the arraylist in shared preferences?

Guy Rajwan
  • 33
  • 1
  • 10

5 Answers5

0

I think the most easiest way to so this is you can save your data in SharedPrefences and populate your arraylist from the sharedPrefernces. As sharedPrefernces only store primitive types you can use Gson for converting your object into String and then store that in the sharedPrefrence. Hope that helps!.

Varun Ajay Gupta
  • 349
  • 1
  • 3
  • 11
0

You need to save your data into the database or you can follow this Stackoverflow question Question

Community
  • 1
  • 1
S Haque
  • 6,881
  • 5
  • 29
  • 35
0

SharedPreferences allows you to save a Set of Strings, so your best scenario is to convert every object into a String and then save this collection of String into sharedpreferences, and then when needed you can rebuild the objects from these Strings.

Or you can save it in file system or DB, but SharedPreferences is lighter and easier if all you want is this. Either way you will need to construct/deconstruct the saved content of your list.

//Retrieve the values
Set<String> set = myScores.getStringSet("key", null);

//Set the values
Set<String> set = new HashSet<String>();
set.addAll(listOfExistingScores);
scoreEditor.putStringSet("key", set);
scoreEditor.commit();

EDIT

simple example

public void saveToSharedPreferences(Context context, List<String> list){

    Set<String> set =
            list.stream()
            .collect(Collectors.toSet()); // Returns in this case a Set, if you need Iterable or Collection it is also available.

    PreferenceManager.getDefaultSharedPreferences(context) // Get Default preferences, you could use other.
            .edit()
            .putStringSet("myKey", set) // Save the Set of Strings (all trips but as Strings) with the key "myKey", this key is up to you.
            .apply();                   // When possible commit the changes to SharePreferences.
}

public void saveToSharedPreferences(Context context, List<Trip> list){
    List<String> stringList = list.stream()
            .map(Trip::getName) // This uses this method to transform a Trip into a String
                                // you could use other method to transform into String but if all you need to save is the name this suffices
                                // examples: .map( trip -> trip.getName()), .map(trip -> trip.toString()), etc. you choose how to save.
                                // It should save every state that a Trip has, so when you are reading the saved Strings
                                // you will be able to reconstruct a Trip with its state from each String.
            .collect(Collectors.toList());
    saveToSharedPreferences(context, stringList);
}

NOTE i did not test this but it should be ok (currently i do not have Android Studio so there might be some little errors, but from this solution you should be able to finish this. If needed i could give you the complete solution working. As of now i do not have access to my IDE and WorkStation.

Edu G
  • 1,030
  • 9
  • 23
  • I don't understand how to do this, Can you explain how to do that? I want to use shared preferences, I need only to save this array list. – Guy Rajwan Mar 30 '17 at 17:09
0

You can save serialized object and read them by using those methods :

public static boolean writeObjectInCache(Context context, String key, Object object) {
    try {
        FileOutputStream fos = context.openFileOutput(key, Context.MODE_PRIVATE);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(object);
        oos.close();
        fos.close();
    } catch (IOException ex) {
        return false;
    }

    return true;
}


public static Object readObjectFromCache(Context context, String key) {
    try {
        FileInputStream fis = context.openFileInput(key);
        ObjectInputStream ois = new ObjectInputStream(fis);
        Object object = ois.readObject();
        return object;
    } catch (Exception ex) {
        return null;
    }
}

To read the list , you should cast the Object by your type :

  ArrayList<TypeOfYourObject> list = new ArrayList<>();
        list = (ArrayList<TypeOfYourObject>) readObjectFromCache(context, CACHE_KEY);

Don't forget to add those permission in your manifest :

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 
Imene Noomene
  • 3,035
  • 5
  • 18
  • 34
  • How did u integrate this code ? Do u make the Object Of your List Serializable ? How did u call writeObjectInCache and readObjectFromCache methods ? Do u add those permission in your manifest : ? – Imene Noomene Mar 31 '17 at 10:28
  • I'm using this method and it works fine. Please check if u add permissions and make object serialized – Imene Noomene Mar 31 '17 at 11:09
-2

I dont think there is lifecyle method which will be called in production mode . the user just moves out of the activity page . you should probably do whatever you want in onPause method .

Balaji V
  • 918
  • 3
  • 10
  • 28
  • "I dont think there is lifecyle method which will be called in production mode" what do you mean by that? – njzk2 Mar 30 '17 at 17:03
  • there is no hook . that was my point . Correct me if i am wrong – Balaji V Mar 30 '17 at 17:05
  • "production mode" is not a thing. onPause is part of the [lifecycle](https://developer.android.com/guide/components/activities/activity-lifecycle.html), as onStop and onDestroy, but it is usually recommended to save your data early, as there is always the possibility of an immediate shutdown for no reason (e.g., the user removes the battery) – njzk2 Mar 30 '17 at 18:17