Maya
Maya

Reputation: 545

ListView using String Array

How can I give values to ListView? When I am trying to create a ListView using String array, my process is suddently stopped.

     public String[] items_list=new String[100];
     items_list[0]="11";
     items_list[1]="22";
     items_list[2]="33";
     items_list[3]="44";
     ListView listitems=(ListView)findViewById(R.id.list);
     adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,items_list);
     listitems.setAdapter(adapter);

But if i am initializing the string array with ite declaration, it is working. Why this is happend?

     public String[] items_list={"chocolate","lime juice","icecreame"};

Please help me... Thnk you..

Upvotes: 2

Views: 6226

Answers (2)

Blrfl
Blrfl

Reputation: 7003

Tseng's answer is right on about the probable cause. The ListView is going to see the array's size as 100 and will try and used the nulls in the remaining elements.

Use any subclass of List<String> (e.g., ArrayList<String> or Vector<String>) to hold your data and the adapter will function properly.

Upvotes: 0

Tseng
Tseng

Reputation: 64121

Well, you're making an array with 100 objects in

 public String[] items_list=new String[100];
 items_list[0]="11";
 ...
 items_list[3]="44";

But you only fill the first 4 elements, this means that the remaining 96 Strings are null. This may cause your errors when the ListView tries to fill out the list, as it assumes there are 100 elements in the list. Try only to allocate as much memory as necessary at new String[100];

Upvotes: 3

Related Questions