Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing Orientation, losing all my list items

While I tested my application on an Android Device turning my Android phone from landscape to portrait, results in all the list items in my list view are disappearing.

Why?

How to manage?

like image 593
soclose Avatar asked May 25 '10 07:05

soclose


People also ask

How do you change orientation when retaining data?

Another most common solution to dealing with orientation changes by setting the android:configChanges flag on your Activity in AndroidManifest. xml. Using this attribute your Activities won't be recreated and all your views and data will still be there after orientation change.

What happens on orientation change android?

When you rotate your device and the screen changes orientation, Android usually destroys your application's existing Activities and Fragments and recreates them. Android does this so that your application can reload resources based on the new configuration.


2 Answers

You are losing the list items because the default behavior for android during orientation change is to destroy your activity and recreate it. This behavior is chosen to enable android to recreate the activity with a new layout that may be used especially for the new orientation.

To prevent your list items from disappearing there are several thing that have to be done. The first thing that helps during orientation change is to simply reuse the same activity after the change. This can be done through adding this line

android:configChanges="keyboardHidden|orientation"

to the activity tag in your manifest you are experiencing the problem with. This is explained in more detail in this question.

The behavior you explained will likely also appear if the user opens the activity and then sends your application to the background does many other memory heavy stuff to get your application removed from memory and then revisits your app. If this is the case you have to overwrite the onSaveInstanceState method in you activity. How to this is explained in this question.

like image 85
Janusz Avatar answered Oct 01 '22 01:10

Janusz


The simplest way is to use onSaveInstanceState, explained in Janusz's answer.

However, if there are many items in your list, saving them into a Bundle in onSaveInstanceState could slow down the Activity recreation process, which the users would experience as a lag. To save relatively large data, use onRetainNonConfigurationInstance, then reload data in onCreate with getLastNonConfugurationInstance.

like image 29
molnarm Avatar answered Oct 01 '22 01:10

molnarm