我无法处理错误?

时间:2015-04-13 05:08:24

标签: android error-handling

我有方法

 public static List<Transaction> getTransactions(){
 if (ShoppingSessionDao.getCurrentShoppingSession()==null){
            //what return?
        }
        return new Select().from(Transaction.class).where("shoppingSession = ?",
                    ShoppingSessionDao.getCurrentShoppingSession().getId()).execute();
    }

它返回包含数据的列表。

然后我做

private void setData() {
    transactionList = TransactionDao.getTransactions();
    baseAdapter = new BasketAdapter(transactionList);
    gridView.setAdapter(baseAdapter);
}

但有时(如果ShoppingSession为空)ShoppingSessionDao.getCurrentShoppingSession()则返回NULL。

如何处理此错误?

溶液

private void setData() {
        ShoppingSession shoppingSession = ShoppingSessionDao.getCurrentShoppingSession();
        if (shoppingSession==null){
            return;
        }
        transactionList = TransactionDao.getTransactions(shoppingSession);
        baseAdapter = new BasketAdapter(transactionList);
        gridView.setAdapter(baseAdapter);
        tvPrice.setText(calculateTotalSum());
    }

public static List<Transaction> getTransactions(ShoppingSession shoppingSession){
        return new Select().from(Transaction.class).where("shoppingSession = ?",
                shoppingSession.getId()).execute();
    }

1 个答案:

答案 0 :(得分:0)

我认为有两种方法可以实现这一点。解决方法之一就是用这样的try catch包围你的代码:

try {       
        ShoppingSession shoppingSession = ShoppingSessionDao.getCurrentShoppingSession();
        transactionList = TransactionDao.getTransactions(shoppingSession);
        baseAdapter = new BasketAdapter(transactionList);
        gridView.setAdapter(baseAdapter);
        tvPrice.setText(calculateTotalSum());

    } catch (NullPointerException ex) {
        Log.e("Error: ", ex.getLocalizedMessage());
//Do error handling here
    }

另一种方法是使用以下代码扩展您正在使用的当前方法:

ShoppingSession shoppingSession = ShoppingSessionDao.getCurrentShoppingSession();
        if (shoppingSession != null) {
            transactionList = TransactionDao.getTransactions(shoppingSession);
            baseAdapter = new BasketAdapter(transactionList);
            gridView.setAdapter(baseAdapter);
            tvPrice.setText(calculateTotalSum());
        } else {
            tvPrice.setText("Shopping session is null");
//Do error handling here
        }