Reputation: 199
In a BroadcastReceiver
, I receive the number of an outgoing call.
I want to compare this phone number with numbers I stored in a SQL database.
Sadly I don't get access in the BroadcastReceiver
to my database. In other Activitys it works fine.
Here is the code for the BroadcastReceiver
:
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
//[ getting "string phonenumber" (works)]
mySQLiteAdapter = new SQLiteAdapter(context);
mySQLiteAdapter.openToRead();
sqLiteDatabase = sqLiteHelper.getReadableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM MYDATABASE_TABLE =" + potatos, null);
if(cursor.getCount() > 0) {
cursor.moveToFirst();
while(!cursor.isAfterLast()) {
cursor.moveToNext();
}
}
}
}
The Code in SQLiteAdapter
public SQLiteAdapter openToRead() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getReadableDatabase();
return this;
}
Upvotes: 4
Views: 1654
Reputation: 16245
Make sure you're using the Context
in the onReceive(...)
method and NOT this
.
The reason for this is that this
isn't a Context
within a BroadcastReceiver
and you need one to get access to your database. It works within an Activity
because an Activity
is a Context
Also, make sure to fix your query which is incorrect and will fail.
Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM " + MYDATABASE_TABLE + " where " + KEY_CONTENT1 + "=" + phonenumber, null);
Where KEY_CONTENT1 is the constant for field inside of MYDATABASE_TABLE for the phone number.
SQLiteAdapter mySQLiteAdapter;
@Override
public void onReceive(Context context, Intent intent) {
mySQLiteAdapter = new SQLiteAdapter(context);
mySQLiteAdapter.openToRead();
sqLiteDatabase = sqLiteHelper.getReadableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM " + MYDATABASE_TABLE + " where " + KEY_CONTENT1 + "=" + phonenumber, null);
}
Upvotes: 3