I am trying to create a very simple dialog box. I found the code references from the internet obviously.
My code is this:
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
ConsignmentConViewActivity.this);
alertDialog.setTitle("Alert Dialog");
alertDialog.setMessage("Welcome to AndroidHive.info");
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialogMain = alertDialog.create();
alertDialogMain.show();
The youtube videos and google link that talks about dialog boxes and are similar to the code above. It even works for the people showing the demo on youtube.
But when I run it, the dialog box appears for half a second like I can see it. and then closes automatically. It appears and then its gone.
I have also tried to reboot my system. Nothing works.
CodePudding user response:
Yes because you created it as it shows.
Why are you declaring a new variable as the below code if you already declared alertDialog
above?
AlertDialog alertDialogMain = alertDialog.create();
alertDialogMain.show();
This problem is showing because you are declaring a new variable when you have already declared it. Make your code as below I maintained.
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
ConsignmentConViewActivity.this);
alertDialog.setTitle("Alert Dialog");
alertDialog.setMessage("Welcome to AndroidHive.info");
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
}
});
alertDialog.create();
alertDialog.show();
OR USE DIRECT WITHOUT DECLARING VARIABLE
new AlertDialog.Builder(this)
.setTitle("Alert Dialog")
.setMessage("Welcome to AndroidHive.info")
//.setIcon(R.drawable.ic_round_warning) // set your dialog icon if you want to show. JJust uncomment.
.setPositiveButton("OK", (dialogInterface, i) -> {
Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
//dialogInterface.dismiss(); // for dismiss dialogbox
}).create().show();
Let me know if the problem not solved yet.
CodePudding user response:
After grinding on it for almost the whole day, I realized that I have an Intent function right after the dialog box. The intent function was switching to the next activity. By the time the dialog would appear, the next code (which was the intent) would run. The activity would change and thats why I was getting that problem.
It works all fine when i removed the intent. My code (in the question) is all correct and has no problem in it.