应用程序关闭后如何保存arraylist <object>

时间:2017-03-30 16:53:10

标签: java android arraylist

应用关闭后如何保存arraylist。 这是我的全球课

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

这是我的旅行课

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

我想保存数组列表,当我关闭并打开应用程序时,会保存数组列表(alltrips)。怎么做?

我想使用共享首选项,但我不知道如何执行此操作,因为它不是带有Trip的数组列表的字符串。任何人都可以帮我保存共享偏好中的arraylist吗?

5 个答案:

答案 0 :(得分:0)

我认为这是最简单的方法,您可以将数据保存在 SharedPrefences 中,并从sharedPrefernces填充您的arraylist。由于sharedPrefernces仅存储基元类型,因此您可以使用 Gson 将对象转换为String,然后将其存储在sharedPrefrence中。希望有所帮助!

答案 1 :(得分:0)

您需要将数据保存到数据库中,或者可以按照此Stackoverflow问题进行操作 Question

答案 2 :(得分:0)

SharedPreferences允许您保存一组字符串,因此最佳方案是将每个对象转换为String,然后将此String集合保存到共享首选项中,然后在需要时可以从这些字符串重建对象。

或者您可以将其保存在文件系统或数据库中,但如果您想要的话,SharedPreferences会更轻松,更轻松。无论哪种方式,您都需要构建/解构列表中保存的内容。

pod update

修改

简单的例子

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

注意我没有对此进行测试,但它应该没问题(目前我没有Android Studio,因此可能会出现一些小错误,但是从这个解决方案中你应该能够完成此操作。如果需要我可以为您提供完整的解决方案。截至目前,我无法访问我的IDE和WorkStation。

答案 3 :(得分:0)

您可以保存序列化对象并使用以下方法读取它们:

gameosszido.size()-1

要阅读列表,您应该按类型强制转换对象:

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

不要忘记在清单中添加这些权限:

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

答案 4 :(得分:-2)

我不认为在生产模式中会调用生命周期方法。用户只是移出活动页面。你应该在 onPause 方法中做任何你想做的事。