ListView with AlertDialog Validation
How can I apply validation to a ListView using an AlertDialog? My scenario is this, I need to have the user select the State from which they are doing a search from. The values of the State are defined in a spinner. If the user clicks on a Listview item without selecting a state I have defined an AlertDialog below.
The problem I am encountering is that the alert box displays but does not stop the execution of the underlying task.
How can I stop the execution of my AsyncTask until the user 开发者_如何转开发has selected a State from the spinner? Are there any examples showing how to validate that the user has made a selection from a spinner prior to kicking off an AsyncTask?
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View itemClicked, int position, long id) {
// This code executes just fine but runs asynchronous with my SearchProducts task.
String selectedState = spinner.getSelectedItem().toString();
if(selectedState.equals("Choose Your State")) {
alertbox("State", "Please Choose Your State");
}
String strText = items[position];
if (strText.equalsIgnoreCase(getResources().getString(R.string.menu_search))) {
new SearchProducts().execute();
This is my AlertDialog code.
protected void alertbox(String title, String mymessage) {
new AlertDialog.Builder(this)
.setMessage(mymessage)
.setTitle(title)
.setCancelable(true)
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){}
})
.show();
}
I feel like such an amateur, I have implemented the dialog in the correct manner. What I was missing from my code was a "return" statement on my onClick for the AlertDialog. The updated code looks like this.
protected void alertbox(String title, String mymessage) {
new AlertDialog.Builder(this)
.setMessage(mymessage)
.setTitle(title)
.setCancelable(true)
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
return;
}
})
.show();
}
精彩评论