Reputation: 262
I'm trying to get the app to show an image from a URL, im fairly certain the issue is with the AsyncTask but I've returned to this code several times over the past week and I still cant see where I'm going wrong.
The Internet permission is set and I am getting no LogCat
ImageView eventImage2;
eventImage2 = (ImageView) findViewById(R.id.eventImage2);
new imageupdate().execute();
public class imageupdate extends AsyncTask<Bitmap, Void, Bitmap> {
@Override
protected Bitmap doInBackground(Bitmap... url) {
URL url1;
try {
url1 = new URL("http://masterzangetsu.eu/Apps/NowIGetYou/banner.png");
HttpURLConnection connection = (HttpURLConnection) url1.openConnection();
InputStream is = connection.getInputStream();
Bitmap img = BitmapFactory.decodeStream(is);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return img;
}
protected void onPreExecute(String result) {
}
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
eventImage2.setImageBitmap(result);
}
}
As far as I can tell the img variable defined with the
img = BitmapFactory.decodeStream(is);
isnt being linked to the variable being returned
return img;
Both variables result and img are coming back as null
Upvotes: 0
Views: 186
Reputation: 44571
Change this
Bitmap result = null;
InputStream is = connection.getInputStream();
Bitmap img = BitmapFactory.decodeStream(is);
img = result;
to
Bitmap img = null;
InputStream is = connection.getInputStream();
Bitmap img = BitmapFactory.decodeStream(is);
result = img;
and return result
in doInBackground()
. You have them switched around so 'img' will be null
no matter what happens.
Also, you can't use Toast
in doInBackground()
as this method isn't run on the UI
thread. You will need to make that a Log
or put your Toast
in onPostExecute()
or onProgressUpdate()
. These are the things I see. If you are still having problems then you need to be a little more clear on what specifically. You will need to debug and use breakpoints to see what isn't being returned that should be and pinpoint a little more what the problem is
AsyncTask - any UI
updates must be done in one of the other methods of AsyncTask
other than doInBackground()
or you can pass a value back to the Activity
to update the UI
there.
Upvotes: 1