我使用此活动在表格布局中显示产品信息。当没有产品或没有产品信息时,当我开始此活动时,我得到一个空指针异常。我该如何处理?
public void startSalesReportActivity() {
Intent salesRepIntent = getMiAirlineActivity().getSalesReportActivityIntent();
double netTotalValue = SalesUtil.calculateFlightTransactionTotal(purchaseDao, refundDao, getMiAirlineActivity());
BigDecimal bigDecimal = new BigDecimal(netTotalValue);
bigDecimal = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
salesRepIntent.putExtra(TOTAL_VALUE, String.valueOf(bigDecimal));
startActivity(salesRepIntent);
}
我在上述活动中调用此方法来计算我的产品信息。
public static double calculateFlightTransactionTotal(PurchaseDao purchaseDao, PurchaseRefundDao purchaseRefundDao, AirlineActivity activity) {
double purchaseAmount = calculateFlightLegPurchaseTransactions(purchaseDao, activity);
double refundAmount = calculateFlightLegRefundTransactions(purchaseRefundDao, activity);
double netAmount = purchaseAmount - refundAmount;
return (netAmount > 0) ? netAmount : 0;
}
导致NPE的行是双netTotalValue = ...
FATAL EXCEPTION: main
Process: com.miairline, PID: 8096
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.miairline.model.PurchaseDao.getSuccessfulTransactions()' on a null object reference
at com.miairline.utils.SalesUtil.calculateFlightLegPurchaseTransactions(SalesUtil.java:43)
at com.miairline.utils.SalesUtil.calculateFlightTransactionTotal(SalesUtil.java:35)
at com.miairline.settings.SettingsFragment.startSalesReportActivity(SettingsFragment.java:1134)
at com.miairline.settings.SettingsFragment$22.onClick(SettingsFragment.java:1114)
答案 0 :(得分:1)
将它放入if ... else语句中。 例如,
if(value == null || value < 0)
{
// Your code
}
else
{
}
或
if(!value==null)
{
// Your code
}
else
{
}
并且对于崩溃问题使用try..catch Block。