0

以下是我的代码。XMLfunctions 读取 XML 文件并将其存储在String xml. 我不得不使用 AsyncTask,因为我得到了 NetworkOnMainThreadException。但是,我不确定该怎么做,并且在某处搞砸了。

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


}

方法executeXML()getXML()在另一个活动中被调用:

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

然而,即使在executeXML我得到一个NullPointerException. 我哪里错了?

4

1 回答 1

2

在 AsyncTask 完成之前,您不会得到结果。

因此,即使将控件移至行xml = funct.getXML();,并执行了该行,但这并不意味着 AsyncTask 已完成。

您的结果将在doInBackground返回时可用,并且在您的 AsyncTask 中覆盖该函数onPostExecute并将结果报告给调用者。

以这样的方式实现一个监听器:

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();
            }
于 2012-09-22T16:57:40.793 回答