androidonsaveinstancestateonrestoreinstancestate

Send ArrayList<Integer> between Bundle


Problem:
How do I transfer the data of _selectednumber and _points from onSaveInstanceState to 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");
}

Solution

  • You can use putIntegerArrayList() to store the data, and getIntegerArrayList() to retrieve it. However, you've declared your variables as List<Integer>, which doesn't satisfy the requirements of putIntegerArrayList().

    You have two choices. First, you can change how you've declared your variables so that they are explicitly ArrayLists, not just Lists:

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

    Or, you can wrap your List instances with new ArrayList<>() when you try to put them into the bundle:

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