java - 如何解决 SQLite 索引越界错误?

标签 java android sqlite

我正在尝试从 SQLite 数据库获取数据,当我尝试时,我的应用程序崩溃,错误为:“android.database.CursorIndexOutOfBoundsException:请求索引 -1,大小为 1”。 我做错了什么?

这是我的 Activity :

public class EventInfo extends AppCompatActivity {
DatabaseHelper myDb;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_event_info);
    myDb=new DatabaseHelper(this);
    SharedPreferences sp = getSharedPreferences("key", 0);
    final String event_title=sp.getString("event_title", "");
    final String event_date=sp.getString("event_date", "");
    String event_content=sp.getString("event_content","");
    String age_limit=sp.getString("age_limit","");
    String event_hour=sp.getString("event_hour","");
    String location_left=sp.getString("location_left","");
    String location_right=sp.getString("location_right","");

    TextView txt5=(TextView)findViewById(R.id.textView5);
    TextView txt6=(TextView)findViewById(R.id.textView6);
    TextView txt7=(TextView)findViewById(R.id.textView7);
    TextView txt8=(TextView)findViewById(R.id.textView8);
    TextView txt9=(TextView)findViewById(R.id.textView9);
    TextView txt10=(TextView)findViewById(R.id.textView10);
    TextView txt14=(TextView)findViewById(R.id.textView14);

    txt5.setText(event_title);
    txt6.setText(event_date);
    txt7.setText(age_limit);
    txt8.setText(event_content);
    txt9.setText(event_hour);
    txt10.setText("Press here for event location");
    String votes_count=myDb.getVotesCount(event_title);
    if(votes_count.equals("1")) {
        txt14.setText("Cancel Attending");
    }
    else {
        if(votes_count.equals("0")||votes_count.isEmpty()) {
            txt14.setText("Accept Attending");
        }
        else
        {
            txt14.setText("Error");
        }
    }
    txt10.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(EventInfo.this, MapsActivity3.class);
            startActivity(intent);

        }
    });



    txt14.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String votes_count=myDb.getVotesCount(event_title);
            if(votes_count.equals("0")||votes_count.isEmpty()) {
                boolean insert = myDb.insertData("1", event_title, event_date);
                if (insert == true)
                    Toast.makeText(EventInfo.this, "You have accepted the arrival", Toast.LENGTH_LONG).show();
                else
                    Toast.makeText(EventInfo.this, "Error", Toast.LENGTH_LONG).show();
            }
            else
            {
                if(votes_count.equals("1"))
                {
                    boolean insert = myDb.insertData("0", event_title, event_date);
                    if (insert == true)
                        Toast.makeText(EventInfo.this, "You have canceled the arrival", Toast.LENGTH_LONG).show();
                    else
                        Toast.makeText(EventInfo.this, "Error, Toast.LENGTH_LONG).show();
                }
                else
                {
                    Toast.makeText(EventInfo.this, votes_count.toString(), Toast.LENGTH_LONG).show();
                }
            }
        }
    });
}

}

这是我的 DatabaseHelper 类:

public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME="usersDB.db";
public static final String TABLE_NAME="votes_table";
public static final String COL2="VOTESCOUNT";
public static final String COL3="EVENTTITLE";
public static final String COL4="EVENTDATE";


public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
    SQLiteDatabase db = this.getWritableDatabase();
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table " + TABLE_NAME + " (VOTESCOUNT TEXT, EVENTTITLE TEXT, EVENTDATE TEXT)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
    onCreate(db);
}

public boolean insertData(String votes_count, String event_title, String event_date){
    SQLiteDatabase db =this.getWritableDatabase();
    ContentValues contentValues=new ContentValues();
    contentValues.put(COL2,votes_count);
    contentValues.put(COL3,event_title);
    contentValues.put(COL4, event_date);
    long result=db.insert(TABLE_NAME,null,contentValues);
    if(result==-1)
    {
        return false;
    }
    else
        return true;
}

public Cursor getAllData()
{
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
    return res;
}

public Cursor getEventTitles()
{
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res=db.rawQuery("select EVENTTITLE from "+TABLE_NAME,null);
    return res;
}

public Cursor getEventDate(String eventtitle)
{
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res=db.rawQuery("select EVENTDATE from "+TABLE_NAME+" where EVENTTITLE='"+eventtitle+"'",null);
    return res;
}

public String getVotesCount(String eventtitle)
{
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res=db.rawQuery("select VOTESCOUNT from "+TABLE_NAME+" where EVENTTITLE='"+eventtitle+"'",null);
    String votes_count=res.getString(0);
    return votes_count;
}

}

最佳答案

在访问数据之前,您必须将游标移动到第一行,最好检查 moveToFirst() 的返回值,以确保游标已数据。另外,使用完后请务必关闭所有游标:

public String getVotesCount(String eventtitle)
{
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res=db.rawQuery("select VOTESCOUNT from "+TABLE_NAME+" where EVENTTITLE='"+eventtitle+"'",null);

    String votes_count = null;
    if (res.moveToFirst()) {
         votes_count =res.getString(0);
    }
    res.close();
    return votes_count;
}

并为返回值添加空检查:

String votes_count = myDb.getVotesCount(event_title);
if(votes_count != null && (votes_count.equals("0")||votes_count.isEmpty())) {
//...............

关于java - 如何解决 SQLite 索引越界错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36140315/

相关文章:

java - 如何从 vector 中获取特定索引的值?

java - 在单个上下文切换中将相同的 tcp 消息发送到多个目的地/主机

java - Sqlite 和 Window 已经聚焦

java - postgresql 通知 channel

java - 带有复杂编辑器的 JTable

java - 物理体的碰撞检测

java - 制作自定义通知的 textView 以记住每个触发的通知的特定字符串

Android:当我将 apk 升级到测试阶段时,Alpha 用户会发生什么

android - 如何在 SQLite 中以古吉拉特语存储数据?

ruby-on-rails - 使用 seed_dump gem 为我的数据库播种时出错