执行异步任务时出错

时间:2013-05-27 09:11:31

标签: java android android-asynctask apache-commons-httpclient background-thread

我试图从几个网页获取一些数据并将其保存到文件中。我正在Android中的AsynkTask(doInBackground)中完成所有这些操作。当我在我的模拟器中运行应用程序时......我收到运行时错误:执行doInBackground时出错。我跑了几次代码,但似乎无法找出问题所在。这是我下面的代码......有人请帮助我!!另外请告诉我如何改进这段代码......现在真的很乏味。

public class OpeningActivity extends Activity {

static final String PAGE_URL = "http://www.facebook.com/pages/Symbiosis-College-of-   Arts-Commerce-Confession/524808617560510";
static String title, imgSource, viewFormLink, viewFormEntry, formResponse, data;
static PrintWriter writer, formWriter, dfWriter;
static FileInputStream fis;
static File dataFile, confessionsPage, formFile;
Button setup;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_opening);
    setup = (Button) findViewById(R.id.btnSetup);

    setup.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            new getWebPage().execute(PAGE_URL);
        }
    });
}


public class getWebPage extends AsyncTask<String, Integer, String> {

protected void onPreExecute(String f) {
    // TODO Setting up variables
    f = "whatevs";
}

@Override
protected String doInBackground(String... params) {
    // TODO Auto-generated method stub
    DefaultHttpClient urlClient = new DefaultHttpClient();
    HttpGet getHtml = new HttpGet(PAGE_URL);
    ResponseHandler<String> resHandler = new BasicResponseHandler();
    try {
        String htmlPage = urlClient.execute(getHtml, resHandler);
                    lod.d("htmlpage", htmplPage);
        confessionsPage = new File("ConfessionsPage.html");
        confessionsPage.createNewFile();
        writer = new PrintWriter(confessionsPage, "UTF-8");
        writer.print(htmlPage.replace("<!--", "").replace("-->", ""));
        writer.flush();
        writer.close();

        Document doc = Jsoup.parse(confessionsPage, "UTF-8", "http://www.facebook.com/");
        title = doc.title().substring(0, doc.title().length() - 11);

        Elements imgSRC = doc.select("img[src$=.jpg]");
        for (Element element : imgSRC) {
            if (element.attr("class").equals("profilePic img")) {
                imgSource = element.attr("src");
            }
        }

        Elements links = doc.select("a[href*=google]");
        viewFormLink = null;
        for (Element element : links) {
            viewFormLink = element.attr("href");
        }
        viewFormLink = viewFormLink.replace("http://www.facebook.com/l.php?u=", "");
        int ampLOC = viewFormLink.indexOf("&");
        viewFormLink = viewFormLink.substring(0, ampLOC);
        viewFormLink = URLDecoder.decode(viewFormLink, "UTF-8");

        formResponse = viewFormLink.substring(0, (viewFormLink.length() - 8));
        formResponse = formResponse + "formResponse";
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    DefaultHttpClient formClient = new DefaultHttpClient();
    HttpGet getForm = new HttpGet(viewFormLink);
    ResponseHandler<String> resHandler2 = new BasicResponseHandler();

    try {
        String formPage = formClient.execute(getForm, resHandler2);
        formFile = new File("FormPage.html");
        formFile.createNewFile();
        formWriter.write(formPage);
        formWriter.flush();
        formWriter.close();

        Document doc2 = Jsoup.parse(formFile, "UTF-8", "http://www.facebook.com");
        Elements entry = doc2.select("textarea[name^=entry]");
        viewFormEntry = entry.attr("name");

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    dataFile = new File("DataFile");
    try {
        dataFile.createNewFile();
        dfWriter = new PrintWriter(dataFile);
        dfWriter.println(title);
        dfWriter.println();
        dfWriter.println(imgSource);
        dfWriter.println();
        dfWriter.println(viewFormLink);
        dfWriter.println();
        dfWriter.println(viewFormEntry);
        dfWriter.println();
        dfWriter.println(formResponse);

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        fis = new FileInputStream(dataFile);
        byte [] dataArray = new byte [fis.available()];
        while (fis.read() != -1) {
            data = new String(dataArray);
        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return data;
}

@Override
protected void onProgressUpdate(Integer... progress) {
    // TODO Auto-generated method stub

}

@Override
protected void onPostExecute(String result) {
    // TODO Auto-generated method stub
    Bundle dataBundle = new Bundle();
    dataBundle.putString("mydata", result);

    Intent intent = new Intent(OpeningActivity.this, Main.class);
    intent.putExtras(dataBundle);
    startActivity(intent);
}
}
}

我稍微更改了代码。我现在在doInBackground中返回数据字符串变量。我在清单文件中添加了Internet权限。 我仍然得到同样的错误。以下是我的错误日志,仅为方便起见:

05-27 10:36:25.995: E/AndroidRuntime(741): FATAL EXCEPTION: AsyncTask #1
05-27 10:36:25.995: E/AndroidRuntime(741): java.lang.RuntimeException: An error occured while executing doInBackground()
05-27 10:36:25.995: E/AndroidRuntime(741):  at android.os.AsyncTask$3.done(AsyncTask.java:299)
05-27 10:36:25.995: E/AndroidRuntime(741):  at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
05-27 10:36:25.995: E/AndroidRuntime(741):  at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
05-27 10:36:25.995: E/AndroidRuntime(741):  at java.util.concurrent.FutureTask.run(FutureTask.java:239)
05-27 10:36:25.995: E/AndroidRuntime(741):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
05-27 10:36:25.995: E/AndroidRuntime(741):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
05-27 10:36:25.995: E/AndroidRuntime(741):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
05-27 10:36:25.995: E/AndroidRuntime(741):  at java.lang.Thread.run(Thread.java:856)
05-27 10:36:25.995: E/AndroidRuntime(741): Caused by: java.lang.NullPointerException
05-27 10:36:25.995: E/AndroidRuntime(741):  at org.apache.http.impl.client.AbstractHttpClient.determineTarget(AbstractHttpClient.java:496)
05-27 10:36:25.995: E/AndroidRuntime(741):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:626)
05-27 10:36:25.995: E/AndroidRuntime(741):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:616)
05-27 10:36:25.995: E/AndroidRuntime(741):  at org.social.myconfessions.OpeningActivity$getWebPage.doInBackground(OpeningActivity.java:68)
05-27 10:36:25.995: E/AndroidRuntime(741):  at org.social.myconfessions.OpeningActivity$getWebPage.doInBackground(OpeningActivity.java:1)
05-27 10:36:25.995: E/AndroidRuntime(741):  at android.os.AsyncTask$2.call(AsyncTask.java:287)
05-27 10:36:25.995: E/AndroidRuntime(741):  at java.util.concurrent.FutureTask.run(FutureTask.java:234)
05-27 10:36:25.995: E/AndroidRuntime(741):  ... 4 more

1 个答案:

答案 0 :(得分:0)

您没有在这些初始化中指定任何变量

DefaultHttpClient urlClient = new DefaultHttpClient();
HttpGet getHtml = new HttpGet();
ResponseHandler<String> resHandler = new BasicResponseHandler();

String htmlPage = urlClient.execute(getHtml, resHandler);没有任何值可以返回空的“新”变量;

试试这个:

DefaultHttpClient urlClient = new DefaultHttpClient();
HttpGet getHtml = new HttpGet(PAGE_URL);
ResponseHandler<String> resHandler = new BasicResponseHandler();

P.S :如果要显示调试消息/ logcat消息,请尝试使用

Log.d("String Identifier", String_Variable);

例如,如果要输出字符串变量htmlPage的内容,请执行以下操作:

Log.d("htmlPage", htmlPage);