如果总和更大,则创建例外

时间:2018-08-22 19:51:27

标签: java android sql

我正在尝试创建一个例外,但是我不知道该怎么做。 如果记录中的值的总和大于100000的总和,则不要。

buttonPurchase.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            ShoppingDAO shoppingDAO = new CompraDAO(getApplicationContext());

                            String amount = textTotal.getText().toString();
                            carros.setAmount(amount);
                            carros.setId_car(id);

                            SQLiteDatabase db = openOrCreateDatabase("DB_SHOPPING", MODE_PRIVATE, null);
                            Cursor c = db.rawQuery("SELECT * FROM shopping where id_car="+id, null);

                            Cursor c2 = db.rawQuery("SELECT SUM(price * amount) FROM shopping;", null);

                            if(c.getCount()>0) {
                                Toast.makeText(getApplicationContext(), "This purchase was made.", Toast.LENGTH_LONG).show();
                            } else {
                                if (c2.equals(100000)) {
                                    Toast.makeText(getApplicationContext(), "You have reached the maximum amount of purchases.", Toast.LENGTH_LONG).show();
                                } else {
                                    if (compraDAO.salvar(carros)) {
                                        Toast.makeText(getApplicationContext(), "Purchase saved successfully.", Toast.LENGTH_LONG).show();
                                    } else {
                                        Toast.makeText(getApplicationContext(), "Error saving.", Toast.LENGTH_LONG).show();
                                    }
                                }
                            }
                            c.close();
                        }

                    });

2 个答案:

答案 0 :(得分:2)

在您的代码中,您只需要更新if / else逻辑。

if(c.getCount()>0 && c2.intValue() < 100000){
   Toast.makeText(getApplicationContext(), "This purchase was made.", Toast.LENGTH_LONG).show();
} else {
   if(c2.intValue() >= 100000){
       Toast.makeText(getApplicationContext(), "You have reached the maximum amount of purchases.", Toast.LENGTH_LONG).show();
   } 
   ...
   ...
}

答案 1 :(得分:1)

好吧,我了解到创建自定义异常不是一个好习惯,因为如果您知道该异常,则应该阻止该异常,但是其他人回答了执行该异常的方法,因此您可以做到这一点。