我有一個通知listview.And我需要刷新列表視圖內容與很短的時間間隔。但是當我調用notifyDataSetChanged()時,直到滾動底部纔會有異常。在滾動底部之後,它拋出ArrayIndexOutOfBoundsException。這裏是我的代碼:自定義適配器notifyDataSetChanged()導致ArrayIndexOutOfBoundsException
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_notification);
init();
runOnUiThread(new Runnable() {
public void run() {
adapter.notifyDataSetChanged();
notificationsListView.postDelayed(this, 1000);
Log.i("Checking", "...");
}
});
}
Adapter.java
public class NotificationsListViewAdapter extends BaseAdapter {
RealmResults<myNotification> notifications;
Context context;
public NotificationsListViewAdapter(Context context, RealmResults<myNotification> notifications){
this.context = context;
this.notifications = notifications;
}
@Override
public int getCount() {
Log.e("NOT SIZE ADAPTER COUNT", String.valueOf(notifications.size()));
return notifications.size();
}
@Override
public myNotification getItem(int position) {
return notifications.get(position);
}
@Override
public int getViewTypeCount() {
Log.e("NOT SZE ADPTR VT COUNT", String.valueOf(notifications.size()));
return notifications.size();
}
@Override
public int getItemViewType(int position) {
return position;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, final View convertView, ViewGroup parent) {
View notificationsRowView = convertView;
// i am not posting getView() it is 400 row code and im sure error is not coming from getView()
return notificationsRowView;
}
}
順便說一下初始化函數;
void init(){
realm = Realm.getDefaultInstance();
notifications = realm.where(myNotification.class).findAllSorted("messageID",Sort.DESCENDING);
notificationsListView = (ListView) findViewById(R.id.notificationActivity_notificationsListView);
adapter = new NotificationsListViewAdapter(NotificationActivity.this,notifications);
notificationsListView.setAdapter(adapter);
}
post「init()」方法和適配器類 –
我貼了2天前你問我什麼@an_droid_dev – madProgrammer
這裏你有很多問題。首先,你從來沒有將適配器設置爲listview。其次,「runOnUiThread」是不需要的,因爲你只是在mainThread中,第三我不明白爲什麼你再次在「runOnUiThread」裏面調用「notifyDataSetChanged」而沒有從不設置適配器到列表視圖@madProgrammer –