为什么我的AsyncTask doInBackground()没有将值传递给onPostExecute()?

时间:2017-09-24 07:37:22

标签: android android-asynctask

当我运行我的代码时,它返回一个值为“null”`

private class   MessageActivityLoaderTask extends AsyncTask<Void, Void, Contentlist> {
    private LinkedMultiValueMap<String, String> formData;
    Activity activity;

    public MessageActivityLoaderTask(Activity activity) {
        this.activity = activity;
    }

    @Override
    protected void onPreExecute() {
        formData = new LinkedMultiValueMap<String, String>();
        mProgress.setMessage("Please wait..");
        mProgress.show();
    }

    @Override
    protected Contentlist doInBackground(Void... params) {
        String url = getString(R.string.base_url) + "/example/example1/1";
        Contentlist mess = null;
        try {
            mess = RestUtils.exchangeFormData(url, HttpMethod.GET, formData, Contentlist.class);
        } catch (Exception e) {
            e.printStackTrace();
            mProgress.dismiss();
        }
        return mess;

    }

    protected void onPostExecute(Contentlist result) {

        if (result== null) {
            Toast message = Toast.makeText(ListobjectsActivity.this, "result is empty", Toast.LENGTH_SHORT);
            message.show();
        } else {
            ListactivityAdapter adapter = new ListactivityAdapter(this.activity, result.getContents());

            ListView list = (ListView) activity.findViewById(R.id.account);
            list.setAdapter(adapter);
            mProgress.dismiss();
        }

    }`

1 个答案:

答案 0 :(得分:2)

您的AsyncTask看起来设置正确,因此onPostExecute()会收到ContentList返回的doInBackgroun()。由于onPostExecute()看到null,因此doInBackground()返回null。这意味着doInBackground()正在获得异常,mess永远不会通过catchRestUtils.exchangeFormData()落入非空值而返回null。

我建议您调试此区域中的代码以查看实际情况。它可能不是AsyncTask问题。