运行AsyncTask类后,下一个活动返回nullpointerexception

时间:2012-05-01 06:22:18

标签: android android-asynctask

这是我的AsyncTask类

private class UpdatingNews extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... params) {
        webservice.UpdateAllNews();
        webservice.updateallCatNews();
        return null;
    }

    @Override
    protected void onPostExecute(String result) {

    }
}

我叫它

UpdatingNewsupdate = new UpdatingNews();
        update.execute();

确实如此。然后我想检查这个任务的状态是否完成,当我点击按钮,所以我检查这样。

if (update.getStatus().toString()
                            .equals(AsyncTask.Status.FINISHED.toString())) {
                        toast = Toast.makeText(Main_FormNewUser.this,
                                "Thanks for fill in our survey form!",
                                Toast.LENGTH_SHORT);
                        toast.setGravity(Gravity.CENTER_VERTICAL
                                | Gravity.CENTER_HORIZONTAL, 0, 0);
                        toast.show();
                        name = nametext.getText().toString();
                        email = emailtext.getText().toString();
                        webservice.InsertSurvey(name, email, ages, genders,
                                jobs, salaries, interesting);
                        webservice.insertFormSubmit(1);

                        startActivity(new Intent(Main_FormNewUser.this,
                                Main_AllLatestNews.class));
                        finish();
                    }

点击后,它将启动Main_AllLatestNews.class但是使用NullPointerException。

我尝试不使用AsyncTask并且没有返回错误,我不知道为什么我调用AsyncTask它会给我错误?

2 个答案:

答案 0 :(得分:0)

如何以这种方式使用onPostExecute

添加布尔值以确定AsyncTask是否结束

@Override
protected void onPostExecute(String result) {
    check = true;
}


//if (update.getStatus().toString().equals(AsyncTask.Status.FINISHED.toString())) {
if(check){
                    toast = Toast.makeText(Main_FormNewUser.this,
                            "Thanks for fill in our survey form!",
                            Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.CENTER_VERTICAL
                            | Gravity.CENTER_HORIZONTAL, 0, 0);
                    toast.show();
                    name = nametext.getText().toString();
                    email = emailtext.getText().toString();
                    webservice.InsertSurvey(name, email, ages, genders,
                            jobs, salaries, interesting);
                    webservice.insertFormSubmit(1);

                    startActivity(new Intent(Main_FormNewUser.this,
                            Main_AllLatestNews.class));
                    finish();
                }

答案 1 :(得分:0)

了解AsyncTask的基础知识查看此博客。 Painless ThreadingAsyncTask

你还没有接受onPostExecute(字符串结果)中doInBackground()的返回

doInBackground()将结果返回给onPostExecute。因此,您必须仅在onPostExecute中更新所需的值或UI。