Android - 为什么我得到一个nullpointer异常(SQLite)

时间:2014-03-20 02:33:10

标签: android sqlite nullpointerexception cursor android-cursorloader

我想从我的数据库中获得平均值。我实例化一个cursorloader,然后调用一个方法来返回一个游标。 (loadInBackGround)。根据logcat,这是我得到nullpointer异常的地方:

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

将rawquery设为(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)

我不知道为什么会得到nullpointer异常。 非常感谢!

编辑: 这是我的数据库设置的位置,它从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;
}

...

1 个答案:

答案 0 :(得分:-1)

您的数据库很可能为null,也许您可​​以调试以找出它的值。