IndexOutOfBoundException when I use notifyDataSetChanged

吃可爱长大的小学妹 提交于 2019-12-23 18:40:24

问题


I Founded my problem in this post Updating ExpandableListView with notifyDataSetChanged()

"each time you refresh the the views using setNotifyDatasetChanged the Adapter will call the loop around the List. and you List in the Adapter gets a null value due to the changes you made."

I am beginner and can not properly make changes to the list

my sources

public class UrlArrayAdapter extends ArrayAdapter<UrlItem> {

    private LayoutInflater inflater;
    private ListView urlListView1;
    private ArrayList<UrlItem> urlItems1;

    public UrlArrayAdapter(Context context, ListView urlListView,
            ArrayList<UrlItem> urlLists) {
        super(context, urlListView.getId(), urlLists);
        this.urlItems1 = urlLists;
        this.urlListView1 = urlListView;


        inflater = LayoutInflater.from(context);

how do I remove an item from the list in urlLists in the base adapter??


回答1:


In addition to overriding public View getView(int position, View view, ViewGroup parent), make sure your class that extends ArrayAdapter overrides these methods:

public int getCount()
public UrlItem getItem(int position)
public int getPosition(Hold item)
public long getItemId(int position)

I believe notifyDataSetChanged() will call getCount() on your adapter to determine how many items there are. If you don't override this method with return urlItems1.size(); then an IndexOutOfBoundException seems imminent because there will be no way for your custom adapter to tell clients about its size and contents.




回答2:


To remove an item: urlList.remove(item_index); Then notify that the data set has been changed.

Based on your comment below, I'm updating my answer.
The remove() method accepts the index of the element being removed, not the element itself.

So, to remove a specific number from the list you should first find its index, and then pass that index to the remove() method.

Ex:

public void deleteItem(int numberToDelete) {
    int index=-1;

    // Find the index of numberToDelete
    if(urlLists.contains(numberToDelete)){
        index = urlLists.indexOf(numberToDelete);
    }

    // Delete the number by spefying the index found.
    if(index!=-1){
        urlLists.remove(index);
    }

//...
}


来源:https://stackoverflow.com/questions/11990399/indexoutofboundexception-when-i-use-notifydatasetchanged

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!