【问题标题】:I can not handle error?我无法处理错误?
【发布时间】:2015-04-13 05:08:23
【问题描述】:

我有方法

 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()return me 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();
    }

【问题讨论】:

  • 添加try catch异常
  • @"什么回报?"返回null并在调用者方法中处理它?这甚至是一个“好”的问题吗? How do I ask a good question?

标签: android error-handling


【解决方案1】:

在我看来,有两种方法可以实现这一点。解决方案之一是用这样的 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
        }

【讨论】:

    猜你喜欢
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-01
    • 2016-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多