samedi 11 avril 2015

Null Object Reference on SUM query in android

I am getting a null object reference error when I try to query my db for the sum of a column.


As far as I can tell the query code is correct.


Here is my query:



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;
}


Here is the fragment that I call the query from:



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;
}


And here is the 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)


Any suggestions would be appreciated.


Aucun commentaire:

Enregistrer un commentaire