Your experience on this site will be improved by allowing cookies
To parse the XML file, the XMLPullParser is recommended in Android. It is faster than the SAX and DOM parser. To parse the XML document using the XMLPullParser, the org.xmlpull.v1.XmlPullParser interface is used.
To move the cursor pointer to the next event, the next() method of the XMLPullParser is used. The four constants defined in the XMLPullParser interface work as the event. These are:
activity_main.xml:
In the activity_main.xml file, we will drag a Listview from the palette.
List_row.xml:
XML document:(File: userdetails.xml)
Inside the assets directory of the project, an XML file will be created.
A Leader City1 B Secretary City2 C Accountant City3 D Officer 1 City4 E Officer 2 City5 |
MainActivity class:(File: MainActivity.java)
In the MainActivity.java file, we will write the code to display the list data in the ListView.
package com.example.radioapp; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); try{ ArrayList> userList = new ArrayList<>(); HashMap user = new HashMap<>(); ListView lv = (ListView) findViewById(R.id.user_list); InputStream istream = getAssets().open("userdetails.xml"); XmlPullParserFactory parserFactory = XmlPullParserFactory.newInstance(); XmlPullParser parser = parserFactory.newPullParser(); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES,false); parser.setInput(istream,null); String tag = "" , text = ""; int event = parser.getEventType(); while (event!= XmlPullParser.END_DOCUMENT){ tag = parser.getName(); switch (event){ case XmlPullParser.START_TAG: if(tag.equals("user")) user = new HashMap<>(); break; case XmlPullParser.TEXT: text=parser.getText(); break; case XmlPullParser.END_TAG: switch (tag){ case "name": user.put("name",text); break; case "designation": user.put("designation",text); break; case "location": user.put("location",text); break; case "user": if(user!=null) userList.add(user); break; } break; } event = parser.next(); } ListAdapter adapter = new SimpleAdapter(MainActivity.this, userList, R.layout.list_row,new String[]{"name","designation","location"}, new int[]{R.id.name, R.id.designation, R.id.location}); lv.setAdapter(adapter); } catch (IOException e) { e.printStackTrace(); } catch (XmlPullParserException e) { e.printStackTrace(); } } } |
0 comments