Shemil Shemil - 1 month ago 9
Android Question

ArrayIndexOutOfBound Exception in ArrayList Android Listview

i am doing a project to display contact details from a csv file. But, my arraylist is not accepting more than 25 values. it shows arrayindexoutofbound exception with lenth 3 and index 3. Here is my code..

ArrayList<Contact> arraylist = new ArrayList<>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setIcon(R.mipmap.ic_app);
getSupportActionBar().setTitle("Directory");
// getting data from csv file
arraylist.ensureCapacity(1000);
try {
InputStreamReader input_stream = new InputStreamReader(getAssets().open("test.csv"));
BufferedReader reader = new BufferedReader(input_stream);
String csv_item;
while ((csv_item = reader.readLine()) != null) {
String[] row = csv_item.split(",");
String col1 = row[0];
String col2 = row[1];
String col3 = row[2];
String col4 = row[3];
Contact wp = new Contact(col1, col2,
col3, col4);
// Binds all strings into an array
arraylist.add(wp);
// namelist.add(col1);
// numberlist.add(col2);
// addresslist.add(col3);
// emaillist.add(col4);
}

}catch(ArrayIndexOutOfBoundsException ez){
System.out.print(ez.getMessage());
}
catch(Exception ex) {
ex.printStackTrace();
}



// Locate the ListView in listview_main.xml
list = (ListView) findViewById(R.id.listview);

Answer

ArrayIndexOutOfBoundsException

Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

Problem Arising from

        String col1 = row[0];
        String col2 = row[1];
        String col3 = row[2]; // Here is problem . Comment this line .Open your CSV and Check.
        String col4 = row[3]; 

Make sure, Your last two fields value exist or not .