mardi 21 juin 2016

Selecting a random row from one table and then another and putting in listView

I have two tables in my SQLite db. I am trying to choose three random rows from table1 and three random rows from table2, and have them alternating in the listView.

(ex) table1 random row table2 random row table1 random row table2 random row table1 random row table2 random row

For some reason it is not alternating the rows from each table in the listView. It puts them in whatever order it wants.

This is my code to choose the rows and insert them into the chosen table:

while (x <= 2) {
                    cursor1 = db.rawQuery("SELECT * FROM table1 ORDER BY RANDOM() LIMIT 1", null);
                    cursor1.moveToFirst();
                    rowId = cursor1.getInt(cursor1.getColumnIndex("_id"));
                    dbHandler.getWritableDatabase().execSQL("INSERT INTO chosen SELECT * FROM table1 WHERE _id = '" + rowId + "'");
                    dbHandler.getWritableDatabase().execSQL("UPDATE chosen SET _id = '" + newID + "' WHERE _id = '" + rowId + "'");
                    newID++;

                    cursor2 = db.rawQuery("SELECT * FROM table2 ORDER BY RANDOM() LIMIT 1", null);
                    cursor2.moveToFirst();
                    rowId = cursor2.getInt(cursor2.getColumnIndex("_id"));
                    dbHandler.getWritableDatabase().execSQL("INSERT INTO chosen SELECT * FROM table2 WHERE _id = '" + rowId + "'");
                    dbHandler.getWritableDatabase().execSQL("UPDATE chosen SET _id = '" + newID + "' WHERE _id = '" + rowId + "'");
                    newID++;

                    x++;
                }
                cursor1.close();
                cursor2.close();

This is what I am using to choose the data to populate the listView

Cursor cursor = db.rawQuery("SELECT _id, value FROM chosen ORDER BY _id", null);

Any help would be greatly appreciated!




Aucun commentaire:

Enregistrer un commentaire