Adding items from XML resource file in ListView

853 views Asked by At

I have an array of titles in my strings.xml file. I want to add these titles from the XML file to a ListView in my Activity. How can I do that? Please help me with some example.

2

There are 2 answers

0
Vamsi On BEST ANSWER

You can do it as:

In your Activity class,

private String[] items;

And inside onCreate() method, initialize items array:

items = getResources().getStringArray(R.array.<your-string-array-name>);

And use this items array with your adapter.

0
dave On

What you could do is parse the XML to an ArrayList, then apply the ArrayList to a ListView adapter. It would probably work something like this:

// create an arraylist object to add all the string values from the xml
ArrayList titles = new ArrayList();
// populate your array
XMLEncoder xmlEncoder = new XMLEncoder(BufferedOutputStream(
                          new FileOutputStream("titles.xml")));
xmlEncoder.writeObject(titles);
xmlEncoder.close();
// create another arraylist that will get applied to list view
ArrayList filteredTitles = new ArrayList();

// sort through all the xml strings in the first xml arraylist
// make sure were only getting the title nodes and adding them
// to the new arraylist 'filteredTitles'
foreach(string node in titles) {
    if (node == titleNode) {
        filteredTitles.add(node)
    }
}

// apply the filtered titles to the arraylist
listView = (ListView) findViewById(R.id.your_list_view_id);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
             this, 
             android.R.layout.simple_list_item_1,
             filteredTitles );
listView.setAdapter(arrayAdapter);