Force closing if i add a string to string array
I have the code as below
String[] myList = new String[] {"Hello","World","Foo","Bar"};
ListView lv = new ListView(this);
myList[4] = "hi";
lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,myList));
setContentView(lv);
The app is force closing,in logs im getting "java.lang.UnsupportedOperationException" if i remove myList[4] = "hi"; code I'm get开发者_开发问答ting the listview as in myList array. But my problem is i have to add string dynamically to this array and have to display.
Don't use array. Array has fixed length and you cannot add new items to it. Use list instead:
List<String> myList = new ArrayList<String>();
myList.add("Hello");
myList.add("World");
myList.add("Foor");
myList.add("Bar");
ListView lv = new ListView(this);
myList.add("hi");
You cannot simply add another element to the array. When you declare your array as
String[] myList = new String[] {"Hello","World","Foo","Bar"};
Your array is created with four elements in it. When you are trying to set myList[4]
, you're essentially trying to set a fifth element - and are obviously getting ArrayIndexOutOfBoundsException
.
If you need to dynamically add elements, you are better off using ArrayList instead of an array.
Since your array contains 4 items, myList[4]
is actually out of bounds. The maximum element index will be myList[3]
. Sure this is the issue.
you are trying to add element at 5th position. Arrays don't grow dynamically. why dont' you try like this,
String[] myList = new String[] {"Hello","World","Foo","Bar"};
ArrayList<String> mList=new ArrayList<String>();
Collections.addAll(mList,myList);
ListView lv = new ListView(this);
mList.add("Hi");
lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,mList));
setContentView(lv);
精彩评论