2015-10-18 81 views
0

我的應用程序包含一個ListView在一個活動和一個BroadcastReciever。觸發後,我想讓我的Broadcastreciever刷新ListView。我的接收器將內容放入sqlite數據庫,我的listview顯示該數據庫的內容。android刷新listview from broadcastreciever

活動與ListView控件:

lv=(ListView) findViewById(R.id.conversation); 
lv.setSelection(lv.getCount()-1); 
lv.setAdapter(new mAdapter(this, srsList, messagesList, timesList, numbersList, idList)); 
registerForContextMenu(lv); 

BroadcastReciever:

SQLiteDatabase db = dbHelper.getWritableDatabase(); 
ContentValues values = new ContentValues(); 
//values.put(Messages.KEY_ID, i1); 
values.put(Messages.KEY_sr, "r"); 
values.put(Messages.KEY_message, message); 
values.put(Messages.KEY_time, datetime); 
values.put(Messages.KEY_number, sen); 
// Inserting Row 
long student_Id = db.insert(Messages.TABLE, null, values); 
db.close(); // Closing database connection 

回答

0

您可以創建活動爲您提供BroadcastReciever持有適配器,並通知該適配器應該被刷新:

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) { 

     // Extract data included in the Intent 
     // String message = intent.getStringExtra("message"); 

     if (mAdapter!= null) { 
      mAdapter.notifyDataSetChanged(); 
     } 
    } 
}; 

Reigester本廣播收錄機onResume:

this.registerReceiver(mMessageReceiver, new IntentFilter("some_unique_name")); 

而且unregiester的onPause:

this.unregisterReceiver(mMessageReceiver); 

在你BroadcastReciever只需使用:

private void updateYourActivity(Context context) { 

    Intent intent = new Intent("some_unique_name"); 

    // put whatever data you want to send, if any 
    // intent.putExtra("message", message); 

    // send broadcast 
    context.sendBroadcast(intent); 
}