如何从onPostExecute传递值

时间:2017-03-27 01:10:32

标签: android android-asynctask

我知道之前已经问过这个问题而且我看过了:

How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

how do i send data back from onPostExecute in an AsyncTask?

how to pass the result of asynctask onpostexecute method into the parent activity android

我尝试创建一个接口来传递值,我也尝试创建一个方法来通过我的onPostExecute分配值,最后我尝试直接设置变量,但似乎没有任何效果。

public class ClassName extends AppCompatActivity {
    private Bitmap bit;

    public void methodName() {
        new RetrieveFavIcon().execute("https://www.google.com");
        // work with 'bit' value, but bit value is null, why?
    }

    class RetrieveFavIcon extends AsyncTask<String, Void, Bitmap> {
    public TaskListener delegate = null;

    protected Bitmap doInBackground(String... urls) {
        try {
            URL url = new URL(new URL(urls[0].trim()), "/favicon.ico");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            return myBitmap;
        } catch (IOException e) {
            Log.d("URL return", "failed");
            e.printStackTrace();
            return null;
        }
    }

    protected void onPostExecute(Bitmap bm) {
        if(bm != null) {
            bit = bm;
            Log.d("bitmap", "bitmap not null");
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您可以使用界面。当Async任务到达postExecute时,接口将回调类实现接口。界面可以将结果带到课堂上。

创建如下界面:

public interface AsyncResponse {
void processFinish(String output);
}

processFinish()的参数应该根据您要发送给MainActivity的数据。

在MainActivity中实现它:

public class Home extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener, AsyncResponse

您需要将接口传递给AsyncTask:

 new AsyncTask(this, MainActivity.this, news).execute();

在AsyncTask类中声明接口的对象。将MainActivity的传递接口分配给该对象:

public Cover(AsyncResponse delegate, Context context, ArrayList<NewsWrapper>      list) {
    this.delegate = delegate;
}

现在在postExecute:

delegate.processFinish(/*Your Data which you want to send in MainActivity*/);

在MainActivity中覆盖接口方法processFinish():

@Override
public void processFinish(/*sent data from AsyncTask*/) {
    /*Use result here*/
}