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 8579723
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T20:40:14+00:00 2026-06-11T20:40:14+00:00

The following is my code. XMLfunctions reads the XML file and stores it in

  • 0

The following is my code. XMLfunctions reads the XML file and stores it in String xml. I had to use AsyncTask as I got a NetworkOnMainThreadException. However I’m not sure of how to do it and am messing it up somewhere.

package foo.bar.quux;

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.os.AsyncTask;


public class XMLfunctions {


    int numResults;
    NodeList nodes;
    Document doc;
    static ServiceTasks task;
    String line;
    public final static Document XMLfromString(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) {
            System.out.println("XML parse error: " + e.getMessage());
            return null;
        } catch (SAXException e) {
            System.out.println("Wrong XML file structure: " + e.getMessage());
            return null;
        } catch (IOException e) {
            System.out.println("I/O exeption: " + e.getMessage());
            return null;
        }

        return doc;

    }


     private class ServiceTasks extends AsyncTask<Void, Void, Void> {

            @Override
            protected Void doInBackground(Void... urls) {

                            try {

                                    DefaultHttpClient httpClient = new DefaultHttpClient();
                                    HttpPost httpPost = new HttpPost("http://10.0.2.2/example.xml");

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

                                } catch (UnsupportedEncodingException e) {
                                    line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
                                } catch (MalformedURLException e) {
                                    line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
                                } catch (IOException e) {
                                    line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
                                }
                            return null;


            }


        } 

     public String getXML(){     

         return line;
    }

     public void executeXML(){
         task = new ServiceTasks();
         task.execute();
     }


}

The methods executeXML() and getXML() are called in another activity :

  public class Main extends ListActivity {

         String xml;
         static XMLfunctions funct;
    @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.listofcategories);
            funct = new XMLfunctions();
            funct.executeXML();
            xml = funct.getXML();
.
.
.
}

However xml seems to be null even after executeXML is called as I get a NullPointerException. Where am I going wrong?

  • 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-11T20:40:15+00:00Added an answer on June 11, 2026 at 8:40 pm

    You will not get the results until the AsyncTask is done.

    So, even though, the control is moved to the line xml = funct.getXML();, and this line is executed, this does not mean that the AsyncTask is done.

    Your results will be available when doInBackground returns and in your AsyncTask override the function onPostExecute and report results back to the caller.

    Implement a listener in such a way:

    package foo.bar.quux;
    
    import java.io.IOException;
    import java.io.StringReader;
    import java.io.UnsupportedEncodingException;
    import java.net.MalformedURLException;
    
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.util.EntityUtils;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    
    import android.os.AsyncTask;
    
    
    public class XMLfunctions {
    
        public interface ListenerToXML {
                public void AsyncTaskDone();
        }
        ListenerToXML mListener;
        public void setListener(ListenerToXML listener) {
            mListener = listener;
        }
        int numResults;
        NodeList nodes;
        Document doc;
        static ServiceTasks task;
        String line;
        public final static Document XMLfromString(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) {
                System.out.println("XML parse error: " + e.getMessage());
                return null;
            } catch (SAXException e) {
                System.out.println("Wrong XML file structure: " + e.getMessage());
                return null;
            } catch (IOException e) {
                System.out.println("I/O exeption: " + e.getMessage());
                return null;
            }
    
            return doc;
    
        }
    
    
         private class ServiceTasks extends AsyncTask<Void, Void, Void> {
    
                @Override
                protected Void doInBackground(Void... urls) {
    
                                try {
    
                                        DefaultHttpClient httpClient = new DefaultHttpClient();
                                        HttpPost httpPost = new HttpPost("http://10.0.2.2/example.xml");
    
                                        HttpResponse httpResponse = httpClient.execute(httpPost);
                                        HttpEntity httpEntity = httpResponse.getEntity();
                                        line = EntityUtils.toString(httpEntity);
    
                                    } catch (UnsupportedEncodingException e) {
                                        line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
                                    } catch (MalformedURLException e) {
                                        line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
                                    } catch (IOException e) {
                                        line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
                                    }
                                return null;
    
    
                }
    @Override
    protected void onPostExecute(Void result) {
        if(mListener!=null)
            mListener.AsyncTaskDone();
        }
    
    
            } 
    
         public String getXML(){     
    
             return line;
        }
    
         public void executeXML(){
             task = new ServiceTasks();
             task.execute();
         }
    
    
    }
    
    
    
    
      public class Main extends ListActivity implements ListenerToXML {
    
             String xml;
             static XMLfunctions funct;
        @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.listofcategories);
                funct = new XMLfunctions();
                funct.setListener(this);
                funct.executeXML();
    .
    .
    .
    }
    
    
                public void AsyncTaskDone() {
                   //here you can get the results
                xml = funct.getXML();
                }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Following code I can use for storing the value of UILabel into a string.
Following code transfer file successfully, but does not print in lable that it has
Following code is written to fetch the data from the xml file. I think
Following code does compile whereas name aNumber is not declared before use. class A
following code is used to find url from a string with php. Here is
Following code is from my REPL: scala> words.zipWithIndex.filter((x:java.lang.String,index:Int)=>index%2==0) <console>:9: error: type mismatch; found :
Following code is only to show how to use condition variable to synchronize threads(one
Following code works fine in Firefox. In IE(8.0) button 2 does not work. $('<button
Following code is saved as html file: <?php $IP = 4; ?> <textarea name=comments>$IP</textarea>
following code works perfectly on FF and Chrome but not in IE8. $(window).keyup(function(e) {

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.