0

I have a text field which indicates date selected by the user.Also i have provided a button for the user to change the currect date. The problem i am facing is as follows.

1 . In the Oncreate method i have set the textfield to the current date.When the activity gets created it displays the current date.

  1. I use the button and change the date to someother date.

All this works fine..

But when i rotate the device the oncreate again gets called and textfield gets changed to the current one. I want the textfield to retain the user selected one.

Please help me in this issue. Is there any way to prevent this ?

Rahul Raj
  • 367
  • 3
  • 17
  • Similar question: [Saving text view state on rotation][1] and more than a few others as well [1]: http://stackoverflow.com/questions/5179686/restoring-state-of-textview-after-screen-rotation – Idistic May 22 '12 at 17:08

2 Answers2

3

Screen rotation kills your activity and causes the entire lifecycle to restart. When this happens, onCreate will still have access to the original intent which began the activity, and certain widgets may retain some of their state (EditTexts, for example), but much of your dynamic Activity data will be lost. To prevent this, look into using the onSaveInstanceState method. This will allow you to put any important data members into a Bundle before rotation kills the screen. This Bundle is then passed to your onCreate as the parameter savedInstanceState. Here are the dev documents on this:

http://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState%28android.os.Bundle%29

In your case, you'll want to save your date value by putting it onto the Bundle as an extra. Then, in onCreate, check if savedInstanceState is not null, indicating that it contains your date and handled it accordingly. Also, make sure that if you set a default value for this text later on in the Activity Lifecycle, it does not clobber your retrieved date.

MattDavis
  • 5,158
  • 2
  • 23
  • 35
2

You need to save the variable before rotation. I think that the best option is use the Application class as a place to save variable and do it in onPause() function.

goodm
  • 7,275
  • 6
  • 31
  • 55