我正在尝试AlertDialog
在我的应用程序中使用一个来选择物品的数量。问题是调用 的活动在AlertDialog
将项目添加到 SQLite 数据库并更改意图之前不会等待它更新项目。
此时,QuantitySelector
( AlertDialog
) 出现,然后立即消失,并通过意图更改更改MealActivity
类(这只是ListView
从数据库中读取的 a),并更新数量为 0 的数据库。
我需要在它更新数据库之前Activity
等待它关闭。AlertDialog
实现这一点的正确方法是什么?
这是给你的一些代码:
QuantitySelector
(运行警报对话框):
public class QuantitySelector{
protected static final int RESULT_OK = 0;
private Context _context;
private DatabaseHandler db;
private HashMap<String, Double> measures;
private Item item;
private View v;
private EditText quan;
private NumberPicker pick;
private int value;
private Quantity quantity;
/**
* Function calls the quantity selector AlertDialog
* @param _c: The application context
* @param item: The item to be added to consumption
* @return The quantity that is consumed
*/
public void select(Context _c, Item item, Quantity quantity){
this._context = _c;
this.item = item;
this.quantity = quantity;
db = new DatabaseHandler(_context);
//Get the measures to display
createData();
//Set up the custom view
LayoutInflater inflater = LayoutInflater.from(_context);
v = inflater.inflate(R.layout.quantity_selector, null);
//Set up the input fields
quan = (EditText) v.findViewById(R.id.quantityNumber);
pick = (NumberPicker) v.findViewById(R.id.numberPicker1);
//Set up the custom measures into pick
pick.setMaxValue(measures.size()-1);
pick.setDisplayedValues(measures.keySet().toArray(new String[0]));
//Start the alert dialog
runDialog();
}
public void createData(){
measures = new HashMap<String, Double>();
//Get the measurements from the database
if(item!=null){
measures.putAll(db.getMeasures(item));
}
//Add grams as the default measurement
if(!measures.keySet().contains("grams")){
//Add grams as a standard measure
measures.put("grams", 1.0);
}
}
public void runDialog(){
AlertDialog dialog = new AlertDialog.Builder(_context).setTitle("Select Quantity")
.setView(v)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Change the consumption to the new quantity
if(!quan.getText().toString().matches("")){
value = Integer.parseInt(quan.getText().toString());
//Check if conversion from other units is needed
String s[] = pick.getDisplayedValues();
String a = s[pick.getValue()];
//Convert the chosen measure back to grams
if(!a.equals("grams")){
for(String m : measures.keySet()){
if(m==a){
value = (int) (value * measures.get(m));
}
}
}
}
quantity.setQuantity(value);
dialog.dismiss();
}
})
.setNegativeButton("Cancel", null).create();
dialog.show();
}
}
favouritesAdapter 中的方法(调用 alertdialog):
add.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
QuantitySelector q = new QuantitySelector();
Quantity quan = new Quantity();
q.select(_context, db.getItem(p.getID()), quan);
db.addConsumption(p.getID(), p.getFavouriteShortName(), quan.getQuantity(), "FAVOURITE");
Intent intent = new Intent(_context,MealActivity.class);
_context.startActivity(intent);
}
});
感谢所有帮助:)