I made an application that generates random word from database. But there is a problem like that:
I insert some rows into the database and ID field is AUTOINCREMENT. I get a random word from database. But, when I delete a record and I insert the new one, as you know, the ID is skipping the old one.
So, when I try to get a random word, it may make an error occured. How can I solve this problem?
Thank you for your responds…
public void kelimeUret() {
SQLiteDatabase db = kelimeler.getReadableDatabase();
rastgele = new Random();
Cursor kayit = db.rawQuery("SELECT count(*) FROM kelimeler", null);
kayit.moveToFirst();
int max = Integer.parseInt(kayit.getString(0));
int min = 1;
int rastgeleKayit = rastgele.nextInt(max - min + 1) + min;
Cursor kayit2 = db.rawQuery("SELECT ingilizce FROM kelimeler WHERE id=" + rastgeleKayit, null);
kayit2.moveToFirst();
String sonuc = kayit2.getString(0);
olusturulanKelime = sonuc;
kelime = (TextView) findViewById(R.id.kelime);
kelime.setText(sonuc);
}
My code is here. Actually there is no problem. It works. But when random generates an ID that has been removed from database before, it gives error. I thought that I should generate an ordered numbers for records, but I couldn’t find the way to do that. I want to do it in another way. (Not on ID)
Your easiest bet is probably to drop the AUTOINCREMENT if you can, and instead handle giving an ID by yourself.
Just query for the highest current ID and increment it yourself.