0

以下は私のコードです。XMLfunctions は XML ファイルを読み取り、.xml ファイルに保存しますString xml。NetworkOnMainThreadException が発生したため、AsyncTask を使用する必要がありました。しかし、私はそれを行う方法がわからず、どこかを台無しにしています。

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ただし、 .xmlを取得すると、 が呼び出された後でも xml は null のよう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 に答える