Himanshu
Himanshu

Reputation: 881

How can I Access Database in BroadcastReceiver Class in Android?

I have a BroadcastReceiver class to receive incoming call. I want to compare the incoming number with a numbers from my database. Now I can't understand how to use database in BroadcastReceiver class. I make object of DBAdapter class in onReceive() method in this way:

@Override
public void onReceive(Context context, Intent intent) {

  DBAdapter db = new DBAdapter(contenxt);
  Cursor c = d.getAllData();
  while(c.moveToFirst){
      do{
            Log.v("Data : "+c.getString(2));
        }
        while(c.moveToNext);
  }
}

Above code snippet throws NullPointerException. Please somebody help me to achieve this.

Upvotes: 2

Views: 4076

Answers (1)

Himanshu
Himanshu

Reputation: 881

The greate and simplest way is below,

SQLiteDatabase db;
@Override
public void onReceive(Context context, Intent intent) {
    db = context.openOrCreateDatabase("PhoneDB2", 0, null);
    Cursor cur = db.rawQuery("SELECT * From checkedNumbers", null);

    if(cur.moveToFirst()) {
        do {

        } while(cur.moveToNext())
    }
}

This is the great solution of above problem..................

Upvotes: 5

Related Questions