光标索引超出范围

时间:2013-06-10 08:40:01

标签: android sqlite cursor

我试图在数据库中搜索id是否存在,当它存在时我打开下一个活动,但是当它不存在时应用程序崩溃..我找到了bug,错误光标索引超出范围

                 Database dbc = new Database(this);
                dbc.open();
                String id = searchId.getText().toString();
                boolean checkId = dbc.isGotId(id);

                if(checkId == true){
                    String s = searchId.getText().toString();
                    Bundle b = new Bundle();
                    b.putString("key",s);
                    b.putInt("keyX", radioBtnFlag);
                    Intent a = new Intent(SearchUpdate.this, UpdateDelete.class);
                    a.putExtras(b);
                    startActivity(a);

                    searchId.setText(null);

                }else if(checkId == false){

                    Log.v(id, id + "2222222");

                    Dialog d = new Dialog(this);
                    d.setTitle("Error!");
                    TextView tv = new TextView(this);
                    tv.setText("This Search is allow only ID! "+ radioBtnFlag);
                    d.setContentView(tv);
                    d.show();

                    searchId.setText(null);

在这里......

  public boolean isGotId(String id){

    boolean result = false;
    try{

    Cursor sId = ourDatabase.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE " + Pro_ID + "=" + id, null);

    result = true;
    }catch(SQLiteException e)
    {
        result = false;
    }//catch

    return result;

}//isGOtId

2 个答案:

答案 0 :(得分:4)

试试这个......

public boolean isGotId(String id){

        Cursor sId = ourDatabase.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE " + 
                                  Pro_ID + "=" + id, null);
        int numberOfRows = sId.getCount();
        if(numberOfRows <= 0)
        {
            return false;
        }

    return true;
}

答案 1 :(得分:3)

try{

    Cursor sId = ourDatabase.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE " + Pro_ID + "=" + id, null);

  if(sId.moveToFirst() && sId ! = null)
             result = true;
    }catch(SQLiteException e)
    {
        result = false;
    }