0

I'm new to this, so bear with me if I make any noob mistakes. I'm trying to write a database and return a random entry from the database. The program should launch a Randomize activity that will update a text view when the randomize button is pressed. \ public void randomize(View v) { view.setText(randRecipe());}

public String randRecipe()
  {
      Random rand= new Random();
      int r= rand.nextInt(base.size());
      Recipe rec= base.get(r);
      return rec.toString();
  }

This is the code that I put in my Randomize activity and although it worked once for some reason, my program crashes every time I try to randomize again. base is the List that I retrieved that contains all the recipe entry names. I figured since I used it to populate my ListView, I could use it again to access it in the randomize.

Should I try to get the value from the database directly? If so, how would I do that and can someone provide an example?

  • 1
    I would get it from the database directly. To do so, append [ORDER BY random() limit 1](http://stackoverflow.com/questions/1253561/sqlite-order-by-rand) to the end of your SQL query. – hd1 Mar 20 '13 at 02:25

2 Answers2

1
public Cursor getRandom() {

Cursor cursor = myDataBase.rawQuery(
        "SELECT * FROM your_table_name ORDER BY RANDOM() LIMIT your_limit_here", null);
if (cursor.moveToFirst()) {
    return cursor;
}
return cursor;
}

suppose you want to get 50 data randomly than put your_limit_here = 50; where your_limit is an int.

try this: Might it will help you

Hiren Patel
  • 52,124
  • 21
  • 173
  • 151
0

Try this

db.query(tableName, null, null, null, null, null, "RANDOM()", "1");
AwadKab
  • 3,054
  • 2
  • 17
  • 17