Json Element在AsyncTask中返回null

时间:2013-01-08 16:47:06

标签: android android-asynctask

当我在wpCategories = JsonToElement.getllAllCategory();按钮中仅调用onClick时,它可以正常工作。 (wpCategories填充数据)。但是当我把它放在asynctask中时,wpCategories返回null。 (doInBackground是否被调用?)

这是我点击垃圾的按钮:

public void onImageGridClick(View view) {       
    new GetJsonElementTask().execute();
    Intent intent = new Intent(this, CategoryGridActivity.class);       
    intent.putParcelableArrayListExtra(Extra.IMAGES, wpCategories);
    startActivity(intent);
}

asyncTask:

private class GetJsonElementTask extends AsyncTask<Void, Integer, String> {
    @Override
    protected void onPreExecute() {
        progressDialog = ProgressDialog.show(HomeActivity.this, "",
                "Loading...");          
    }
    @Override
    protected String doInBackground(Void... arg0) {
        wpCategories = JsonToElement.getllAllCategory();
        return null;
    }

    @Override
    protected void onPostExecute(String value) {
        progressDialog.dismiss();
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        Log.v("DEBUG_LOG", "In onProgressUpdate");
    }

}

2 个答案:

答案 0 :(得分:2)

onPostExecute内启动您的活动,因为此方法在doInBackground执行完成后执行:

 @Override
    protected String doInBackground(Void... arg0) {
        wpCategories = JsonToElement.getllAllCategory();

        return wpCategories;  //<<< return value from here
    }
 @Override
    protected void onPostExecute(String value) {
        progressDialog.dismiss();

        Intent intent = new Intent(this, CategoryGridActivity.class);       
        intent.putParcelableArrayListExtra(Extra.IMAGES, value);
        startActivity(intent);
    }

答案 1 :(得分:1)

尝试以下

public void onImageGridClick(View view) {       
    new GetJsonElementTask().execute();
}

    public void startCategoryGridActivity(){
           Intent intent = new Intent(this, CategoryGridActivity.class);        
       intent.putParcelableArrayListExtra(Extra.IMAGES, wpCategories);
       startActivity(intent);
    }

asyncTask:

private class GetJsonElementTask extends AsyncTask<Void, Integer, String> {
    @Override
    protected void onPreExecute() {
        progressDialog = ProgressDialog.show(HomeActivity.this, "",
                "Loading...");          
    }
    @Override
    protected String doInBackground(Void... arg0) {
        wpCategories = JsonToElement.getllAllCategory();
        return null;
    }

    @Override
    protected void onPostExecute(String value) {
        progressDialog.dismiss();
            startCategoryGridActivity();
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        Log.v("DEBUG_LOG", "In onProgressUpdate");
    }

}