issue with program flow when rotating device with two activities
My first activity is creating a second activity within its onCreate:
if (userName == null || password == null) {
if (!getUserNameAndPassword() ) {
// User is launching this for the first time
Intent explicitIntent = new Intent(CreateSessionAlert.this,CreateUserNameAndPassword.class);<br>
startActivityForResult(explicitIntent,GET_USER_NAME_AND_PASSWORD);
}
}
The second activity has EditText views for the username and password along with submit and cancel buttons. When either button is pushed, the text from username and password is sent back to activity one (via onActivityResult), which connects to a server to see if the username is available. While connecting开发者_开发百科 to the server showDialog is used to show a ProgressDialog. When the server responds, the ProgressDialog is dismissed and an AlertDialog is shown. This works fine as long as the device is not rotated.
Here's the problem: if the user rotates the device from within the second activity and pushes submit, the first activity re-invokes its onCreate, which ends up launching the second activity again since the username and password are still null.
Does anyone have any suggestions to get around this?
Is there a method that could be used to pass data from activity-2 to activity-1's onCreate? I wouldn't want to use a database in this case, as that seems like overkill.
I've thought about containing the server communication and dialogs to activity 2, but then I'd have duplicate server code in activity 1 and activity 2 (activity 1 connects to the server for other things too). Another issue I'd have with this approach is that the user has an option to cancel creating the password, in which case I want the app to finish. If I called finish from activity 2, activity 1 would appear and I don't want that to show unless a username and password have been created.
It just occurred to me - if I could replace activity 2 with a dialog it might make things simpler. The dialog view needs to have 2 EditTexts and 2 buttons. Can I create something like this and use the showDialog method? Any other ideas?
You can just add:
<activity android:name="..."
android:label="@string/appName"
android:configChanges="keyboardHidden|orientation" />
to the activity in your manifest. This will prevent the activity from being destroyed on the screen rotation.
Beware that you still have to save the state of your activities in the onPause method. Just test what happens if you press the home button while the user logs in or recieve a call during logging in. This should remove your Activity from the memory and some more problems may occur.
精彩评论