android中的SUM查询的空对象引用

时间:2015-04-11 19:48:37

标签: android sqlite nullpointerexception

当我尝试查询我的数据库中的列总和时,我收到一个空对象引用错误。

据我所知,查询代码是正确的。

这是我的问题:

int tripSummary(){
    int distance;
    Cursor mCursor = mDb.rawQuery("SELECT SUM (distance) FROM Trip WHERE vehicle = 'Car';", null);

    if(mCursor.moveToFirst()) {
        distance = mCursor.getInt(0);
    }else{
        distance = -1;
    }
    return distance;
}

以下是我从以下地址调用查询的片段:

    public class SummaryFragment extends Fragment {

TripsDbAdapter dbHelper;

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.summary_fragment, container, false);

    String carbonFootprint = "Your carbon footprint for all all trips by category is:";
    TextView footprint = (TextView) view.findViewById(R.id.carbonFootprint);
    footprint.setText(carbonFootprint);

    String carTrips = "Total distance for car = " + calculateFootprint();
    TextView car = (TextView) view.findViewById(R.id.car);
    car.setText(carTrips);

    return view;
}

public int calculateFootprint(){

    dbHelper.tripSummary();

    int distance = dbHelper.tripSummary();

    return distance;
}

这是logcat:

    E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.brianmcmahon.carbonfootprintcalculator, PID: 3914
java.lang.NullPointerException: Attempt to invoke virtual method 'int com.brianmcmahon.carbonfootprintcalculator.TripsDbAdapter.tripSummary()' on a null object reference
        at com.brianmcmahon.carbonfootprintcalculator.SummaryFragment.calculateFootprint(SummaryFragment.java:41)
        at com.brianmcmahon.carbonfootprintcalculator.SummaryFragment.onCreateView(SummaryFragment.java:32)
        at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1126)
        at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1489)
        at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:454)

任何建议将不胜感激。

1 个答案:

答案 0 :(得分:0)

好吧,正如stacktrace所说的那样,你永远不会从我能看到的dbHelper中分配任何值。因此,预计dbHelper.tripSummary();会引发NPE。您应该根据应用程序的逻辑将dbHelper设置为某个内容。