4

I have a ListView and cannot display the sub items on the list... It only displays one or the other but not both. If I remove the number from below it will display the string (titles):

I want to display both Items and sub items.

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    this.loadData();

    String []titles_str = titles.toArray(new String[titles.toArray().length]);
    this.setListAdapter(new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_2, android.R.id.text1, titles_str));

    Number []subtitles_str = lengths.toArray(new Number[lengths.toArray().length]);
    this.setListAdapter(new ArrayAdapter<Number>(this,
            android.R.layout.simple_list_item_2, android.R.id.text2, subtitles_str));
}
brodster
  • 77
  • 1
  • 2
  • 12

1 Answers1

5

you are using "this.setListAdapter" two times, only Second "this.setListAdapter" will reflect.

For your requirement, Please use

1)custom arrayadapter<customObject> 
      or 
2)simpleadapter.

1) Using custom arrayadapter, Please check http://devtut.wordpress.com/2011/06/09/custom-arrayadapter-for-a-listview-android/

2) Using SimpleAdapter:

List<Map<String, String>> data = new ArrayList<Map<String, String>>();
for (int i=0; i<titles_str.length; i++) {
    Map<String, String> datum = new HashMap<String, String>(2);
    datum.put("title", titles_str[i]);
    datum.put("subtitle", String.valueof(subtitles_str[i]));
    data.add(datum);
}
SimpleAdapter adapter = new SimpleAdapter(this, data,
                                      android.R.layout.simple_list_item_2,
                                      new String[] {"title", "subtitle"},
                                      new int[] {android.R.id.text1,
                                                 android.R.id.text2});
this.setListAdapter(adapter);
Vidyadhar
  • 1,088
  • 9
  • 15
  • Hey, notice that the `SimpleAdapter` is designed for static data. If the data is needed to be update. You probably need to re-create a new `SimpleAdapter` for new updated content. – Yeung Aug 07 '13 at 07:56
  • @Yeung - yes, need to re-create a new SimpleAdapter for new updated content. Or go for any other Adapter like ArrayAdapter – Vidyadhar Aug 07 '13 at 11:30
  • How to get this sub item "title" value ? as an example,when click one item on list view we want to get sub item title. – Elshan Dec 26 '13 at 05:46