android应用程序不断崩溃,我不知道为什么具有java.lang.indexoutofboundsexception的内容:索引:0,大小:0

t1qtbnec  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(355)

这个问题在这里已经有了答案

什么是indexoutofboundsexception?我该怎么修[重复](1个答案)
18天前关门了。
我使用dbhelper类和以下方法

public List<List<String>> getReservations (String username) {
        List<List<String>> reservations = new ArrayList<List<String>>();
        List<String> row = new ArrayList();
        SQLiteDatabase database = this.getReadableDatabase();
        Cursor c1 = database.rawQuery("SELECT * FROM Reservations WHERE username LIKE '" + username + "'", null);
        while(c1.moveToNext()) {
            row.add(c1.getString(1)); //parkingname
            row.add(c1.getString(2)); //date
            row.add(c1.getString(3)); //time
            reservations.add(row);
            row.clear();
        }
        c1.close();
        return reservations;
    }

我的数据库已填充(100%确定,其他方法有效) db.execSQL("CREATE TABLE Reservations(username VARCHAR, parkingname VARCHAR, date VARCHAR, timeslot VARCHAR);"); 现在每当我尝试

List<List<String>> values = database.getReservations(username);
        text = (TextView) findViewById(R.id.myreservations);
        if(!values.isEmpty()) {
            String b = String.valueOf(values.size());
            List<String> lista = values.get(0); //crashes here
            String a = lista.get(0);
            text.setText(b + a);
        }

应用程序崩溃

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myparking/com.example.myparking.MyReservations}: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
wvt8vs2t

wvt8vs2t1#

您需要在游标循环内创建行。当您调用reservations.add(row)时,您的row对象不会复制到reservations中,当您调用row.clear()时,在row和reservations中列出cleared。

public List<List<String>> getReservations (String username) {
        List<List<String>> reservations = new ArrayList<List<String>>();
        SQLiteDatabase database = this.getReadableDatabase();
        Cursor c1 = database.rawQuery("SELECT * FROM Reservations WHERE username LIKE '" + username + "'", null);
        while(c1.moveToNext()) {
            List<String> row = new ArrayList();
            row.add(c1.getString(1)); //parkingname
            row.add(c1.getString(2)); //date
            row.add(c1.getString(3)); //time
            reservations.add(row);
        }
        c1.close();
        return reservations;
    }

相关问题