1

I have been trying to use ArrayList.add, when I was putting just .add("some data") it worked fine, when I tried assigning the id - .add(1, "some data"); I keep getting the error when I try running the app - "The application MobileApp(process com.example.mobileapp) has stopped unexpectedly. Please try again.".

This is the next code that I am running:

    List<String> log = new ArrayList<String>();
    log.add(1, "some data");

This works fine:

    List<String> log = new ArrayList<String>();
    log.add("some data");

What I want to achieve from this:

  1. ListView will have list of items, each item would have specific "id".
  2. On click this "id" will be picked up and user is moved to different layout where further information is shown on item with selected "id".
Trinimon
  • 13,839
  • 9
  • 44
  • 60

2 Answers2

5

You are trying to add an item at index 1 which doesn't exist. You will need to change the code to insert into the 0 position first.

List<String> log = new ArrayList<String>();
log.add(0, "some data");

If you need specific IDs that do not correspond to the index, you might want to look into using a Map.

  • Yes, it seems that Map would be an option for me to take, because I might not have item with "id" of 0 in the list. How would I go about supplying it to ArrayAdapter? – user1652382 Apr 04 '13 at 21:36
  • Here is an answer that entails extending BaseAdapter for use with a HashMap http://stackoverflow.com/questions/5234576/what-adapter-shall-i-use-to-use-hashmap-in-a-listview –  Apr 04 '13 at 21:45
  • 1
    I also found this guide - http://www.vogella.com/articles/AndroidListView/article.html – user1652382 Apr 04 '13 at 21:47
3

Try this

List<String> log = new ArrayList<String>();
log.add(0, "some data");//Changed from 1 to 0

I think you need to start from 0. You cannot insert 1 if we dont have data in 0th position.

Joseph Selvaraj
  • 2,225
  • 1
  • 21
  • 21