-1

I'm using a DBHelper class with the following method

    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;
    }

My database is populated (100% sure of this, other methods work)

db.execSQL("CREATE TABLE Reservations(username VARCHAR, parkingname VARCHAR, date VARCHAR, timeslot VARCHAR);");

Now whenever I try

        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);
        }

The application crashes with

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myparking/com.example.myparking.MyReservations}: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
Zoe
  • 27,060
  • 21
  • 118
  • 148

1 Answers1

0

You need to create row inside cursor cycle. When you call reservations.add(row), your row object is not copied into reservations, and when you call row.clear() - list cleared in both row and reservations.

    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;
    }
Mikhail
  • 309
  • 1
  • 6