In android the second time I call an alert dialog it forces closed
I have some code to use an alert dialog to add stuff to a database. this works, but only the first time I use it. The second time I press the button to open the alert dialog it force closes.
final AlertDialog.Builder alert1 = new AlertDialog.Builder(EmergencyDb.this);
final AlertDialog.Builder alert2 = new AlertDialog.Builder(EmergencyDb.this);
alert1.setTitle("New Contact");
alert1.setMessage("Name: ");
alert2.setTitle("New Contact");
alert2.setMessage("Phone Number: ");
final EditText input1 = new EditText(EmergencyDb.this);
final EditText input2 = new EditText(EmergencyDb.this);
final int PHONE_TYPE = 3;
input2.setInputType(PHONE_TYPE);
alert1.setView(input1);
alert2.setView(input2);
alert1.setPositiveButton("Next", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
name = input1.getText().toString();
alert2.show();
}
});
alert2.setPositiveButton("Add", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
phoneNum = input2.getText().toString();
SQLiteDatabase db = openHelper.getReadableDatabase();
openHelper.addContact(name, phoneNum, db);
Cursor cursor = null;
try {
cursor = getContactCursor();
SimpleCursorAdapte开发者_运维百科r adapter = new SimpleCursorAdapter(EmergencyDb.this,
R.layout.row, cursor, COLUMNS, VIEWS);
setListAdapter(adapter);
}
catch (Exception ex){
//... error handling
}
}
});
alert1.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert2.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
final Button addButton = (Button) findViewById(R.id.addButton);
addButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
alert1.show();
}
});
Maybe the problem is in final access modifier? However, check your logcat to find the answer. Good luck!
You probably have to dismiss()
or cancel()
the alerts before you show another one or things could get confused. Add a call to dialog.cancel()
in the onClick
methods.
alert1.setPositiveButton("Next", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
name = input1.getText().toString();
dialog.cancel(); alert2.show();
}
});
Let me know if that works.
精彩评论