elL
elL

Reputation: 777

Parse XML in Android for ListView

I'm currently working on parsing xml for android listview. I was able to parse and get a data for my listview. But, what if I want to get a specific data from that XML. hmmm like performing something in SQL "select * from [table] where id = 1". Something like that...How can I do that with my XML? Thanks

Upvotes: 0

Views: 284

Answers (2)

best11
best11

Reputation: 19

public class XMLParsing_DisplayListviewActivity extends Activity {
    String res1         = null;
    InputStream is      = null;
    StringBuilder sb    = null;

    public String[] mCD;
    public String[] mTitle;
    public String[] mArtist;
    public String[] mCountry;
    public String[] mCompany;
    public String[] mPrice;
    public String[] mYear;

    ListView listview;

    ProgressDialog mDialog = null; // thread code
    private Runnable viewOrders; // thread code
    private Thread thread1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        listview=(ListView)findViewById(R.id.listview);

        mDialog = new ProgressDialog(this); // thread code
        mDialog.setMessage("Please wait...");

        viewOrders = new Runnable(){
        public void run(){
            load();
            runOnUiThread(returnRes);
        }
    };
    thread1 = new Thread(null, viewOrders, "Background"); // thread
    thread1.start(); // thread code
    mDialog.show();

}

private Runnable returnRes = new Runnable(){
    public void run(){
        mDialog.cancel();
         for(int i=0;i<mCD.length;i++){
                System.out.println("======================");
                System.out.println("Title :- "+mTitle[i]);
                System.out.println("Artist :- "+mArtist[i]);
                System.out.println("Country :- "+mCountry[i]);
                System.out.println("Company :- "+mCompany[i]);
                System.out.println("Price :- "+mPrice[i]);
                System.out.println("Year :- "+mYear[i]);
            }


         listview.setAdapter(new CustomAdapter(XMLParsing_DisplayListviewActivity.this));       

    }
};

public void load() {
    //mLoading = true;
    Document doc = null;
    HttpURLConnection urlConnection = null;
    URL url = null;
    try {
        //url = new URL(urlString.toString());
        url = new URL("http://www.xmlfiles.com/examples/cd_catalog.xml");
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.connect();
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        doc = db.parse(urlConnection.getInputStream());
    } catch (Exception e) {
        System.out.println("e"+e.toString());
    }
    try {
        NodeList nodes = doc.getElementsByTagName("CD");
        // iterate the employees

        mCD=new String[nodes.getLength()];
        mTitle=new String[nodes.getLength()];
        mArtist=new String[nodes.getLength()];
        mCountry=new String[nodes.getLength()];
        mCompany=new String[nodes.getLength()];
        mPrice=new String[nodes.getLength()];
        mYear=new String[nodes.getLength()];

        for (int i = 0; i < nodes.getLength(); i++) {
           Element element = (Element) nodes.item(i);

           NodeList cd = element.getElementsByTagName("CD");
           Element line = (Element) cd.item(0);
           mCD[i]=getCharacterDataFromElement(line);               

           NodeList title = element.getElementsByTagName("TITLE");
           line = (Element) title.item(0);
           mTitle[i]=getCharacterDataFromElement(line);
           //System.out.println("catcatcatmidmidmidmidName: " + getCharacterDataFromElement(line));

           NodeList artist = element.getElementsByTagName("ARTIST");
           line = (Element) artist.item(0);
           mArtist[i]=getCharacterDataFromElement(line);
           //System.out.println("salary: " + getCharacterDataFromElement(line));

           NodeList country = element.getElementsByTagName("COUNTRY");
           line = (Element) country.item(0);
           mCountry[i]=getCharacterDataFromElement(line);

           NodeList company = element.getElementsByTagName("COMPANY");
           line = (Element) company.item(0);
           mCompany[i]=getCharacterDataFromElement(line);

           NodeList price = element.getElementsByTagName("PRICE");
           line = (Element) price.item(0);
           mPrice[i]=getCharacterDataFromElement(line);

           NodeList year = element.getElementsByTagName("YEAR");
           line = (Element) year.item(0);
           mYear[i]=getCharacterDataFromElement(line);

        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

  public static String getCharacterDataFromElement(Element e) {
    Node child = e.getFirstChild();
    if (child instanceof CharacterData) {
       CharacterData cd = (CharacterData) child;
       return cd.getData();
    }
    return "?";
  }


  public class CustomAdapter extends BaseAdapter {
    private Context mContext;
    Application app;
    private LayoutInflater inflater=null;

    public CustomAdapter(Context c) {
        mContext = c;
         inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }   

    public int getCount() {
        return mTitle.length;

    }

    public Object getItem(int position) {
        return null;
    }

    public long getItemId(int position) {
        return 0;
    }

    // create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) {

        View vi=convertView;
        if (convertView == null)        
             vi = inflater.inflate(R.layout.list, null);


        TextView txt=(TextView)vi.findViewById(R.id.txtview_title);
        TextView txt1=(TextView)vi.findViewById(R.id.txtview_artist);
        TextView txt2=(TextView)vi.findViewById(R.id.txtview_country);
        TextView txt3=(TextView)vi.findViewById(R.id.txtview_company);
        TextView txt4=(TextView)vi.findViewById(R.id.txtview_price);
        TextView txt5=(TextView)vi.findViewById(R.id.txtview_year);

        txt.setText("Title : " + mTitle[position]);
        txt1.setText("Artist : " + mArtist[position]);
        txt2.setText("Country : " + mCountry[position]);
        txt3.setText("Company : " + mCompany[position]);
        txt4.setText("Price : " + mPrice[position]);
        txt5.setText("Year : " + mYear[position]);

        return vi;
    };
  }
}

Upvotes: 1

ebarrenechea
ebarrenechea

Reputation: 3785

You should parse the xml file just once and create an array or list of objects from it. Once you have everything on memory you can use the array to populate your list with an ArrayAdapter. The position in the array can be used as your id. If you rather have an attribute of the object be the id instead of the position then you can just sort the array accordingly.

Upvotes: 0

Related Questions