如何通过url获取xml(AsyncTask,android)?

时间:2013-01-24 18:07:22

标签: android android-asynctask

我有以下课程:

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;
    }
    //................
}

不幸的是,我不明白错误存在于何处。我在LogCat中看到(没有过滤器):

  

01-24 17:47:44.194:W / Zygote(37):预装的可绘制资源   随配置而变化!! 01-24 17:47:44.204:W / Zygote(37):   预加载的可绘制资源#0x1080446   (res / drawable-mdpi / popup_inline_error_above_holo_light.9.png)那个   随配置而变化!! 01-24 17:47:44.284:W / Zygote(37):   预加载的可绘制资源#0x1080447   (res / drawable-mdpi / popup_inline_error_holo_dark.9.png)变化多端   配置!! 01-24 17:47:44.294:W / Zygote(37):预装   可绘制资源#0x1080448   (res / drawable-mdpi / popup_inline_error_holo_light.9.png)变化多端   配置!! 01-24 17:47:46.315:W / Zygote(37):预装   可绘制资源#0x10802ec   (res / drawable-mdpi / ic_lockscreen_outerring.png)随之变化   组态!! 01-24 17:47:48.644:A / BatteryStatsImpl(93):引起:   libcore.io.ErrnoException:open failed:ENOENT(没有这样的文件或   目录)01-24 17:47:48.714:E / AndroidRuntime(93):错误报告   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):加载错误/system/media/audio/ui/Lock.ogg 01-24   17:47:56.774:E / SoundPool(93):加载错误   /system/media/audio/ui/Unlock.ogg 01-24 17:48:03.064:   W / NetworkManagementSocketTagger(93):setKernelCountSet(10005,1)   错误的错误-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):加载错误   /system/media/audio/ui/Effect_Tick.ogg 01-24 17:48:12.592:   E / SoundPool(93):加载错误/system/media/audio/ui/Effect_Tick.ogg   01-24 17:48:12.592:E / SoundPool(93):加载错误   /system/media/audio/ui/Effect_Tick.ogg 01-24 17:48:12.592:   E / SoundPool(93):加载错误/system/media/audio/ui/Effect_Tick.ogg   01-24 17:48:12.592:E / SoundPool(93):加载错误   /system/media/audio/ui/Effect_Tick.ogg 01-24 17:48:12.592:   E / SoundPool(93):加载错误   /system/media/audio/ui/KeypressStandard.ogg 01-24 17:48:12.592:   E / SoundPool(93):加载错误   /system/media/audio/ui/KeypressSpacebar.ogg 01-24 17:48:12.592:   E / SoundPool(93):加载错误   /system/media/audio/ui/KeypressDelete.ogg 01-24 17:48:12.592:   E / SoundPool(93):加载错误   /system/media/audio/ui/KeypressReturn.ogg 01-24 17:48:12.982:   W / AudioService(93):loadSoundEffects(),加载样本时出错-1   01-24 17:48:20.262:A / NetworkStats(93):引起:   libcore.io.ErrnoException:open failed:ENOENT(没有这样的文件或   目录)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):引起:   libcore.io.ErrnoException:open failed:ENOENT(没有这样的文件或   目录)01-24 17:48:30.883:D / MmsSmsDatabaseHelper(190):[MmsSmsDb]   hasAutoIncrement:CREATE TABLE线程(_id INTEGER PRIMARY KEY   AUTOINCREMENT,日期INTEGER DEFAULT 0,message_count INTEGER DEFAULT   0,recipient_id TEXT,snippet TEXT,snippet_cs INTEGER DEFAULT 0,读取   INTEGER DEFAULT 1,输入INTEGER DEFAULT 0,错误INTEGER DEFAULT   0,has_attachment INTEGER DEFAULT 0)结果:true 01-24 17:48:38.492:   W / MediaScanner(412):打开目录时出错   '/mnt/sdcard/.android_secure/',跳过:权限被拒绝。 01-24   17:48:44.462:I / ActivityManager(93):启动proc com.svox.pico   broadcast com.svox.pico / .VoiceDataInstallerReceiver:pid = 541 uid = 10024   gids = {1015} 01-24 17:48:51.142:W / NetworkManagementSocketTagger(93):   setKernelCountSet(10041,1)以errno -2 01-24 17:48:55.792失败:   W / NetworkManagementSocketTagger(93):setKernelCountSet(10005,0)   errno -2

失败了

按应用程序名称过滤: LogCat中存在空白。

按标签“tag”过滤:

  

01-24 17:48:03.064:W / NetworkManagementSocketTagger(93):   setKernelCountSet(10005,1)以errno -2 01-24 17:48:51.142失败:   W / NetworkManagementSocketTagger(93):setKernelCountSet(10041,1)   错误的错误-2 01-24 17:48:55.792:   W / NetworkManagementSocketTagger(93):setKernelCountSet(10005,0)   errno -2

失败了

1 个答案:

答案 0 :(得分:3)

似乎没有正确解析XML文件以便在您的应用程序中使用。解决此问题的一种可能解决方案是创建适当的XML解析器,然后使用它来遍历AsyncTask中文件中的所有节点。以下是我创建的解析器示例:

接下来,您所要做的就是使用解析器获取DOM元素,并将信息推送到您希望在onPostExecute()方法中显示的位置。这是一个样本,

........

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();
        }
    }
}

........

此外,这是用于此方法的XML文件的结构示例,但只要正确映射键,任何结构都应该没问题:

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

希望这有助于解决您的错误。