I am trying to store the text inside many TextViews to restore in a new Activity and I would like to know how can I do this using a for loop instead of doing one by one.
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
    String item1;
    String item2;
    String item3;
    if (listItem1!=null){
        item1 = listItem1.getText().toString();
        outState.putString(TEXT_SAVED, item1);
    }
    if (listItem2!=null){
        item2 = listItem2.getText().toString();
        outState.putString(TEXT_SAVED, item2);
    }
    if (listItem3!=null){
        item3 = listItem3.getText().toString();
        outState.putString(TEXT_SAVED, item3);
    }
    super.onSaveInstanceState(outState);
}
Thanks for helping me.
                        
You can get your values of your
listItems via reflection. In this given example you need to replaceDataby the class yourlistItems are from. You need for this example the getters for your listItems, e.g.Via the line starting with Method method you are getting the
Getterdynamic from the current index in thefor-loop. In the next line, the method (in this case, theGetteris called and the value of this method call is returned. Please be aware that reflection is causing the following exceptions:IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException |SecurityException. These exceptions need to be handeld in case something went wrong.Another possible solution would be to store all your listItems in a
java.util.Listand looping over it.