1

I'm using jsoup to parse a html code, I'm using obviously an AsyncTask but it's returning null (javanullpointerexception).

private class LoadDocument extends AsyncTask<String, Void, Document>
    {

        ProgressDialog mProgressDialog;



        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(Parser.this, "Loading...", "Recuperation donnees...");
        }



        @Override
        protected Document doInBackground(String... url) {
            url[0] = urll;

                try {
                    document = Jsoup.connect(url[0])
                            .data("query", "Java")
                            .userAgent("Mozilla")
                            .cookie("auth", "token")
                            .timeout(10000)
                            .post();
                } catch (IOException e) {
                    e.printStackTrace();
                }



            return document;
        }

        @Override
        protected void onPostExecute(Document result) {
             document=result;
            mProgressDialog.dismiss();

        }


}

And then to execute a task and return the document:

urll= //the website
document=new LoadDocument().execute(urll).get();

I guess that document is always null. What's going wrong in my code? Thank you for helping.

androniennn
  • 3,117
  • 11
  • 50
  • 107

4 Answers4

2

There's nothing wrong with the code. Please log it with Document.text(); Can you try changing the one line to check: doc = Jsoup.connect("http://stackoverflow.com").get(); then use Document.text() in your log.

wtsang02
  • 18,603
  • 10
  • 49
  • 67
1

AsyncTask.execute() doesn't return the result. Instead it returns a reference to the task itself. The result is only available to the onPostExecute method once the task completed.

patheticpat
  • 861
  • 6
  • 11
  • And i think that `execute(URL).get()` returns result value, no ? – androniennn Dec 22 '12 at 17:55
  • Oops, you are right, `get()` waits for the task to finish and retrieves the result. Although this pretty much defeats the purpose of an `AsyncTask`. It doesn't make sense to start the work in the background and then block to wait until it finished. – patheticpat Dec 22 '12 at 17:59
0

many can go wrong in that code:

url[0]

can be an empty string...

I would split that statement to:

Jsoup.connect(url[0])

+

.data("query", "Java")
                            .userAgent("Mozilla")
                            .cookie("auth", "token")
                            .timeout(10000)
  • .post();

at least

0

Problem is somewhere inside your try catch block around the Jsoup code. Instead of printStackTrace, log something with Log.e, and then check your LogCat output.

tom
  • 18,953
  • 4
  • 35
  • 35