How can I Access Database in BroadcastReceiver Class in Android?

断了今生、忘了曾经 提交于 2021-02-08 05:28:30

问题


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.


回答1:


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..................



来源:https://stackoverflow.com/questions/11719981/how-can-i-access-database-in-broadcastreceiver-class-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!