Welcome to the CSC Q&A, where you can get help (and share your knowledge) about computer science!

How can I add items to a List View from Java code?

+13 votes

I already have some code written for this.  As an example:

private void generateList() {
        candidateMappedList.add(createCandidate("test", "Erik"));
        candidateMappedList.add(createCandidate("test", "Chris"));
        candidateMappedList.add(createCandidate("test", "Alex"));
    }
    // beginTest
    generateList();
    ListView lv = (ListView) findViewById(R.id.candidatesListView);
    // this is the adapter that will help show the list
    SimpleAdapter ourSimpleAdapter = new SimpleAdapter(this, candidateMappedList,
            android.R.layout.simple_list_item_1, new String[]{"category"},
            new int[]{android.R.id.text1});
    lv.setAdapter(ourSimpleAdapter);
    // endTest



//Other code involved:
    // Generates the List
private void generateList() {
        candidateMappedList.add(createCandidate("test", "Erik"));
        candidateMappedList.add(createCandidate("test", "Chris"));
        candidateMappedList.add(createCandidate("test", "Alex"));
    }
    // Puts the items in the map
private HashMap<String, String> createCandidate(String key, String name) {
        HashMap<String, String> tempCandidate = new HashMap<String, String>();
        tempCandidate.put(key, name);
        return tempCandidate;
    }

But i'm not getting it to Display properly... it will have the 3 spaces allocated for the 3 names but it wont actually display the names in the list...

IDs: (List View) candidatesListView && (Checked Text View) checkedTextView

asked May 13, 2015 in Spring 2015 by Erik Aksland (100 points)

1 Answer

+2 votes

It looks like you are just trying to add the names to the ListView, this can be accomplished with an ArrayAdapter  is there a reason that you are using the SimpleAdapter? For our ListView I wrote a custom adapter, that may also be a possibility for you if you want better control of how data is displayed and how it is styled.

If I were you I would create a Class for Candidate, the Candidate object could hold all of the data for the Candidate. Then create an ArrayList<Candidate> to hold all of the Candidates that you want to go in the list. When you use an ArrayAdapter on the for the arraylist you will need a toString, this is called when the ArrayAdapter is populating your listView. When you set an OnItemClickListener for the ListView, it will have a position parameter, this is the position of the item you clicked, which should correspond to the index of the object in the ArrayList<Candidate> so you can easily do something with the Candidate when it is clicked.

I would be happy to explain it in more depth, if you feel that this will work for your project.

answered May 13, 2015 by Ethan Wojcinski (100 points)
edited May 14, 2015 by Ethan Wojcinski
...