2015-01-15 25 views
0

我的應用程序讀取行1,第1欄是扔我例外:安卓:錯誤:無法從CursorWindow

Error: Couldn't read row 1, col 1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.

這裏是我的功能:

static public String[] getData(Context ctx) { 
    String[] result = null; 
    try { 
     SQLiteDatabase db = ctx.openOrCreateDatabase("mydatabase", 0, 
       null); 
     Cursor c = db.query("answers", new String[]{"answer"}, "id_question='1'", null, null, null, null); 
     if (c.getCount() == 0) { 
      return null; 
     } 

     result = new String[c.getCount()]; 
     c.moveToFirst(); 

     for (int i = 0; i < c.getCount(); i++) { 
      result[i]=c.getString(i); 
      Log.v(TAG, "Answer "+c.getString(i));//responds just on 1st time 
      c.moveToNext(); 
     } 
     c.close(); 
     db.close(); 

     return result; 
    } catch (Exception e) { 
     Log.e(TAG, 
       "Database.getData(Context) - Error: " 
         + e.getMessage()); 
     return result; 
    } 
} 

表結構:

db.execSQL("CREATE TABLE IF NOT EXISTS answers (id INTEGER PRIMARY KEY AUTOINCREMENT, " + "id_question VARCHAR, answer VARCHAR);"); 

當我把光標放在搜索列中只是爲了列

  • 「回答」 的結果是[TTTTT,NULL,NULL] - ,其中TTTTT是第一答案
  • 「id_question」 的結果是[1,NULL,NULL]
  • 空結果爲[1,1,WWWWW ] - 其中1是id_question和wwww是最後一個答案

我在做什麼錯?

我將不勝感激任何幫助。謝謝!

+1

您在移動** **對角線,而不是** **縱:列索引,增加......超出其限制。這裏:'result [i] = c.getString(i);''你想要類似'result [i] = c.getString(0); // 0是答案欄# – 2015-01-15 17:01:19

回答

2

Cusror.getCount返回光標中的行數。使用Cursor.getColumnCount()從行獲得列:

result = new String[c.getColumnCount()]; 
for (int i = 0; i < c.getCount(); i++) { 
     for(int j=0;j<c.getColumnCount();j++){ 
     result[j]=c.getString(j); << here pass column index 
     } 
    .... 
    } 
+0

天啊。我昨天顯然真的很累。謝謝! =) – 2015-01-16 06:07:17

1

這是您的解決方案:

result = new String[c.getColumnCount()]; 
for (int i = 0; i < c.getCount(); i++) { 
for(int ii=0;ii<c.getColumnCount();ii++){ 
result[ii]=c.getString(1); 
.... 
}