0

我有一个解析 XML 文件的 HTTP 请求。我正在尝试从 asyntask 连接到互联网,但我无法

我这样做并通过将代码放在线程中而不是在 AsycTask 中来工作我遇到的问题是 HTTP 请求是在使用以下代码行的字符串中调用的:

String xml = parser.getXmlFromUrl(URL);

运行这个

public String getXmlFromUrl(String url) {
            Thread t= new Thread(){
                public void run() {
                    xml = null;              
                    try {
                        Log.i("Log1","Parse");
                        // defaultHttpClient
                        DefaultHttpClient httpClient = new DefaultHttpClient();
                        HttpPost httpPost = new HttpPost("http://api.androidhive.info/music/music.xml");

                        HttpResponse httpResponse = httpClient.execute(httpPost);
                        HttpEntity httpEntity = httpResponse.getEntity();
                        xml = EntityUtils.toString(httpEntity);

                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    } catch (ClientProtocolException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    mHandler.post(mUpdateResults);
                }
            };
            t.start();
            return xml;
        }

        final Runnable mUpdateResults =new Runnable (){
            public void run(){//2

            }
        };

正如我所提到的,HTTP 请求在一个线程中,但是当我尝试将它放在 AsycTask 中时,我总是会发现错误......我不知道该怎么做。

我已经参考了 AsycTask 的文档并阅读了很多次,我搜索了教程,但我无法正确构建它。

两天后,我开始有点绝望

我为我的工作放了完整的代码,如果有人能告诉我如何替换 AsyncTask 线程,我将非常感激。

非常感谢和问候

完整的活动:

public class PruebasActivity extends Activity {


    static final String URL = "http://api.androidhive.info/music/music.xml";
    // XML node keys
        static final String KEY_SONG = "song"; // parent node
        static final String KEY_ID = "id";
        static final String KEY_TITLE = "title";
        static final String KEY_ARTIST = "artist";
        static final String KEY_DURATION = "duration";
        static final String KEY_THUMB_URL = "thumb_url";

        private ArrayList<HashMap<String, String>> data;
        ArrayList<HashMap<String, String>> songsList;

        ListView list;
        LazyAdapter adapter;
        String xml;

        final Handler mHandler=new Handler();


        // constructor
        public void XMLParser() {

        }

        /**
         * Cogiendo el XML de la URL mediante HTTP request
         * @param url string
         * */
        public String getXmlFromUrl(String url) {
            Thread t= new Thread(){
                public void run() {
                    xml = null;              
                    try {
                        Log.i("Log1","Parse");
                        // defaultHttpClient
                        DefaultHttpClient httpClient = new DefaultHttpClient();
                        HttpPost httpPost = new HttpPost("http://api.androidhive.info/music/music.xml");

                        HttpResponse httpResponse = httpClient.execute(httpPost);
                        HttpEntity httpEntity = httpResponse.getEntity();
                        xml = EntityUtils.toString(httpEntity);

                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    } catch (ClientProtocolException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    mHandler.post(mUpdateResults);
                }
            };
            t.start();
            return xml;
        }

        final Runnable mUpdateResults =new Runnable (){
            public void run(){//2

            }
        };

        /*
         * @param XML string
         * */
        public Document getDomElement(String xml){
            Document doc = null;
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            try {

                DocumentBuilder db = dbf.newDocumentBuilder();

                InputSource is = new InputSource();
                is.setCharacterStream(new StringReader(xml));
                doc = db.parse(is); 

            } catch (ParserConfigurationException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (SAXException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (IOException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            }

            return doc;
        }

        /*
         * @param elem element
         */
        public final String getElementValue( Node elem ) {
            Node child;
            if( elem != null){
                if (elem.hasChildNodes()){
                    for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
                        if( child.getNodeType() == Node.TEXT_NODE  ){
                            return child.getNodeValue();
                        }
                    }
                }
            }
            return "";
        }

        /*
         * @param Element node
         * @param key string
         * */
        public String getValue(Element item, String str) {      
            NodeList n = item.getElementsByTagName(str);        
            return this.getElementValue(n.item(0));
        }

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

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

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

        XMLParser parser = new XMLParser();
        String xml = parser.getXmlFromUrl(URL); // Cogiendo XML de la URL
        Document doc = parser.getDomElement(xml); // Cogiendo DOM de los elementos

        NodeList nl = doc.getElementsByTagName(KEY_SONG);
        // looping through all song nodes <song>
        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_ARTIST, parser.getValue(e, KEY_ARTIST));
            map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
            map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));          

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

        // Pasando datos parseados del adaptador al arrayList
        adapter=new MinAdapter(this, songsList);        
        list.setAdapter(adapter);   
    }
}
4

