Denis
Denis

Reputation: 3707

How to get xml by url (AsyncTask, android)?

I have the the following classes:

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        XmlManager xm = new XmlManager();
        Log.i("tag",documentToString(xm.getXmlFromUrl("http://domen.com/abc/timelist.xml")));
    }
    //................
}

public class XmlManager {
    public Document getXmlFromUrl(String url) {
        GetXmlTask txt = new GetXmlTask();
        txt.execute(url);
        Document doc = null;
        try {
            doc = txt.get(5, TimeUnit.SECONDS);
            Log.i("tag", "test");
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return doc;
    }
    //................
}

public class GetXmlTask extends AsyncTask<String, Void, org.w3c.dom.Document> {
    @Override
    protected Document doInBackground(String... arg0) {
          String url = "";
              if( arg0.length > 0 ){
                  url = arg0[0];                
              }

              Document doc = null;
          try {
            doc = stringToDom(convertStreamToString(new URL(url).openStream()));
          }
          catch (Exception e) {
            e.printStackTrace();
          }

          return doc;
    }
    //................
}

Unfortunately, I do not understand where the error exists. I see in LogCat (no filters):

01-24 17:47:44.194: W/Zygote(37): Preloaded drawable resource varies with configuration!! 01-24 17:47:44.204: W/Zygote(37): Preloaded drawable resource #0x1080446 (res/drawable-mdpi/popup_inline_error_above_holo_light.9.png) that varies with configuration!! 01-24 17:47:44.284: W/Zygote(37): Preloaded drawable resource #0x1080447 (res/drawable-mdpi/popup_inline_error_holo_dark.9.png) that varies with configuration!! 01-24 17:47:44.294: W/Zygote(37): Preloaded drawable resource #0x1080448 (res/drawable-mdpi/popup_inline_error_holo_light.9.png) that varies with configuration!! 01-24 17:47:46.315: W/Zygote(37): Preloaded drawable resource #0x10802ec (res/drawable-mdpi/ic_lockscreen_outerring.png) that varies with configuration!! 01-24 17:47:48.644: A/BatteryStatsImpl(93): Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory) 01-24 17:47:48.714: E/AndroidRuntime(93): Error reporting WTF 01-24 17:47:48.714: E/AndroidRuntime(93): at android.util.Log$1.onTerribleFailure(Log.java:103) 01-24 17:47:56.774: E/SoundPool(93): error loading /system/media/audio/ui/Lock.ogg 01-24 17:47:56.774: E/SoundPool(93): error loading /system/media/audio/ui/Unlock.ogg 01-24 17:48:03.064: W/NetworkManagementSocketTagger(93): setKernelCountSet(10005, 1) failed with errno -2 01-24 17:48:11.094: D/StrictMode(190): at com.android.internal.telephony.gsm.SpnOverride.loadSpnOverrides(SpnOverride.java:61) 01-24 17:48:11.094: D/StrictMode(190): at com.android.internal.telephony.gsm.SpnOverride.(SpnOverride.java:43) 01-24 17:48:12.592: E/SoundPool(93): error loading /system/media/audio/ui/Effect_Tick.ogg 01-24 17:48:12.592: E/SoundPool(93): error loading /system/media/audio/ui/Effect_Tick.ogg 01-24 17:48:12.592: E/SoundPool(93): error loading /system/media/audio/ui/Effect_Tick.ogg 01-24 17:48:12.592: E/SoundPool(93): error loading /system/media/audio/ui/Effect_Tick.ogg 01-24 17:48:12.592: E/SoundPool(93): error loading /system/media/audio/ui/Effect_Tick.ogg 01-24 17:48:12.592: E/SoundPool(93): error loading /system/media/audio/ui/KeypressStandard.ogg 01-24 17:48:12.592: E/SoundPool(93): error loading /system/media/audio/ui/KeypressSpacebar.ogg 01-24 17:48:12.592: E/SoundPool(93): error loading /system/media/audio/ui/KeypressDelete.ogg 01-24 17:48:12.592: E/SoundPool(93): error loading /system/media/audio/ui/KeypressReturn.ogg 01-24 17:48:12.982: W/AudioService(93): loadSoundEffects(), Error -1 while loading samples 01-24 17:48:20.262: A/NetworkStats(93): Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory) 01-24 17:48:24.822: D/StrictMode(190): at com.android.internal.telephony.gsm.GsmDataConnectionTracker.getPreferredApn(GsmDataConnectionTracker.java:2276) 01-24 17:48:28.822: A/NetworkStats(93): Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory) 01-24 17:48:30.883: D/MmsSmsDatabaseHelper(190): [MmsSmsDb] hasAutoIncrement: CREATE TABLE threads (_id INTEGER PRIMARY KEY AUTOINCREMENT,date INTEGER DEFAULT 0,message_count INTEGER DEFAULT 0,recipient_ids TEXT,snippet TEXT,snippet_cs INTEGER DEFAULT 0,read INTEGER DEFAULT 1,type INTEGER DEFAULT 0,error INTEGER DEFAULT 0,has_attachment INTEGER DEFAULT 0) result: true 01-24 17:48:38.492: W/MediaScanner(412): Error opening directory '/mnt/sdcard/.android_secure/', skipping: Permission denied. 01-24 17:48:44.462: I/ActivityManager(93): Start proc com.svox.pico for broadcast com.svox.pico/.VoiceDataInstallerReceiver: pid=541 uid=10024 gids={1015} 01-24 17:48:51.142: W/NetworkManagementSocketTagger(93): setKernelCountSet(10041, 1) failed with errno -2 01-24 17:48:55.792: W/NetworkManagementSocketTagger(93): setKernelCountSet(10005, 0) failed with errno -2

Filter by application name: There is void in LogCat.

Filter by tag "tag":

01-24 17:48:03.064: W/NetworkManagementSocketTagger(93): setKernelCountSet(10005, 1) failed with errno -2 01-24 17:48:51.142: W/NetworkManagementSocketTagger(93): setKernelCountSet(10041, 1) failed with errno -2 01-24 17:48:55.792: W/NetworkManagementSocketTagger(93): setKernelCountSet(10005, 0) failed with errno -2

Upvotes: 0

Views: 5085

Answers (1)

Karey Powell
Karey Powell

Reputation: 482

It seems as if the XML file is not being parsed correctly for use in your application. One possible solution to fix this is to create a proper XML parser and then use it to loop over all the nodes in your file in the AsyncTask. Here is an example of a parser I created:

Next, all you have to do is use the parser to get the DOM elements and push the information where ever you want to display it in the onPostExecute() method. Here is a sample,

........

private class LoadExampleTask extends
        AsyncTask<Void, Integer, ArrayList<HashMap<String, String>>> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // code here
    }

    @Override
    protected ArrayList<HashMap<String, String>> doInBackground(
            Void... params) {

        XMLParser parser = new XMLParser(); // the parser create as seen in the Gist from GitHub
        String xml = parser.getXmlFromUrl(URL); // getting XML from URL
        Document doc = parser.getDomElement(xml); // getting DOM element

        NodeList nl = doc.getElementsByTagName(KEY_VENUE);

        // looping through all song nodes <venue>
        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_TITLE, parser.getValue(e, KEY_TITLE));
            map.put(KEY_DESCRIPTION, parser.getValue(e, KEY_DESCRIPTION));
            map.put(KEY_LOCATION, parser.getValue(e, KEY_LOCATION.toString()));
            map.put(KEY_TAGS, parser.getValue(e, KEY_TAGS.toString()));
            map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
            map.put(KEY_THUMB_LARGE_URL, parser.getValue(e, KEY_THUMB_LARGE_URL));

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

        return exampleList;
    }

    @Override
    protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
        super.onPostExecute(result);

        try {
            // Getting adapter by passing xml data ArrayList
            adapter = new YourExampleAdapter(getActivity(), exampleList);
            list.setAdapter(adapter);
            adapter.notifyDataSetChanged();

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

........

Also, this is an example the structure of the XML file used for this approach, but any structure should be fine, as long as you are mapping the keys correctly:

<venues>
    <venue>
      <id></id>
      <title></title>
      <location></location>
      <tags></tags>
      <description></description>
      <thumb_url></thumb_url>
      <thumb_large_url></thumb_large_url>
    </venue>
</venues>

Hope this helps to fix your error.

Upvotes: 3

Related Questions