【发布时间】:2014-03-20 02:33:09
【问题描述】:
我正在尝试从我的数据库中获取平均值。我实例化了一个游标加载器,然后调用一个方法返回一个游标。 (loadInBackGround)。根据 logcat,这是我得到空指针异常的地方:
MyCursor = MyCursorLoader.loadInBackground();
这是我创建 MyCursorLoader 的地方:
SQLiteCursorLoaderAverage MyCursorLoader = new SQLiteCursorLoaderAverage(getApplicationContext(),databaseHelper,null,null);
这是我的 loadInBackground 方法:
public Cursor loadInBackground() {
Cursor cursor=buildCursor();
if (cursor!=null) {
// Ensure the cursor window is filled
cursor.getCount();
}
return(cursor);
}
这是我的 buildCursorMethod:
protected Cursor buildCursor()
{
return(db.getReadableDatabase().rawQuery(rawQuery, null));
}
原始查询为(SELECT avg(numbers) FROM random)
然后我通过这样做得到平均值:MyCursor.getDouble(0);
我的 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)
我不知道为什么会出现空指针异常。 非常感谢!
编辑: 这是我的数据库设置的地方,它以 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;
}
...
【问题讨论】:
-
要么 db 为 null,要么 db.getReadableDatabase 返回 null。根据给出的代码,我不知道是哪个。
-
添加SQLiteCursorLoaderAverage.buildCursor,出错的方法。
标签: android sqlite nullpointerexception cursor android-cursorloader