2 回答 2

0

以下代码应该适合您。试试看:

public class PruebasActivity extends Activity {

static final String URL = "http://api.androidhive.info/music/music.xml";
// XML node keys
    static final String KEY_SONG = "song"; // parent node
    static final String KEY_ID = "id";
    static final String KEY_TITLE = "title";
    static final String KEY_ARTIST = "artist";
    static final String KEY_DURATION = "duration";
    static final String KEY_THUMB_URL = "thumb_url";

    private ArrayList<HashMap<String, String>> data;
    ArrayList<HashMap<String, String>> songsList;

    ListView list;
    LazyAdapter adapter;
    String xml;

    // constructor
    public void XMLParser() {

    }

    /**
     * Cogiendo el XML de la URL mediante HTTP request
     * @param url string
     * */
    public String getXmlFromUrl(String url) {
            xml = null;              
            try {
                Log.i("Log1","Parse");
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost("http://api.androidhive.info/music/music.xml");

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                xml = EntityUtils.toString(httpEntity);

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        return xml;
    }


    /*
     * @param XML string
     * */
    public Document getDomElement(String xml){
        Document doc = null;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {

            DocumentBuilder db = dbf.newDocumentBuilder();

            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(xml));
            doc = db.parse(is); 

        } catch (ParserConfigurationException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        } catch (SAXException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        } catch (IOException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        }

        return doc;
    }

    /*
     * @param elem element
     */
    public final String getElementValue( Node elem ) {
        Node child;
        if( elem != null){
            if (elem.hasChildNodes()){
                for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
                    if( child.getNodeType() == Node.TEXT_NODE  ){
                        return child.getNodeValue();
                    }
                }
            }
        }
        return "";
    }

    /*
     * @param Element node
     * @param key string
     * */
    public String getValue(Element item, String str) {     
        NodeList n = item.getElementsByTagName(str);        
        return this.getElementValue(n.item(0));
    }

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

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

    AsyncTask<Void, Void, Void> ast = new AsyncTask<Void, Void, Void>(){
        ProgressDialog p;
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
             p = new ProgressDialog(EditTextDemoActivity.this);
            //write code to start the progress dialog
        }

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
            songsList = new ArrayList<HashMap<String, String>>();

            XMLParser parser = new XMLParser();
            String xml = parser.getXmlFromUrl(URL); // Cogiendo XML de la URL
            Document doc = parser.getDomElement(xml); // Cogiendo DOM de los elementos

            NodeList nl = doc.getElementsByTagName(KEY_SONG);
            // looping through all song nodes <song>
            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_ARTIST, parser.getValue(e, KEY_ARTIST));
                map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
                map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));          

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


        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            p.dismiss();
            adapter=new MinAdapter(this, songsList);        
            lst.setAdapter(adapter); 
        }
    };

    ast.execute();
}
}

我已经使用AsyncTask. Thread当您使用AsyncTask. 我留下了一小部分编码(用于创建和显示进度对话框)作为练习。

希望这可以帮助。

于 2012-07-10T18:13:08.463 回答
0

HTTP 请求可以在 Asynctask 的 doInBackground 函数中运行,而您的可运行对象是 onPostExecute 函数。结果是这样的:

public class XmlTask extends AsyncTask<String, Void, String>{

    public String doInBackground(String... urls){
        String url = urls[0];

        // Place your getXmlFromUrl content here

        return xml;
    }

    public void onPostExecute(String xml){
        // Your XML parsing staement here
    }
}

在此代码中,不需要 Thread 和 runnable。

在您的活动中,只需点击:

new XmlTask().execute("http://yoururl");
于 2012-07-10T17:45:25.060 回答