2014-02-19 110 views
0

我試圖從外部SD卡工作對我來說可是當我得到的值從光標它拋出錯誤IndexOutOfBoundException讀取數據庫獲取數據從數據庫拋出IndexOutOfBound異常

mycode的是

public class Database{ 

    public static final String DATABASE_NAME = "Test/EduTab.s3db"; 

    private SQLiteDatabase database; 
    private File SDCardDir = Environment.getExternalStorageDirectory(); 

    public Database() 
    { 
     try 
     { 
      File file = new File(SDCardDir + File.separator + DATABASE_NAME); 
      if(file.exists()){ 
       database = SQLiteDatabase.openDatabase(SDCardDir + File.separator + DATABASE_NAME, null,SQLiteDatabase.OPEN_READONLY); 
      } 
     } 
     catch (SQLiteException ex) 
     { 
      ex.printStackTrace(); 
     } 
    } 

    public SQLiteDatabase getdatabase(){ 
     return database; 
    } 
} 

主要活動

public class MainActivity extends Activity { 

    SQLiteDatabase mDatabase; 
    Database mData = new Database(); 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     mDatabase = mData.getdatabase(); 

     Cursor mCursor = mDatabase.rawQuery("Select * From mst_Subject",null); 
     String[] ColumnNames = mCursor.getColumnNames(); 

     Log.d("Cursor Size",""+mCursor.getCount()); // It Works Returns Size of The Table 

     for(int row=0;row<mCursor.getCount();row++) 
     { 
      for(int col=0;col<ColumnNames.length;col++){ 

       Log.d("ColumnName",""+ColumnNames[col]); // It Works Returns The Name Of The Column 
       Log.d("Column Value",mCursor.getString(mCursor.getColumnIndex(ColumnNames[col]))); // Not Working It Throw Error   

       /* 
       * Error Is 
       * java.lang.RuntimeException: Unable to start activity 
       * ComponentInfo{com.example.readdatabasefromsdcard/com.example. 
       * readdatabasefromsdcard.MainActivity}: 
       * android.database.CursorIndexOutOfBoundsException: Index -1 
       * requested, with a size of 8 
       */ 

       Log.d("Record["+row+"]["+col+"]",mCursor.getString(mCursor.getColumnIndex(ColumnNames[col]))); 

      } 
      Log.d("End Of The Record ["+row+"]","=========================================================="); 
     } 

    } 
} 
+0

沒有嘗試調試,正是錯誤即將 – Count

回答

1

for循環之前只寫如下語句

mCursor.moveToFirst(); 
+0

喔.. Thanxs @ user3322955 –

+0

@KaranMavadhiya歡迎。你應該通過接受答案來欣賞它。 – user3322955

1

變化

for(int row=0;row<mCursor.getCount();row++) 

int row = -1; 
while (mCursor.moveToNext()) { 
    row++; 
    // now use cursor.getString() 

光標最初位於第一行之前,有什麼可以從中讀到

1

使用此代碼:

if(mCursor.moveToFirst()) 
    { 
     do 
     { 

     }while(mCursor.moveToNext()); 
    } 
相關問題