2

In android is there any direct method that executes a query and returns a cursor??

like in java there is statement.getCursor() is there any equivalent method in android?

Prachi
  • 994
  • 5
  • 23
  • 36

2 Answers2

2

you can execute query this way

 

Cursor cursor;

String select = "Select * from contactTable";

try {

  cursor = myDataBase.rawQuery(select, null);

  for (int i = 0; i < cursor.getCount(); i++) {
    cursor.moveToNext();
    // your code
  }      
  cursor.close();

} catch (Exception e) {
        e.printStackTrace();
}finally{
        myDataBase.close();
        SQLiteDatabase.releaseMemory();
}
krunal shah
  • 16,089
  • 25
  • 97
  • 143
1

I find the best way to interface with a database in android is to use a DatabaseAdapter class. This is a class loaded up with methods that do everything you could want to do with a database. Some good reading on this can be found here. Just check out listing 4.

Also, make sure to use an SQLiteOpenHelper in conjunction with your database adapter. This will create a database automatically if one doesnt exist, and handle upgrades automatically as well. Be careful though: SQLiteOpenHelper will only help you create one table per database automatically, I get around this by just creating multiple databases. As SQLite doesn't support foreign keys I don't really see a disadvantage to this. Check out the example code here for SQLiteOpenHelper.

Community
  • 1
  • 1
reader1
  • 93
  • 1
  • 8