java.lang.IllegalStateException:无法从CursorWindow读取第0行,第2列

时间:2016-02-18 16:31:54

标签: android sqlite android-sqlite illegalstateexception

从SQLLite数据库检索数据时,我遇到异常。

  java.lang.IllegalStateException: Couldn't read row 0, col 2 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it

String username= result.getString(1);

MainActivity

mSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SQLiteDatabase myDatabase=openOrCreateDatabase("Login",MODE_PRIVATE,null);
                myDatabase.execSQL("CREATE TABLE IF NOT EXISTS Login(Username VARCHAR,Password VARCHAR);");
                myDatabase.execSQL("INSERT INTO Login VALUES('"+mUserName.getText()+"','"+mPassword.getText()+"');");

            }
        });

SecondActivity

  SQLiteDatabase myDatabase=openOrCreateDatabase("Login",MODE_PRIVATE,null);

                Cursor result=myDatabase.rawQuery("Select * from Login",null);
             result.moveToFirst();
                String username= result.getString(1);
                String password=result.getString(2);

我哪里错了?

1 个答案:

答案 0 :(得分:1)

这应该是

 String username= result.getString(0);
 String password=result.getString(1);

光标索引从零开始

完整代码

SQLiteDatabase myDatabase=openOrCreateDatabase("Login",MODE_PRIVATE,null);
Cursor result=myDatabase.rawQuery("Select * from Login",null);
if (result.moveToFirst()) {      
   String username= result.getString(0);
   String password=result.getString(1);                
}