在Bundle之间发送ArrayList <integer>

时间:2018-02-05 16:39:32

标签: android onsaveinstancestate onrestoreinstancestate

问题:
如何将_selectednumber_points的数据从onSaveInstanceState转移到onRestoreInstanceState

private List<Integer> _selectednumber= new ArrayList<>();
private List<Integer> _points = new ArrayList<>();
private int _hit= 0;
private int _round = 1;


protected void onSaveInstanceState(Bundle out)
{
    super.onSaveInstanceState(out);

    out.putInt("p_hit", _hit);
    out.putInt("p_round", _round );
}


@Override
protected void onRestoreInstanceState(Bundle in)
{
    super.onRestoreInstanceState(in);

    _hit = in.getInt("p_hit");
    _round = in.getInt("p_round");
}

2 个答案:

答案 0 :(得分:0)

下面应该适合你:

protected void onSaveInstanceState(Bundle out) {
    super.onSaveInstanceState(out);
    out.putInt("p_hit", _hit);
    out.putInt("p_round", _round);
    out.getIntegerArrayList("_selectednumber");
    out.getIntegerArrayList("_points");
}


@Override
protected void onRestoreInstanceState(Bundle in) {
    super.onRestoreInstanceState(in);
    _hit = in.getInt("p_hit");
    _round = in.getInt("p_round");
    _selectednumber = in.getIntegerArrayList("_selectednumber");
    _points = in.getIntegerArrayList("_points");
}

答案 1 :(得分:0)

您可以使用putIntegerArrayList()来存储数据,并使用getIntegerArrayList()来检索数据。但是,您已将变量声明为List<Integer>,但不满足putIntegerArrayList()的要求。

你有两个选择。首先,您可以更改声明变量的方式,使其明确ArrayList s,而不仅仅是List s:

private ArrayList<Integer> _selectednumber= new ArrayList<>();
private ArrayList<Integer> _points = new ArrayList<>();
private int _hit= 0;
private int _round = 1;

protected void onSaveInstanceState(Bundle out)
{
    super.onSaveInstanceState(out);

    out.putInt("p_hit", _hit);
    out.putInt("p_round", _round );
    out.putIntegerArrayList("p_selectednumber", _selectednumber);
    out.putIntegerArrayList("p_points", _points);
}

@Override
protected void onRestoreInstanceState(Bundle in)
{
    super.onRestoreInstanceState(in);

    _hit = in.getInt("p_hit");
    _round = in.getInt("p_round");
    _selectednumber = in.getIntegerArrayList("p_selectednumber");
    _points = in.getIntegerArrayList("p_points");
}

或者,当您尝试将List实例放入捆绑包中时,可以将new ArrayList<>()个实例包裹起来:

private List<Integer> _selectednumber= new ArrayList<>();
private List<Integer> _points = new ArrayList<>();
private int _hit= 0;
private int _round = 1;

protected void onSaveInstanceState(Bundle out)
{
    super.onSaveInstanceState(out);

    out.putInt("p_hit", _hit);
    out.putInt("p_round", _round );
    out.putIntegerArrayList("p_selectednumber", new ArrayList<>(_selectednumber));
    out.putIntegerArrayList("p_points", new ArrayList<>(_points));
}

@Override
protected void onRestoreInstanceState(Bundle in)
{
    super.onRestoreInstanceState(in);

    _hit = in.getInt("p_hit");
    _round = in.getInt("p_round");
    _selectednumber = in.getIntegerArrayList("p_selectednumber");
    _points = in.getIntegerArrayList("p_points");
}