我正在尝试从外部SDCard读取数据库它适用于我但是当我从光标获取值时它会抛出错误IndexOutOfBoundException
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 :(得分:1)
在for
循环
mCursor.moveToFirst();
答案 1 :(得分:1)
更改
for(int row=0;row<mCursor.getCount();row++)
到
int row = -1;
while (mCursor.moveToNext()) {
row++;
// now use cursor.getString()
光标最初位于第一行之前,没有什么可以在那里阅读
答案 2 :(得分:1)
使用此代码:
if(mCursor.moveToFirst())
{
do
{
}while(mCursor.moveToNext());
}