Android AlertDialog等待呼叫活动的结果



我正在尝试在我的应用程序中使用AlertDialog来选择项目的数量。问题在于,调用AlertDialog的活动在将项目添加到 SQLite 数据库并更改意向之前不会等待它更新项目。

此时,QuantitySelectorAlertDialog)出现,然后立即消失,并通过意图更改更改更改MealActivity类(这只是从数据库中读取的ListView),并对数量为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();
    }
}

来自 favoritesAdapter 的方法(调用 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);
            }
        });

感谢所有帮助:)

使用异步任务并在doInBackGround和onPostExecute方法Show Dialog中更新数据。

你想要这样做的方法是在对方按下肯定按钮时实际开始下一个意图。 简而言之,您需要在附加到警报对话框的正面按钮的OnClickListener中启动下一个活动。

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();
                    //The only catch now is passing through your _context
                    Intent intent = new Intent(_context,MealActivity.class);
                    _context.startActivity(intent);
                }
            })
            .setNegativeButton("Cancel", null).create();
        dialog.show();
}

实际上,您的问题是您在销毁警报对话框之前调用了 MealACtivity 的启动活动,因此可以按如下方式更新代码:

更新通过以下代码调用警报对话框的方法:

    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);*/
        }
    });

并使用以下方法更新数量选择器类:

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);
                        Intent intent = new Intent(_context,MealActivity.class);
                        _context.startActivity(intent);
                        dialog.dismiss();
                    }
                })
                .setNegativeButton("Cancel", null).create();
            dialog.show();
    }

最新更新