-2

I know this question has been asked before and I've looked:

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

And I tried creating an interface to pass the value to, I also tried creating a method to assign the value through my onPostExecute and lastly I tried setting the variable directly like below, but nothing seems to work.

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");
        }
    }
}
Community
  • 1
  • 1
Sai Grr
  • 23
  • 5

1 Answers1

1

You can use interface. when Async task will reach postExecute than interface will callback class which implement interface. interface can carry result to class.

create a interface like below:

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

processFinish()'s argument should be according to data which you want to send to MainActivity.

implements it in MainActivity:

public class Home extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener, AsyncResponse

You need to pass interface to AsyncTask:

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

Declare a object of interface in AsyncTask Class. assign passed interface from MainActivity to this object:

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

Now in postExecute :

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

override interface method processFinish() in MainActivity:

@Override
public void processFinish(/*sent data from AsyncTask*/) {
    /*Use result here*/
}
Firoz Jaroli
  • 505
  • 5
  • 11