【问题标题】:SQLite error: CursorIndexOutOfBound ExceptionSQLite 错误:CursorIndexOutOfBound 异常
【发布时间】:2014-04-02 09:57:40
【问题描述】:

代码: 它显示 CursorIndexOutOfBoundException。 我正在运行以下代码,并尝试将值保存在数据库中并在从数据库中获取 columnindex 后将其提取并进行比较。

SQLiteDatabase db= openOrCreateDatabase("tryitdb", MODE_PRIVATE, null);
        String sql= "create table if not exists tabletry(score int)";
        db.execSQL(sql);
        db.close();
        tv1= (TextView) findViewById(R.id.textView1);
        et1= (EditText) findViewById(R.id.editText1);
        b1 = (Button) findViewById(R.id.button1);
        b1.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                getsc();
            }
        });
    };
    public void getsc() {
        SQLiteDatabase db= openOrCreateDatabase("tryitdb", MODE_PRIVATE, null);
        String sql= "select * from tabletry";
        Cursor c1= db.rawQuery(sql, null);
        if(c1!=null && c1.getCount()>0){
            int i1= c1.getColumnIndex("score");
            String score= c1.getString(i1);
            int old= Integer.valueOf(score);
            int str= Integer.valueOf(et1.getText().toString());
            if(old>=str){
                tv1.setText(old);
            }
            else{
                tv1.setText(str);
            }
        }
        else{
            init();
        }

    }
    public void init() {
        String s=et1.getText().toString();
        SQLiteDatabase db= openOrCreateDatabase("tryitdb", MODE_PRIVATE, null);
        String string= "insert into tabletry values(?)";
        Object[] oa= new Object[1];
        oa[0] = s;
        db.execSQL(string,oa);
        db.close();
        tv1.setText(s);
    }

它显示在线错误 字符串分数= c1.getString(i1); 请提出修复建议。谢谢

【问题讨论】:

    标签: android sqlite cursor indexoutofboundsexception


    【解决方案1】:

    您应该将光标移动到第一条记录,然后尝试检索值。

     if(c1!=null && c1.getCount()>0){
           ***c1.moveToFirst();***
            int i1= c1.getColumnIndex("score");
            String score= c1.getString(i1);
    

    【讨论】:

      【解决方案2】:

      在尝试从游标访问列值之前,您必须将其移动以指向有效行。为此使用moveTo...() 方法之一。

      例如,改变

      Cursor c1= db.rawQuery(sql, null);
      if(c1!=null && c1.getCount()>0){
          int i1= c1.getColumnIndex("score");
          String score= c1.getString(i1);
      

      Cursor c1= db.rawQuery(sql, null);
      if(c1.moveToFirst()){
          int i1= c1.getColumnIndex("score");
          String score= c1.getString(i1);
      

      rawQuery() 不会返回 null,因此检查它并不是真正必要的,如果光标在移动后未指向有效行,moveToFirst() 将返回 false,因此您可以删除getCount() 检查也是。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-02-24
        • 1970-01-01
        • 1970-01-01
        • 2015-02-24
        • 2019-05-02
        • 1970-01-01
        • 2010-11-01
        • 2015-10-07
        相关资源
        最近更新 更多