Using for loop to store text of TextView

95 Views Asked by At

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.

1

There are 1 best solutions below

0
On

You can get your values of your listItems via reflection. In this given example you need to replace Data by the class your listItems are from. You need for this example the getters for your listItems, e.g.

public Data getListItem1() {
    return listItem1;
}

Via the line starting with Method method you are getting the Getter dynamic from the current index in the for-loop. In the next line, the method (in this case, the Getter is 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.

@Override
protected void onSaveInstanceState(@NonNull Bundle outState) throws Exception {
    for (int i = 1; i <= 3; i++) {
        Method method = this.getClass().getDeclaredMethod("getListItem" + i);
        method.setAccessible(true);
        Data data = (Data) method.invoke(this);
        if(data != null) {
            String value = data.getText().toString();
            outState.putString(TEXT_SAVED, value);
        }
    }
    super.onSaveInstanceState(outState);
}

Another possible solution would be to store all your listItems in a java.util.List and looping over it.