2017-07-14 142 views
-1

我有一個通知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); 
} 
+0

post「init()」方法和適配器類 –

+0

我貼了2天前你問我什麼@an_droid_dev – madProgrammer

+0

這裏你有很多問題。首先,你從來沒有將適配器設置爲listview。其次,「runOnUiThread」是不需要的,因爲你只是在mainThread中,第三我不明白爲什麼你再次在「runOnUiThread」裏面調用「notifyDataSetChanged」而沒有從不設置適配器到列表視圖@madProgrammer –

回答

0

看來,您的代碼錯誤地計算了內部適配器中的getCount()。 發佈您的元素的存儲和適配器代碼,以確保。

+0

實際上'getCount'返回確切的數組大小。我的意思是它正在增加和減少的操作,我已經測試與日誌。但是我剛剛注意到,如果我將getViewTypeCount()的返回值增加1,它允許我添加1個項目,如果我添加第二個項目它會崩潰。所以我認爲問題在於'getViewTypeCount'方法。它會返回'getCount()'...但不會動態變化... – madProgrammer

+0

@madProgrammer分享我的代碼 – Vyacheslav

+0

我分享了我的代碼2天前@Vyacheslav – madProgrammer