Tutorial :Android ListView in Activity getting Refreshed on Changing Orientation



Question:

I have Activity with ListView inside it and in the onCreate method of the Activity I have code for populating the Data of the ListView this Data is a server based and so populating includes calling Network URLs. I have the ArrayAdapter of the ListView in the Same Activity Class.

Now the Issue I'am facing is that, in Rest all scenarios my Activity is behaving in a proper way but when the Orientation [ Portrait to Landscaped or other way round] is taking place the Data is Getting lost and Newer Data calls are Required to Populate the Same Old Data now this is something that is not intended out the code how should I deal with it.


Solution:1

Android will stop and restart your activity unless you've told it you will handle orientation changes yourself. It does this so that you can specify different resources (such as layouts) that are orientation-specific (among other reasons).

You need to add android:configChanges="orientation" to your activity delcaration in your AndroidManifest.xml, and you need to override onConfigurationChanged(). I don't believe you need to do anything special inside onConfigurationChanged(), simply implementing it should do the trick.


Solution:2

For those targeting API 13 or higher, "screenSize" should also be used. If that is your case, add

android:configChanges="orientation|screenSize"  

to your Android manifest.

More information here.


Solution:3

AFAIK the whole Activity gets recreated on an orientation change! The same is true if you switch to anoter app and return back later. I would suggest to store the data is the SharedPreferences or serialize them into XML and store them.

Another possibility could be to register your own service that stores the data in memory and the activity poluplates the data from the service.


Solution:4

Why not saving any data into a parceable and if the bundle you get in onCreate contains a saved state of data re-set the list adapter? Here is a nice code sample on this: http://blog.cluepusher.dk/2009/10/28/writing-parcelable-classes-for-android/


Solution:5

android:configChanges="orientation|screenSize"  

this code will work only if we don't have another layout for landscape mode!


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »