Question

I'm creating an Android app with an activity comprised of a mixture of static views and dynamically created views. The activity contains UI elements held in an XML file and UI elements which are created dynamically based on the content of a model class. (as in, there is an array in my model class and an EditText will be created for every element in the array.. and a Spinner will be created containing every element in a different array)

What's the usual method for saving and restoring the state of the application when dynamically created UI elements are involved? Because I won't always know which UI elements will exist at any one time! Currently, my binding code simply reloads the data from the database when the device orientation changes, losing any changes that the user made.

I've had a good look around on Google/SO for this and I've not found anything related to this problem.

Thanks all

Edit: For anyone that comes across this in the future, I did a slightly modified version of Yakiv's approach and wound up with this:

for (int i = 0; i < views.size(); i++) {
        View currentView = views.get(i);
        if (currentView instanceof CheckBox) {
            outState.putBoolean("VIEW"+i, (((CheckBox) currentView).isChecked()));
        } else if (currentView instanceof EditText) {
            outState.putString("VIEW"+i, ((EditText) currentView).getText().toString());
        } else if (currentView instanceof Spinner) {
            //.....etc. etc.
        }
    }

Thanks again Yakiv for the awesome idea.

Was it helpful?

Solution

To restore dynamic views state you need to make them as class fields and initialize them in onCreate. Then just use this article to save and restore their state.

private List<View> mViews= new ArrayList<View>();

@Override
public void onCreate(..)
{
  LinearLayout parent = ....//initialize it here
  initializeViews();
}

public void initializeViews()
{
  // create and add 10 (or what ever you need) views to the list here
  mViews.add(new View(this));
}

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  super.onSaveInstanceState(savedInstanceState);

  int mViewsCount = 0;
  for(View view : mViews)
  {
     savedInstanceState.putInt("mViewId_" + mViewsCount, view.getId());
     mViewsCount++;
  }

  savedInstanceState.putInt("mViewsCount", mViewsCount);
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);

  int mViewsCount = savedInstanceState.getInt("mViewsCount");;
  for(i = 0; i <= mViewsCount)
  {
     View view = mViews.get(i);

     int viewId = savedInstanceState.getInt("mViewId_" + i);
     view.setId(viewId);

     mViewsCount++;
  }
}

Best wishes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top