![](/img/trans.png)
[英]ListFragment IllegalStateException: “The content of the adapter has changed but ListView did not receive the notification”
[英]Refresh listview adapter on GSM notification receive
說listview.java
是一個創建適配器並將其分配給listview的文件。
我想要的是當我收到GSM通知時想要刷新該列表視圖適配器。 因此,一旦我收到通知,我的列表視圖應包含新數據。
我正在使用GcmListenerService
onMessageReceived(String from, Bundle data)
這個方法。
我可以從類MyGcmListenerService擴展GcmListenerService {}調用listview.java的某些方法來刷新適配器並分配給listview嗎?
如果用戶已經在列表視圖布局上,那么我希望它使用新數據進行更新。
有任何想法的人怎么做?
更清晰
在listview.java中,我使用共享首選項中的數據創建了一個適配器。 收到GSM通知時,我會對共享首選項進行一些更改。 現在,我希望使用新的共享首選項重新創建我的適配器,並將其分配給列表視圖。
現在伙計們?
在onMessageReceived(String from, Bundle data)
您可以嘗試執行listviewAdapter.notifyDataSetChanged()
。 來自notifyDataSetChanged的文檔
通知附加的觀察者基礎數據已更改,任何反映該數據集的視圖都應刷新自身。
您可以像這樣在onRecieve的方法中使用廣播接收器
Intent intent = new Intent("custom-event-name");
// You can also include some extra data.
intent.putExtra("message", "This is my message!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
在活動中,您將必須執行這樣的更改
@Override
public void onCreate(Bundle savedInstanceState) {
...
// Register to receive messages.
// We are registering an observer (mMessageReceiver) to receive Intents
// with actions named "custom-event-name".
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("custom-event-name"));
}
// Our handler for received Intents. This will be called whenever an Intent
// with an action named "custom-event-name" is broadcasted.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
//here refresh your listview
// adater.notifyDatasetChanged();
}
};
@Override
protected void onDestroy() {
// Unregister since the activity is about to be closed.
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onDestroy();
}
並在接收方法上使用adater.notifydatasetchanged刷新適配器
接收推送通知時,使用BroadcatReceiver刷新列表視圖。
在您的ListView活動中,添加以下代碼,
ListView活動
@Override
public void onCreate(Bundle savedInstanceState) {
-------
IntentFilter filter = new IntentFilter(1001);
LocalBroadcastManager.getInstance(this).registerReceiver(
handlePushNewMessage, filter);
}
private final BroadcastReceiver handlePushNewMessage = new BroadcastReceiver() {
@Override
public void onReceive(Context context, final Intent intent) {
// Update list here and refresh listview using adapter.notifyDataSetChanged();
}
};
@Override
protected void onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(handlePushNewMessage);
super.onDestroy();
}
在MyGcmListenerService.java中,在onMessageReceived()上添加以下代碼
Intent intent1 = new Intent(1001).putExtra("MESSAGE", message);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.