Reputation: 103
My objective is, i need to create a database using service class not in activity, for that i have created one service class which is given as follows.
public class Receiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
select();//
}
public void select()
{
SQLiteDatabase myDb;
myDb = openOrCreateDatabase(path + "/" + db, Context.MODE_PRIVATE, null);
cur4readdb = myDb.query("users",null, null, null, null, null, null);
cur4readdb.moveToFirst();
while (cur4readdb.isAfterLast() == false)
{
Log.i(TAG, " From SMSReceive : " + cur4readdb.getString(1));
cur4readdb.moveToNext();
}
cur4readdb.close();
}
}
But, i got errors in this line :
myDb = openOrCreateDatabase(path + "/" + db, Context.MODE_PRIVATE, null); //openOrCreateDatabase is underlined in red colour.
In my main activity i have used the same code its working here. But not in service.
Will you anybody please tell me. is it possible or not. If yes means elaborate that solution.
myDb = openOrCreateDatabase(path + "/" + db, Context.MODE_PRIVATE, null);
cur4readdb = myDb.query("users", null, null, null, null, null, null);
cur4readdb.moveToFirst();
while (cur4readdb.isAfterLast() == false)
{
Log.i(TAG, "User : " + cur4readdb.getString(1));
cur4readdb.moveToNext();
}
Thanks in advance.
Upvotes: 1
Views: 518
Reputation: 14271
Definitely a compilation error.
openOrCreateDatabase
can be seen in Context
class. And both Activity
and Service
extends the Context
class.
You are not writing a service, but a receiver. BroadcastReceiver doesn't extend the Context class. You can use the context object in the receiver by context.openOrCreateDatabase(...)
.
Upvotes: 1
Reputation: 1045
openOrCreateDatabase()
method is of Context class, so you need to call it from context object. i.e.
myDb = context.openOrCreateDatabase(path + "/" + db, Context.MODE_PRIVATE, null);
Upvotes: 0