从中访问数据之前,初始化SQLite光标



我试图将数据插入SQLite DB,一旦通过FCM收到通知。为了调试目的,当显示" show token"活动时,我还将一个虚拟数据插入我的数据库。

但是,我得到了

"我得到的"无法从Cursorwindow读取第0行,Col -1。在从中访问数据之前,请确保光标已正确初始化。"

链接到我的代码: - github

有人可以浏览我的代码,让我知道我要在哪里做错了什么。

注释 - 我在下面添加了homescreen.java,myfirebasemessagingservice.java和notificationdetails.java

private sqlitedb dbhelper = new sqlitedb(this);
由于建议
私人sqlitedb dbhelper;
对我不起作用

当我上述使用时,我一直在获得NullPointer异常,因此我想知道SQLitedB类构造函数正在接受上下文,所以让我通过一个,帖子,我没有获得NullPointer异常。

现在,我做到了这一点,而没有完全意识到我一直试图缠绕头的上下文概念,但是由于对Android是一个极端的菜鸟,所以我无法掌握它。我怀疑这可能与我所经历的上下文有关。

有人可以通过有关如何解决此问题的详细说明来帮助我,我已经通过了许多其他线程,但是在经历了5个小时的多次SO问题之后,我无法修复此问题,我正在发布此问题。

事先感谢社区中的每个人的帮助。:)

编辑

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

我在哪里调用光标

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

getAllnotification函数

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

无法从Cursorwindow读取第0行-1。

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

最有可能的原因是,光标方法 getColumnIndex(the_column_name_as_a_string)将返回 -1 当将列传递给该方法的 -1 在光标中找不到。注意到由于错误列名称是案例敏感的。

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

从外观上看,您应该使用字符串变量 notification_details ,因此您可能需要使用: -

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

附加

您绝对不要假设MovetoFirst(或任何光标移动???方法)实际上是移动的。您应该始终检查返回的值。它将是 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&lt; rs.getColumnCount(); i ){ notification_array.add(rs.getString((rs.getColumnIndex(notification_details))))); }} while(rs.movetonext());

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

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

最新更新