游标非法状态异常出错

时间:2013-09-05 08:20:25

标签: android database sqlite cursor

我收到了这个错误。

09-05 16:17:27.460: E/CursorWindow(29553): Failed to read row 0, column -1 from a CursorWindow which has 1 rows, 8 columns.
09-05 16:17:27.465: E/AndroidRuntime(29553): FATAL EXCEPTION: main
09-05 16:17:27.465: E/AndroidRuntime(29553): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nesv.landstar/com.nesv.landstar.LandstarPage}: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.

我不知道我的代码出了什么问题。这是:

Cursor c = null;

        try
        {
            c = landstarDB.rawQuery("SELECT * FROM DriverShipment", null);
        }catch (Exception e) {
            Log.w("Error selecting table", "Error selecting table");
        }

 if (c != null && c.moveToFirst()) {
         c.moveToFirst();
         do {
             Log.i("cctid:", c.getString(c.getColumnIndex("cctid")));
             if(c.getString(c.getColumnIndex("cctid")) == cctid)
             {
                 isRecorded = true;
                 shipmentId = c.getString(c.getColumnIndex("cctid"));
                 origin = c.getString(c.getColumnIndex("origin"));
                 destination = c.getString(c.getColumnIndex("destination"));
                 protectTime = c.getString(c.getColumnIndex("protect_time"));
                 readyTime = c.getString(c.getColumnIndex("ready_time"));
                 etat = c.getString(c.getColumnIndex("eta"));

                 if(c.getString(c.getColumnIndex("isAccepted")) == "1")
                 {
                     isAccepted = true;
                 }
             }
         }while(c.moveToNext());
        }
            c.close();

有什么想法吗?谢谢!

3 个答案:

答案 0 :(得分:0)

您有两次致电 c.moveToFirst();

if (c != null && c.moveToFirst()) {
         c.moveToFirst(); // Remove this one

答案 1 :(得分:0)

column -1告诉您没有列cctidgetColumnIndex返回-1。

另外

c.getString(c.getColumnIndex("cctid")) == cctid

不行。使用equals方法比较字符串。

我建议您发布表创建查询,以便我们可以看到列不存在的原因。

答案 2 :(得分:0)

按以下方式更改循环:

if (c.getCount > 0) {
     c.moveToFirst();
     do {
         Log.i("cctid:", c.getString(c.getColumnIndex("cctid")));
         if(c.getString(c.getColumnIndex("cctid")) == cctid)
         {
             isRecorded = true;
             shipmentId = c.getString(c.getColumnIndex("cctid"));
             origin = c.getString(c.getColumnIndex("origin"));
             destination = c.getString(c.getColumnIndex("destination"));
             protectTime = c.getString(c.getColumnIndex("protect_time"));
             readyTime = c.getString(c.getColumnIndex("ready_time"));
             etat = c.getString(c.getColumnIndex("eta"));

             if(c.getString(c.getColumnIndex("isAccepted")) == "1")
             {
                 isAccepted = true;
             }
         }
     }while(c.moveToNext());
    }