I am trying to get an average from my database. I instantiate a cursorloader, and then call a method to return a cursor. (loadInBackGround). According to logcat this is where I get the nullpointer exception:
MyCursor = MyCursorLoader.loadInBackground();
This is where I create MyCursorLoader:
SQLiteCursorLoaderAverage MyCursorLoader = new SQLiteCursorLoaderAverage(getApplicationContext(),databaseHelper,null,null);
Heres my loadInBackground method:
public Cursor loadInBackground() {
Cursor cursor=buildCursor();
if (cursor!=null) {
// Ensure the cursor window is filled
cursor.getCount();
}
return(cursor);
}
Heres my buildCursorMethod:
protected Cursor buildCursor()
{
return(db.getReadableDatabase().rawQuery(rawQuery, null));
}
With the rawquery being (SELECT avg(numbers) FROM random)
I then get the average by doing this: MyCursor.getDouble(0);
My LogCat:
03-19 22:19:28.013: E/AndroidRuntime(1226): Caused by: java.lang.NullPointerException
03-19 22:19:28.013: E/AndroidRuntime(1226): tcom.example.helloworld.SQLiteCursorLoaderAverage.buildCursor(SQLiteCursorLoaderAverage.java:52)
03-19 22:19:28.013: E/AndroidRuntime(1226): at com.example.helloworld.AbstractCursorLoader.loadInBackground(AbstractCursorLoader.java:21)
03-19 22:19:28.013: E/AndroidRuntime(1226): at com.example.helloworld.AverageActivity.onCreate(AverageActivity.java:27)
I have no idea why I get the nullpointer exception. Thanks very much!
EDIT: Here is where my db gets set, it starts out as null.
public class SQLiteCursorLoaderAverage extends AbstractCursorLoader
{
SQLiteOpenHelper db=null;
String rawQuery=null;
String[] args=null;
Context context;
/**
* Creates a fully-specified SQLiteCursorLoader. See
* {@link SQLiteDatabase#rawQuery(SQLiteDatabase, String, String[])
* SQLiteDatabase.rawQuery()} for documentation on the
* meaning of the parameters. These will be passed as-is
* to that call.
*/
public SQLiteCursorLoaderAverage(Context newContext, SQLiteOpenHelper db, Bundle searchParameters, String[] args)
{
super(newContext);
this.db=db;
this.rawQuery=createQuery(searchParameters);
this.args=args;
context = newContext;
}
...
Your db is most likely null, maybe you can debug to find out the value of it.