Getting a random databse row

Sunday, July 6, 2014

Im trying to get a random row from my database. The random row should be defined by the correct "category". Meaning it should only be able to random between the rows with the defined category.


Here is a what i thought would work:





public void onClick_Mandatory(View v) {
Cursor cursor;
Random r = new Random();
cursor = myDb.getBetting();
for(int i = 0; cursor.getCount() > i; i++){
if(i == 0){
cursor.moveToFirst();
array[i] = cursor.getInt(DBAdapter.COL_ROWID);
}
else{
cursor.moveToNext();
array[i] = cursor.getInt(DBAdapter.COL_ROWID);
}
}
int randomId = array[r.nextInt(array.length)];
cursor = myDb.getRow(randomId);
if (cursor.moveToFirst()) {
title = cursor.getString(DBAdapter.COL_TITLE);
text = cursor.getString(DBAdapter.COL_TEXT);
creator = cursor.getString(DBAdapter.COL_CREATOR);
category = cursor.getString(DBAdapter.COL_CATEGORY);

}
cursor.close();

titleText.setText(title);
textText.setText(text + "\n" + creator + "\n" + category);

}




...and here is the getBetting method from the database class.



public Cursor getBetting() {
String where = KEY_CATEGORY + "=" + "Betting";
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}




Hope you are able to help me.







http://ift.tt/1vMOGV0