Vamsi Challa February 2016

ListView with Custom Adapter - IndexOutOfBoundsException when list is empty

I have a List in which i store some strings that i get from server. I have a custom adapter for the ListView. Each item has a TextView and a Switch.

In the onCreate method, the list will be empty and after the data is received from server, i am calling notifyDataSetChanged on the adapter.

My query is specific to Switch(or a Checkbox in similar case). Please look at the code below. I will do my best to explain it using quotes.

public class DetailDOMActivity extends AppCompatActivity {

   ListView listview;
   DealofTheMonthAdapter mDealofTheMonthAdapter;
   List<String> mTitles = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_detail_dom);
      ....
      ....

      // Clearing the List before getting values from server
      mTitles.clear();

      listview = (ListView) findViewById(R.id.listView);

      // If i remove the below 2 lines, 
      // and add them after getting the data from server,
      // everything works fine.

      // My query here is, when the list is empty,
      // and when getCount() in adapter returns 0,
      // why is getView() being called? 
      // Is this the normal behaviour?
      mDealofTheMonthAdapter = new DealofTheMonthAdapter(this);
      listview.setAdapter(mDealofTheMonthAdapter);

      // Gets Values from server and
      // stores them in mTitles List.  
      // At the end notifyDataSetChanged() 
      // is called on the adapter 
      getDataFromServer();
    }   

   private class DealofTheMonthAdapter extends BaseAdapter {

    final Context context;

    List<Boolean> mProgress = new ArrayList<Boolean>();

    public DealofTheMonthAdapter(Context context) {
        this.context = context;
        mProgress.clear();
    }


    @Override
    public int getCount() {
        return mTitles.size();
    }


         

Answers


Blackbelt February 2016

the IndexOutOfBoundsException is caused by mProgress which is empty while mTitles is not. Dealing with multiple collections on ListView can be tricky, since you have always to make sure that all the collections have at least getCount()'s size. That's of course possible, but is error prone. What you can do is to wrap all the information around a Model class. E.g.

 public class MyModel {
    public String name;
    public boolean isChecked
 }

and change from List<String> mTitles to List<MyModel> mTitles. This way you can deal with only one collection, and easily retrieve and change the property of the the item at position

Post Status

Asked in February 2016
Viewed 3,339 times
Voted 9
Answered 1 times

Search




Leave an answer