digitalmouse12
digitalmouse12

Reputation: 155

Android - Scrolling through ListView leads to Out of Bounds Exception

I'm working on an application that primarily consists of a list view. It's backed up by my own custom array adapter whose size changes every 5 seconds. If I scroll through the list view as the array adapter changes from a greater size to a lesser size, I get an out of bounds exception. It makes sense to me why this occurs (since I'm scrolling at a position beyond the new array size), but I was wondering if there was a good way to debug it. I can't seem to come to a clear conclusion, and I was wondering if I could get some help.

I update the adapter using the following asyncTask...

public class myTask extends AsyncTask<Void, Void, Void>{

        @Override
        protected Void doInBackground(Void... params) {
            while(isRunning){
                myData.clear();
                getData();
                publishProgress();
                SystemClock.sleep(5000);
            }
            return null;
        }

        protected void onProgressUpdate(Void...progress){
            listAdapter.notifyDataSetChanged();

        }     
}

myData is the ArrayList that supports listAdapter and getData() is the function that populates myData with the relevant info that will eventually be displayed in my list view.

Is there a good way to tackle this problem?

Regards

Upvotes: 2

Views: 2145

Answers (4)

yostane
yostane

Reputation: 383

try to override the getCount() function of the adapter class:

@Override
public int getCount() {
return [list that contains data].size();
}

Upvotes: 2

Francisco Jordano
Francisco Jordano

Reputation: 885

Sorry, maybe is not the answer for the question, but having that infinite loop seems for me that is not the correct way, even if it´s an async task.

I would try to use the an AlarmManager or a Timer.

With that said, seems what you have is a race condition, take into account that it´s not immediately when you ask for data, or a specific position and rebuild the views.

Cheers, Francisco.

Upvotes: 0

Ken
Ken

Reputation: 1558

Are you using a custom adapter?

Perhaps in your getViewTypeCount() and getItemViewType(int position) it is going out of bounds there. The view type count should be from (0, n] but the item view type should be [0, n).

E.g. view type count should be 2

But the view types should be 0 and 1, not 1 and 2.

Upvotes: 2

inanutshellus
inanutshellus

Reputation: 10001

Have you tried resetting the user to either the top of the list or as close as possible when the list changed sizes?

Upvotes: 0

Related Questions