Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying alerts in Activity.onCreate(..)

Tags:

android

dialog

I am new to Android and this is my first question here so please go easy on me.

Is it possible to check some condition inside onCreate() of an Activity and display an AlertDialog?

I am creating an AlertDialog anonymously in Oncreate() and calling show on that instance but the AlertDialog is never displayed.

like image 337
eatSleepDrinkJava.repeat Avatar asked Aug 18 '10 06:08

eatSleepDrinkJava.repeat


People also ask

How do I add icons to alert dialog?

You can add an icon with the following code: Dialog dialog = new Dialog(context); dialog. requestWindowFeature(Window. FEATURE_LEFT_ICON); dialog.

Is OnCreate called only once?

OnCreate is only called once.


2 Answers

Showing an alert dialog in onCreate causes android.view.WindowLeaked exception, because the activity isn't yet created.

The solution I found is to put the code that shows the dialog in onStart() method:

@Override
protected void onStart() {
    super.onStart();
    // show dialog here
}
like image 124
kolufild Avatar answered Sep 17 '22 12:09

kolufild


It is definitely possible, try this:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Stackoverflow!").create().show();
}
like image 29
Konstantin Burov Avatar answered Sep 20 '22 12:09

Konstantin Burov