Reputation: 520
I'm learning Android Development and started creating an app which has about 20 dialog (yes, no button). I planned to create a class which will return true or false upon yes/no press. Then class is here
public class CustomDialog{
Boolean Resp;
public Boolean Confirm(Activity act, String Title, String ConfirmText,
String CancelBtn, String OkBtn) {
AlertDialog dialog = new AlertDialog.Builder(act).create();
dialog.setTitle(Title);
dialog.setMessage(ConfirmText);
dialog.setCancelable(false);
dialog.setButton(DialogInterface.BUTTON_POSITIVE, OkBtn,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int buttonId) {
Resp = true;
}
});
dialog.setButton(DialogInterface.BUTTON_NEGATIVE, CancelBtn,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int buttonId) {
Resp = false;
}
});
dialog.setIcon(android.R.drawable.ic_dialog_alert);
dialog.show();
if (Resp == null){
Resp = false;
}
return Resp;
}
}
Now when I'm calling this from main activity, within a button click listener, app is crushing.
@Override
public void onClick(View v) {
if (v.getId() == R.id.Toast){
CustomDialog tans = new CustomDialog();
boolean tan = tans.Confirm(MainActivity.this, "Message Title", "Message Text Goes Here", "No", "Yes");
if (tan){
Toast.makeText(this, "wow", Toast.LENGTH_LONG).show();
}
}
}
I need your advice to fix.
EDIT: I've updated my code, app isn't crushing now but no toast while pressing Yes.
Upvotes: 0
Views: 539
Reputation:
Try instead of this to MainActivity.this as follow:
Boolean tan = tans.Confirm(MainActivity.this, "Confirmation", "Are you sure?", "No", "Yes");
Also one more thing your Boolean tan variable value is null as Resp variable is not initialized during tans.Confirm method is called. Resp value is changed only after user click Yes or No button.
Upvotes: 1