Changing Orientation, losing all my list items
Asked Answered
M

3

14

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?

Magnanimity answered 25/5, 2010 at 7:50 Comment(1)
You know that if the orientation is changed, the onCreate() method is called again? I assume that that's why the items of your list are not added directly at starting the activity.Webbing
O
27

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.

Ophthalmoscopy answered 25/5, 2010 at 8:1 Comment(1)
In later API versions of Android, this should actually look something like this: android:configChanges="keyboardHidden|orientation|screenSize"Perkoff
R
6

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.

Rickie answered 25/5, 2010 at 9:25 Comment(0)
C
6

Try to add this in your activity:

android:configChanges="orientation|screenSize"

it works for me

Capriola answered 25/11, 2014 at 9:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.