I am trying to use AlertDialog widget in my app, but whatever I do the app crashes at launch. I know something is messed up or not defined but can’t seem to find it.I have defined a button for triggering the alert dialog and set ‘yes’ and ‘no’ options for the dialog. Selecting ‘yes’ will result in exiting the app and showing a toast and Selecting ‘no’ will close the alert dialog and return to app by showing a toast. This is how it should work on paper but as I said the app will crash on launch.
My code:
package com.example.togglebutton;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends AppCompatActivity {
private Button bt;
AlertDialog.Builder builder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bt = (Button) findViewById(R.id.btn);
builder = new AlertDialog.Builder(this);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
builder.setMessage("Do you want to close this application ?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id, ) {
finish();
Toast.makeText(getApplicationContext(), "you chose yes",
Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
Toast.makeText(getApplicationContext(), "you chose no ",
Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
alert.setTitle("AlertDialogExample");
alert.show();
}
});
}
}
3
Answers
Because you forgot this line
Add
setContentView(R.layout.activity_main)
belowsuper.onCreate(savedInstanceState);
SOLUTION OF YOUR PROBLEM
You need to set the layout of the activity and in the above-posted code what we can see that it is missing. So just add the line below
super.onCreate(savedInstanceState);
NOTE: Replace YOUR_LAYOUT_NAME with the name of the layout file which you have defined for
MainActivity
.