【问题标题】:How can I store Arraylists in class?如何在课堂上存储 Arraylist?
【发布时间】:2021-02-11 15:17:08
【问题描述】:

我有一个班级data,我在其中存储我的用户数据。

public class deck {
    public static ArrayList deck = new ArrayList();
    public static ArrayList cardchosen = new ArrayList();
    public static ArrayList deck1Image = new ArrayList();
    public static ArrayList deck2Image = new ArrayList();
}

如何在 onSaveInstanceState 中保存这些数组的状态? 我必须使用不同的东西吗?

【问题讨论】:

  • deck、cardchosen、deck1Image、deck2Image的ArrayList()的类型是什么?
  • 全是 Integer ArrayList
  • 我已经尝试过使用 outstate.getIntegerArraylist 但它得到红色下划线...

标签: java android arraylist save onsaveinstancestate


【解决方案1】:

在你的数据类中实现 Serializable 接口会更容易

public class Deck implements Serializable {

    public static ArrayList deck = new ArrayList();
    public static ArrayList cardchosen = new ArrayList();
    public static ArrayList deck1Image = new ArrayList();
    public static ArrayList deck2Image = new ArrayList();
}

然后在 onSaveInstanceState 中设置类似的 bundle

科特林

    override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) {
        val deck = Deck()
        outState.putSerializable("mydeck", deck)
        super.onSaveInstanceState(outState, outPersistentState)
    }

Java

@Override
public void onSaveInstanceState(Bundle outState) {
   outState.putSerializable("mydeck", deck);
   super.onSaveInstanceState(outState);
}

【讨论】:

  • 我应该把 onSaveInstanceState 放在哪里?在 MainActivity 中?因为deck 类没有 OnCreate,所以没有什么可以覆盖...
  • 是的,在你的活动中
  • 不幸在java中需要
  • 谢谢!但是重新打开应用程序后如何恢复该数据?也在 MainActivity 中?如果是这样,将我保存的数据恢复到我的甲板类中的最佳方法是什么?
【解决方案2】:

你需要隐式声明ArrayList的类型:

public class deck {
    public static ArrayList deck = new ArrayList<Integer>();
    public static ArrayList cardchosen = new ArrayList<Integer>();
    public static ArrayList deck1Image = new ArrayList<Integer>();
    public static ArrayList deck2Image = new ArrayList<Integer>();
}

当您尝试这样做时,编译器不知道其他情况:

ArrayList myArrayList = outstate.getIntegerArrayList("My Key")

【讨论】:

    猜你喜欢
    • 2012-09-02
    • 1970-01-01
    • 2019-07-03
    • 2019-03-26
    • 2012-01-12
    • 2015-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多