Victor Laerte
Victor Laerte

Reputation: 6556

How to add subitems in a ListView

I'm trying to add subItems in my ListView. My listView should be organized with emails for items and their institution for the subitems, but with the following code I just added items, how can I add my subitems on it? I've tried so many things but it doesn't work.

        List<Login> listEmails = JsonUtil.getAllEmails(json);

        ArrayList<String> emails = new ArrayList<String>();

        ArrayList<String> institutions = new ArrayList<String>();

        for (Login loginObj : listEmails) {

            emails.add(loginObj.getEmailAndress());
        }

        for (Login loginObj : listEmails) {

            institutions.add(loginObj.getInstitution());
        }

        ArrayAdapter<String> adapter;

        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, emails);

        emailListView.setAdapter(adapter);

Upvotes: 1

Views: 5055

Answers (2)

Victor Laerte
Victor Laerte

Reputation: 6556

The right way to do that is to create a HashMap for each item: Look the code below:

List<Login> listEmails = JsonUtil.getAllEmails(json);

                ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>(listEmails.size());

                for (Login loginObj : listEmails) {

                    HashMap<String, String> item = new HashMap<String, String>();
                    item.put("email", loginObj.getEmailAndress());
                    item.put("institution", loginObj.getInstitution());

                    list.add(item);
                }

                String[] from = new String[] { "email", "institution" };

                int[] to = new int[] { android.R.id.text1, android.R.id.text2 };

                int nativeLayout = android.R.layout.two_line_list_item;

                emailListView.setAdapter(new SimpleAdapter(this, list, nativeLayout , from, to));

Upvotes: 0

gpasci
gpasci

Reputation: 1440

You need a custom adapter with two textviews and in its getView() method set the appropriate data to each of your textviews.

Also by now you are passing to your adapter only the emails array, you'll need a different structure to include institutions too.

Upvotes: 3

Related Questions