2011-11-14 48 views
0

我正在製作一個android數據庫應用程序,其中當我使用光標從數據庫獲取值時 它給了我以下例外。Android:java.lang.IllegalStateException:從行0得到字段插槽col -1失敗

java.lang.IllegalStateException: get field slot from row 0 col -1 failed 

我使用下面的代碼進行獲取:

public Cursor fetchChildren(String KEY_){ 

      Cursor c = db.rawQuery("SELECT children FROM " + DATABASE_TABLE_NAVIGATION 
        + " WHERE key_ = ?", new String[] {KEY_}); 
       return c; 
      } 



    try{ 
    for(int k=0;k<n;k++){ 
     db.open(); 
    System.out.println("children are"); 
     Cursor cursor=db.fetchChildren(keys_a); 
     if (cursor.moveToFirst()) // data? 
      { 
     System.out.println(cursor.getString(9)); 
    } 
    } 
db.close(); 
    } 
    catch(Exception e) 
    { 
    System.out.println(e); 
     } 
+0

爲什麼每次迭代都會打開'db'? –

+0

即使我不打開它它給我同樣的例外 – ekjyot

回答

4

使用System.out.println(cursor.getString(0)),而不是System.out.println(cursor.getString(9));

或者使用System.out.println(cursor.getString(cursor.getColumnIndex("children"));

問題在你的邏輯:

您正在從數據庫中提取單個列。所以光標只有一列(子)。正如您所知,列索引從0開始(第一列爲0,第二列爲1),您必須在getString()中傳遞0。另一種方法是,搜索光標中的列索引並將其與getString()一起傳遞。如getColumnIndex(java.lang.String)計算光標中列名的索引,並在getString(int)內使用它。

希望這會有所幫助。

+0

謝謝@Pankaj庫馬爾 – ekjyot

+0

我已經upvoted :) – ekjyot

相關問題