Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8199985
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T06:16:59+00:00 2026-06-07T06:16:59+00:00

I have an HTTP Request that parses an XML file. I’m trying to connect

  • 0

I have an HTTP Request that parses an XML file.
I’m trying to connect to internet from an asyntask but I have not been able

I do this and works by putting the code inside a thread, but not inside an AsycTask
The problem I have is that the HTTP Request is called within a String with this line of code:

String xml = parser.getXmlFromUrl(URL);

Running this

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

            }
        };

As I mentioned, the HTTP Request is within a thread, but I always find errors when I try to put it inside a AsycTask … I do not know how do it.

I have been referred to the documentation of AsycTask and have read many times, I have searched tutorials, but I could not build it correctly.

After two days, i begin to be a little desperate

I put the complete code for my work, if anyone can tell me how to replace a AsyncTask thread, I’ll be very grateful.

Thank you very much and regards

full activity:

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);   
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T06:17:01+00:00Added an answer on June 7, 2026 at 6:17 am

    The HTTP request can be run in the doInBackground function of Asynctask and your runnable is the onPostExecute function.
    The result is this :

    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
        }
    }
    

    In this code, Thread and runnable are unnecessary.

    And in your activity just tap:

    new XmlTask().execute("http://yoururl");
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string containing XML data that is returned from an http request.
I have an HTTP Request Dispatcher class that works most of the time, but
I have a table view controller that makes an http request, which returns xml.
So I have a small project that parses through an XML file. I am
I have set up several http request samplers in Jmeter that have either get
I have a relatively simple object with a method that makes an HTTP request.
I have a django view that returns HTTP 301 on a curl request: grapefruit:~
I have long HTTP request ( generating large Excel file - about 60K records
I have a servlet that users post a XML file to. I read that
I have to send an XML request to recover data from a remote server

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.