Question

This is my code to check Internet and download XMl and show in a ListView

What I want is, while XML loads , show my custom layout or show a loading picture . If I should Use AsynceTask please explain how . Thanks.

       ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();

        XMLParser parser = new XMLParser();
        String xml = parser.getXmlFromUrl(URL); // getting XML
        Document doc = parser.getDomElement(xml); // getting DOM element

        NodeList nl = doc.getElementsByTagName(KEY_ITEM);
        // looping through all item nodes <item>
        for (int i = 0; i < nl.getLength(); i++) {
            // creating new HashMap

            HashMap<String, String> map = new HashMap<String, String>();
            Element e = (Element) nl.item(i);
            // adding each child node to HashMap key => value
            map.put(KEY_ID, parser.getValue(e, KEY_ID));
            map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
            map.put(KEY_COST, parser.getValue(e, KEY_COST));
            map.put(KEY_DESC, parser.getValue(e, KEY_DESC));

            // adding HashList to ArrayList
            menuItems.add(map);
        }

        // Adding menuItems to ListView
        ListAdapter adapter = new SimpleAdapter(this, menuItems,
                R.layout.list_item,
                new String[] { KEY_COST,KEY_NAME,KEY_DESC,KEY_ID},     new int

[] {
                                R.id.cost,R.id.name,R.id.desciption,R.id.linke});


        setListAdapter(adapter);
Was it helpful?

Solution

Yes, an AsyncTask would be good for this.

  1. Show whatever image/layout you want while loading in onPreExecute(). You can use a ProgressDialog/ProgressBar if you want or show something else here.
  2. Do your parsing in doInBackground()
  3. Then dismiss your ProgressDialog/ProgressBar, image, or whatever you decide to use in onPostExecute(). Also, update your Adapter in this method.
  4. You can make the AsyncTask an inner class of your Activity if you don't need it anywhere else to make it easier.

Be sure you read through the AsyncTask Docs a couple times to understand how they work.

Here is an example of setting up an AsyncTask

OTHER TIPS

@Override
    protected void onPreExecute() {
        super.onPreExecute();

 progress = ProgressDialog.show(activity, activity.getString(R.string.spinner_title), activity.getString(R.string.spinner_message_retrieving), true);}

 @Override
    protected void doInBackground() {
        super.onPreExecute();
// do here network stuff
}
 protected void onPostExecute(Void result) {      
progress.dismiss();}

this is a part of your asynktask methode

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top