I actually had the same task that I had to figure out. I end up using a SAX Parser, but I assume that it looks similar to the DOM parser.
Here is how I went about doing this:
I parsed the XML (using the saxparser and a custom handler) into a Map with the key being the element name, and the value an array list of the data in the xml file.
I then passed the map and the context to the adapter where you override the getCount (by passing it the size of one of the arraylists in the map) and getView methods.
As an example (and if anyone else has a better way of doing this please let me know)
Here is the handler class:
Using java Syntax Highlighting
public class XMLHandler extends DefaultHandler {
static Map<String, ArrayList<String>> parsedXML = new HashMap<String, ArrayList<String>>();
static ArrayList<String> keyList = new ArrayList<String>();
StringBuilder buffer = new StringBuilder();
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
buffer.setLength(0);
buffer.trimToSize();
if (!keyList.contains(localName)) {
keyList.add(localName);
parsedXML.put(localName, new ArrayList<String>());
}
}
public void characters(char ch[], int start, int length) {
buffer.append(ch, start, length);
}
public void endElement(String namespaceURI, String localName, String qName) {
String extractedString = buffer.toString();
parsedXML.get(localName).add(extractedString);
}
}
Parsed in 0.033 seconds, using
GeSHi 1.0.8.4
and here is the getView method of the adapter:
Using java Syntax Highlighting
public View getView(int position, View convertView, ViewGroup parent) {
View containerLayout = convertView;
if (containerLayout == null) { //Inflate the view on first use
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
containerLayout = inflater.inflate(R.layout.mainrow, null);
}
ImageView iconView = (ImageView) containerLayout.findViewById(R.id.mainIcon);
TextView labelView = (TextView) containerLayout.findViewById(R.id.mainText);
String key = (String) MainAdapter.keyArray[position];
SharedPreferences itemPrefs = mContext.getSharedPreferences(key, 0);
labelView.setText(itemPrefs.getString("title", "Sorry No Title Was Found"));
containerLayout.setTag(R.id.title, itemPrefs.getString("title", "Sorry no Title was found"));
containerLayout.setTag(R.id.url, itemPrefs.getString("url", null));
Resources res = mContext.getResources();
iconView.setImageDrawable(res.getDrawable(R.drawable.icon));
return containerLayout;
}
Parsed in 0.033 seconds, using
GeSHi 1.0.8.4
Hope this helps.