mardi 28 juillet 2015

Android: Access SQLite Database from service

I can access a SQLite db from activity. But if I follow the same procedure in a service its unfortunately closing.

Here is what I tried

Creating db

db = openOrCreateDatabase("DB", MODE_MULTI_PROCESS, null);
db.execSQL("CREATE TABLE IF NOT EXISTS MYTABLE (ROWID INTEGER PRIMARY KEY AUTOINCREMENT, VAL VARCHAR)");

Inserting values

String sql = "INSERT INTO MYTABLE(VAL) VALUES ('" + edVal.getText().toString() + "');";
db.execSQL(sql);

To retrieve data

Cursor c;
c = db.rawQuery("SELECT VAL FROM MYTABLE", null);
c.moveToFirst();
if(c.getCount() > 0)
{
    ...
}

Since I am inserting data from my activity, I don't find any problem. But I want to retrieve data in a service. From a service on executing the line for creating cursor its got unfortunately closed. Can I create cursor in a service? Or else how can I read data from the db?

Aucun commentaire:

Enregistrer un commentaire