Sam Borick Sam Borick - 1 year ago 165
Java Question

Android: cannot resolve method 'findViewById(int)' in AsyncTask

Following the tutorial here I have set up an app that should be able to download an image from a URL and place it into an ImageView. The only issue is that it cannot find findViewById because it is in the Activity class instead of the AsyncTask class. code is here:

package com.example.weather2;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;


public class ImageDownloader
extends AsyncTask<String, Integer, Bitmap> {
protected void onPreExecute(){
//Setup is done here
protected Bitmap doInBackground(String... params) {
//TODO Auto-generated method stub
URL url = new URL(params[0]);
HttpURLConnection httpCon =
if(httpCon.getResponseCode() != 200)
throw new Exception("Failed to connect");
InputStream is = httpCon.getInputStream();
return BitmapFactory.decodeStream(is);
}catch(Exception e){
Log.e("Image", "Failed to load image", e);
return null;
protected void onProgressUpdate(Integer... params){
//Update a progress bar here, or ignore it, I didn't do it
protected void onPostExecute(Bitmap img){
ImageView iv = (ImageView) findViewById(; //here is where the issue is
if(iv!=null && img!=null){
protected void onCancelled(){

When I comment out the lines with the issue, I don't get any errors, which makes me think it is working, but I can't tell because there is no image being posted.
Any help for solving this issue would be much appreciated.

Answer Source

findViewById is a method of Activity class.

And you have

 public class ImageDownloader
    extends AsyncTask<String, Integer, Bitmap>  // not a activity class

If you need the data back in activity you could use interface as a callback to the activity.

I would update ui in Activity itself. look @ blackbelts answer

How do I return a boolean from AsyncTask?


Make AsyncTask an inner class of Activity class and update ui in onPostExecute

Also you might find this blog by Alex Loockwood interesting

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download