AsyncTask不调用onPostExecute()

时间:2014-09-25 22:41:11

标签: android android-asynctask

我有一个Android AsyncTaskonPostExecute()永远不会运行。

现在,我知道我的doInBackground()已经完成,因为我测试了它。

我的onPostExecute()就是这样:

 protected void onPostExecute( ) {
    System.out.println("onPost");
    helper.close();
    System.out.println("worked");
    if (unitary && exists)    {  
        adapter.notifyDataSetChanged();
        System.out.println("notified");
    }
    }

没有打印出任何打印行。

我是否必须在某处实际调用该方法?

1 个答案:

答案 0 :(得分:2)

  

我是否必须在某处实际调用该方法?

不,但你必须正确实施。

首先向其添加@Override注释。当您覆盖方法(或实现在接口上定义的方法)时,始终执行此操作。

然后,您将收到编译错误,指出您的方法实际上没有覆盖任何内容。这是因为onPostExecute()始终采用AsyncTask声明中第三种类型的参数。因此,如果您要创建AsyncTask<Foo, Bar, Baz>onPostExecute()会将Baz作为参数。

以下是使用AsyncTask模拟在后台下载数据的片段的示例实现。它使用Void作为AsyncTask声明中的第三种数据类型(根据您的评论),因此将Void作为onPostExecute()的参数:

/***
  Copyright (c) 2008-2014 CommonsWare, LLC
  Licensed under the Apache License, Version 2.0 (the "License"); you may not
  use this file except in compliance with the License. You may obtain   a copy
  of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
  by applicable law or agreed to in writing, software distributed under the
  License is distributed on an "AS IS" BASIS,   WITHOUT WARRANTIES OR CONDITIONS
  OF ANY KIND, either express or implied. See the License for the specific
  language governing permissions and limitations under the License.

  From _The Busy Coder's Guide to Android Development_
    http://commonsware.com/Android
 */

package com.commonsware.android.async;

import android.app.ListFragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import java.util.ArrayList;

public class AsyncDemoFragment extends ListFragment {
  private static final String[] items= { "lorem", "ipsum", "dolor",
      "sit", "amet", "consectetuer", "adipiscing", "elit", "morbi",
      "vel", "ligula", "vitae", "arcu", "aliquet", "mollis", "etiam",
      "vel", "erat", "placerat", "ante", "porttitor", "sodales",
      "pellentesque", "augue", "purus" };
  private ArrayList<String> model=null;
  private ArrayAdapter<String> adapter=null;
  private AddStringTask task=null;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setRetainInstance(true);

    if (model == null) {
      model=new ArrayList<String>();
      task=new AddStringTask();
      task.execute();
    }

    adapter=
        new ArrayAdapter<String>(getActivity(),
                                 android.R.layout.simple_list_item_1,
                                 model);
  }

  @Override
  public void onViewCreated(View v, Bundle savedInstanceState) {
    super.onViewCreated(v, savedInstanceState);

    getListView().setScrollbarFadingEnabled(false);
    setListAdapter(adapter);
  }

  @Override
  public void onDestroy() {
    if (task != null) {
      task.cancel(false);
    }

    super.onDestroy();
  }

  class AddStringTask extends AsyncTask<Void, String, Void> {
    @Override
    protected Void doInBackground(Void... unused) {
      for (String item : items) {
        if (isCancelled())
          break;

        publishProgress(item);
        SystemClock.sleep(400);
      }

      return(null);
    }

    @Override
    protected void onProgressUpdate(String... item) {
      if (!isCancelled()) {
        adapter.add(item[0]);
      }
    }

    @Override
    protected void onPostExecute(Void unused) {
      if (!isCancelled()) {
        Toast.makeText(getActivity(), R.string.done, Toast.LENGTH_SHORT)
             .show();
      }

      task=null;
    }
  }
}

(来自this sample project