user1583209 user1583209 - 23 days ago 12
Android Question

OnCreate dialog and screen rotation

I have an alertDialog in the onCreate() of my activity, which sets certain properties of the activity.

public class MyActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myactivity);

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("My Dialog");
alertDialogBuilder
.setCancelable(false)
...

AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}


When I start the activity, the dialog is started and after submitting the dialog the properties are set and the dialog is dismissed. So far so good.

However, if at this point (after submitting/dismissing the dialog), I rotate the device/screen, onCreate() is called again and the dialog is opened again (which I don't want).

How do I prevent opening the dialog on screen rotation? Or should I create the dialog somewhere else (not in onCreate() of the activity)?

Answer

your problem is onCreateMethod called in each time you rotate the screen you can override onSaveInstanceState method to save instance of your current layout

boolean isSubmited=false;
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putBoolean(isSubmited, true);


// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}

Now when you submit the dialog, change isSubmited to true then type

if(isSubmited)
alertDialog.show();

reference http://developer.android.com/training/basics/activity-lifecycle/recreating.html