初始化SQLite游标,然后再从中访问数据

时间:2018-12-17 21:19:00

标签: android sqlite android-cursoradapter

一旦通过FCM收到通知,我正在尝试将数据插入SQLite DB。出于调试目的,当在HomeScreen活动中单击SHow Token时,我还将虚拟数据插入数据库。

但是得到

“我正在获取”无法从CursorWindow读取行0,col -1。在从游标访问数据之前,请确保游标已正确初始化。”

链接到我的代码:-GitHub

有人可以浏览我的代码,让我知道我要去哪里了。

注意-我在HomeScreen.java,MyFirebaseMessagingService.java和NotificationDetails.java中添加了

私有SQLiteDB dbHelper =新的SQLiteDB(this);
由于建议
私有SQLiteDB dbHelper;
不适用于我

当我在上面使用时,我一直在获取Nullpointer异常,因此我认为由于SQLiteDB类构造函数正在接受上下文,因此让我传递一个,后发我没有获得NullPointer异常。

现在,我在做此操作的时候并没有完全意识到我一直想绕过它的上下文的概念,但是由于对Android来说是一个极端的菜鸟,所以我现在还无法掌握它。我怀疑这可能与我传递的上下文有关。

有人可以在这里提供有关如何解决此问题的详细说明,请帮助我,我已经通过其他许多线程进行了讨论,但是无法解决,因此在经历多个SO问题5小时后,我正在发布此问题。

在此先感谢社区中的每个人。 :)

编辑

根据管理员的建议,我将以下代码片段包括在内。

我在哪里调用游标

   dbHelper.insertNotification("This is a notification");
                //Check if the message contains data
                Cursor rs = dbHelper.getAllNotifications();
                rs.moveToFirst();
                token_text.setText("Token: " +rs.getString((rs.getColumnIndex("NOTIFICATION_DETAILS"))));

在SQLiteDB.java中插入通知功能

public boolean insertNotification(String notification){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(NOTIFICATION_DETAILS,notification);
    db.insert(NOTIFICATION_TABLE_NAME,null,contentValues);
    return true;
}  

getAllNotifications函数

public Cursor getAllNotifications() {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res =  db.rawQuery( "SELECT * FROM " + NOTIFICATION_TABLE_NAME, null );
    return res;
}

1 个答案:

答案 0 :(得分:2)

  

无法从CursorWindow读取行0,col -1。

是说您正在尝试从0行(第一行)获取偏移量为-1的列。因此,您提供了一个无效的偏移量 (偏移量不能为-1,偏移量必须为0或更大,并且最大值比游标中的列数少1)

最可能的原因是,当在游标中找不到传递给该方法的列时,游标方法 getColumnIndex(the_column_name_as_a_string)将返回 -1 。请注意,由于错误列名称是区分大小写的。

因此,您的问题是游标不包含列名 NOTIFICATION_DETAILS ,并且您使用了*(所有列),那么该列在表中不存在。

从外观上看,您应该使用String变量 NOTIFICATION_DETAILS ,因此您可能需要使用:-

token_text.setText("Token: " +rs.getString((rs.getColumnIndex(NOTIFICATION_DETAILS)))); //<<<<<<<<<< double quotation marks removed.

其他

您永远不要以为moveToFirst(或任何Cursor move ????方法)实际上是在进行移动。您应该始终检查返回的值。如果移动成功,将为 true ,否则为 false

  • 再次请注意,传递给getColumnIndex方法的列名称取决于大小写。

  • 因此,您应该使用

:-

       dbHelper.insertNotification("This is a notification");
       //Check if the message contains data
       Cursor rs = dbHelper.getAllNotifications();
       if (rs.moveToFirst()) {
           token_text.setText("Token: " +rs.getString((rs.getColumnIndex(NOTIFICATION_DETAILS))));
       } else {
           ........ code here if anything need to be done if there are no rows extracted 
       }

补充评论:-

  

光标rs = dbHelper.getAllNotifications(); rs.moveToFirst();做   (int i = 0; i

使用以下内容要简单得多:-

Cursor rs = dbHelper.getAllNotifications();
while (rs.moveToNext()) {
    notification_array.add(rs.getString((rs.getColumnIndex(NOTIFICATION_DETAILS))));
}