Downloading Image using an Async Task and DIsplaying it in Gallery - android

I have to download some images and display them using Gallery. For the Image adapter I'm using for the gallery I have to start downloading the images in the get view method using an Async task. My problem is that i cant return the downloaded image view to the calling function. I cant download using the main thread due to networkonmainthread exception.
GalleryActivity
public class GalleryActivity extends Activity {
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.gallery);
((Gallery) findViewById(R.id.gallery)).setAdapter(new ImageAdapter(this));
}
Image Adapter
public class ImageAdapter extends BaseAdapter {
public View getView(int position, View convertView, ViewGroup parent) {
new galleryBackground().execute(Integer.toString(position));
ImageView i =null;
return i;
}
}
Gallery
public class galleryBackground extends AsyncTask<String, Integer, String> {
Bitmap bm;
public String[] myRemoteImages = { ....};
ImageView i = new ImageView(GalleryActivity.this);
#Override
protected String doInBackground(String... arg0) {
try {
URL aURL = new URL(myRemoteImages[Integer.parseInt(arg0[0])]);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = bitmapFactory.decodeStream(bis);
bis.close();
is.close();
}
#Override
protected void onPostExecute(String result) {
i.setImageBitmap(bm);
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
i.setLayoutParams(new Gallery.LayoutParams(150, 150));
// i have to return this Image view to the calling function
super.onPostExecute(result);
}

This library will solve your problem:
https://github.com/xtremelabs/xl-image_utils_lib-android
Pull the JAR from that repo into your project.
Instantiate an ImageLoader in your Activity/Fragment and pass it in to the adapter.
Call imageLoader.loadImage(imageView, url), and everything is done for you by that system.
The wiki can show you how to plug it in.

Change your Asynctask to
AsyncTask<String, Integer, Bitmap>
which will return you Bitmap and onPostExecute use the Bitmap
You are already passing the position so onPostExecute you can
yourlist.getItem(your position) and set the bitmap

Look at: Lazy load of images in ListView
It does not matter how to display data, your adapter will be the same.

you should return bm from doingBackground();
#Override
protected String doInBackground(String... arg0) {
try{
URL aURL = new URL(myRemoteImages[Integer.parseInt(arg0[0])]);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = bitmapFactory.decodeStream(bis);
bis.close();
is.close();
return bm;
}
}

Related

Call to AsyncTask from custom adapter

I have created a listview with a custom adapter. One of the fields is an image to show the avatar of each user. I must obtain those images from an url.
I have created a class that converts an image from URL into a Bitmap.
I think this should be done from an asyntask. The problem is that I do not know how to call this method from a custom adapter.
This is my class:
private class obtAvatar2 extends AsyncTask<Void , Void, Bitmap>{
Bitmap bm;
#Override
protected Bitmap doInBackground(Void... voids) {
try {
URL url = new URL("https://www.bellatores.cl/wp-content/uploads/2018/01/Avatar-Mujer.png");
URLConnection con = url.openConnection();
con.connect();
InputStream is = con.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
}catch (IOException e){
}
return bm;
}
}
This return a Bitmap.
Then from my custom adapter, i need to put that Bitmap in a ImageView
for example, i'm trying:
ImageView avatarView = (ImageView)view.findViewById(R.id.imageViewAvatarMensa);
avatarView.setImageBitmap(new obtAvatar2().execute());
But, it's wrong :(
any advice?
I suggest to you to either work with Glide or Picasso libaries, they are the most used image library on android application :
To import to you project with gradle :
PICASSO :
dependencies {
compile 'com.squareup.picasso:picasso:2.5.1'
}
GLIDE :
dependencies {
compile 'com.github.bumptech.glide:glide:3.5.2'
}
Usage :
PICASSO :
Picasso.with(myFragment)
.load(url)
.into(myImageView);
GLIDE :
Glide.with(myFragment)
.load(url)
.into(myImageView);
Hope this helps
You can use Glide or Picasso. As those are very helpful libraries for setting image in adapter (here views are reusable).
If you still want to use asynctask then check below:
In adapter each time scroll will lead to new network call, that can be avoided using saving bitmap object.
You are trying to get image by using below code:
ImageView avatarView = (ImageView)view.findViewById(R.id.imageViewAvatarMensa);
avatarView.setImageBitmap(new obtAvatar2().execute());
This will not work as:
new obtAvatar2().execute()
It will execute in background and return response in onPostExucute(). And result is:
avatarView.setImageBitmap(null)
If you want to use asytask then probably you need make your code like:
private class obtAvatar2 extends AsyncTask<Void, Void, Bitmap> {
Bitmap bm;
#Override
protected Bitmap doInBackground(Void... voids) {
try {
URL url = new URL("https://www.bellatores.cl/wp-content/uploads/2018/01/Avatar-Mujer.png");
URLConnection con = url.openConnection();
con.connect();
InputStream is = con.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
}
return bm;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
ImageView avatarView = (ImageView)view.findViewById(R.id.imageViewAvatarMensa);
avatarView.setImageBitmap(bitmap);
//set bitmap to imageview and save in local list, so in future no need to download
}
}
You can pass reference of ImageView in constructor.
First of all you should add obtAvatar2 async task in your custom adapter.
I hope you are using ViewHolder in your customadapter, then in you getView(), before assigning value to your Imageview, call the async task. For example:
public static class ViewHolder {
public ImageView display_adImage;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
try {
if (convertView == null) {
vi = inflater.inflate(R.layout.test_layout, null);
holder = new ViewHolder();
holder.display_adImage = vi.findViewById(R.id.IvAdImage);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
...
Bitmap b = new GetImageTask().execute().get();
holder.display_adImage.setImageBitmap(b);
}
}
private class obtAvatar2 extends AsyncTask<Void , Void, Bitmap>{
Bitmap bm;
#Override
protected Bitmap doInBackground(Void... voids) {
try {
URL url = new URL("https://www.bellatores.cl/wp-content/uploads/2018/01/Avatar-Mujer.png");
URLConnection con = url.openConnection();
con.connect();
InputStream is = con.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
}catch (IOException e){
}
return bm;
}
}

Load images in listview only when they are about to display

I am working on making a music player and what i have done so far is that I created a song list in listview with their thumbnail images using metadata files.
Now when i scroll my list it lags, that might be because of the image loading.
I referred to Google Play Music App and what they have done is that they fetch album art at the time of scrolling so scrolling is smooth.
Is there any way to implement that kind of functionality?
You have to use lazy loading of images, so images will be downloaded in background.
public class DownloadImage extends AsyncTask<ImageView, Void, Bitmap> {
ImageView imageView = null;
#Override
protected Bitmap doInBackground(ImageView... imageViews) {
this.imageView = imageViews[0];
return download_Image((String) imageView.getTag());
}
#Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
private Bitmap download_Image(String url) {
try {
URL ulrn = new URL(url);
HttpURLConnection con = (HttpURLConnection) ulrn.openConnection();
InputStream iS = con.getInputStream();
Bitmap bmp = BitmapFactory.decodeStream(iS);
return bmp;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
}
Make a call to this class in your adapter getview
imgThumbnail.setTag(<your image url>);
new DownloadImage().execute(imgThumbnail);

android.os.NetworkOnMainThreadException in AsyncTask's doInBackground

Why do I get in an AsyncTask which should a android.os.NetworkOnMainThreadException? I thought that an AsyncTask is the solution to that problem. The exxeption is on line 7.
private class ImageDownloadTask extends AsyncTask<String, Integer, byte[]> {
#Override
protected byte[] doInBackground(String... params) {
try {
URL url = new URL(params[0]);
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
} catch (IOException ex) {
return new byte[0];
}
}
}
I want to use it for downloading a picture.
public byte[] getProfilePicture(Context context, String id) {
String url = context.getString(R.string.facebook_picture_url_large, id);
ImageDownloadTask task = new ImageDownloadTask();
return task.doInBackground(url);
}
By calling doInBackground() directly, you are not actually using the AsyncTask functionality. Instead, you should call execute() and then use the results by overriding the AsyncTask's onPostExecute() method as explained in the Usage section of that same page.
Best way to download an image and attach it to a ImageView is passing the ImageView as the parameter in your async task and set the URL as a tag of the image view then after downloading the task in the OnPostExecute() set the image to the ImageView look at this example :
public class DownloadImagesTask extends AsyncTask<ImageView, Void, Bitmap> {
ImageView imageView = null;
#Override
protected Bitmap doInBackground(ImageView... imageViews) {
this.imageView = imageViews[0];
return download_Image((String)imageView.getTag());
}
#Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
private Bitmap download_Image(String url) {
...
}
And the Usage will be like this
ImageView mChart = (ImageView) findViewById(R.id.imageview);
String URL = "http://www...someImageUrl ...";
mChart.setTag(URL);
new DownloadImageTask.execute(mChart);
The image will be attached automatically when done, for more memory optimization you could use WeakReference.
Good Luck.

error occured while executing doInBackground()

i want to donload image from server asynchronously but when i run it force close....and gives msg on log cat... An error occured while executing doInBackground()...whats the problem pls help me..pls pls
public class artspacedetailShowingNow extends Activity implements OnClickListener {
private int imageCounter = 0;
private ProgressDialog bar;
private ImageView imageLoader;
private String[] imageList = {"http://www.artealdiaonline.com/var/artealdia_com/storage/images/argentina/directorio/galerias/ruth_benzacar/artistas/martin_di_girolamo._diosas/198915-1-esl-AR/MARTIN_DI_GIROLAMO._Diosas.jpg","http://www.artealdiaonline.com/var/artealdia_com/storage/images/argentina/directorio/galerias/ruth_benzacar/artistas/jorge_macchi._la_espera/198929-1-esl-AR/JORGE_MACCHI._La_espera.jpg","http://www.artealdiaonline.com/var/artealdia_com/storage/images/argentina/directorio/galerias/ruth_benzacar/artistas/leon_ferrari._hongo_nuclear/198950-1-esl-AR/LEON_FERRARI._Hongo_Nuclear.jpg","http://www.artealdiaonline.com/var/artealdia_com/storage/images/argentina/directorio/galerias/ruth_benzacar/artistas/martin_sastre._fiebre/198922-1-esl-AR/MARTIN_SASTRE._Fiebre.jpg"};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.showingnow);
imageLoader = (ImageView) findViewById(R.id.imageLoader);
//imageLoader.setImageResource(image1);
Button next = (Button) findViewById(R.id.next);
Button back = (Button) findViewById(R.id.back);
next.setOnClickListener(this);
back.setOnClickListener(this);
back.setEnabled(false);
new ImageDownload().execute(imageList[imageCounter]);
}
#Override
public void onClick(View v)
{
String imagePath = null;
// imagePath = imageList[imageCounter];
}
new ImageDownload().execute(imagePath);
}
private void loadImage(String imagePath)
{
try {
/* Open a new URL and get the InputStream to load data from it. */
URL aURL = new URL(imagePath);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
/* Buffered is always good for a performance plus. */
BufferedInputStream bis = new BufferedInputStream(is);
/* Decode url-data to a bitmap. */
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
imageLoader.setImageBitmap(bm);
imageLoader.setImageBitmap(bm);
} catch (IOException e)
{
Log.e("DEBUGTAG", "Remote Image Exception", e);
}
}
private class ImageDownload extends AsyncTask<String , Void, Void>
{
#Override
protected Void doInBackground(String... params) {
loadImage(params[0]);
return null;
}
#Override
protected void onPostExecute(Void result) {
}
#Override
protected void onPreExecute() {
}
}
}
try this
private class ImageDownload extends AsyncTask<String , Void, Void>
{
Bitmap imBitmap;
#Override
protected Void doInBackground(String... params) {
try {
/* Open a new URL and get the InputStream to load data from it. */
URL aURL = new URL(params[0]);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
/* Buffered is always good for a performance plus. */
BufferedInputStream bis = new BufferedInputStream(is);
/* Decode url-data to a bitmap. */
Bitmap bm = BitmapFactory.decodeStream(bis);
imBitmap=bm;
bis.close();
is.close();
} catch (IOException e)
{
Log.e("DEBUGTAG", "Remote Image Exception", e);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
imageLoader.setImageBitmap(imBitmap);
imageLoader.setImageBitmap(imBitmap);
}
#Override
protected void onPreExecute() {
}
}
you cant use imageLoader.setImageBitmap(imBitmap); in doinBackground.
You look like you are accessing your ImageView from within doInBackground. That is not allowed.
Manipulating UI elements can only be done from the UI thread.
If you read AsyncTask, you'll see that doInBackground is executed in another thread, while onPreExecute, onProgressUpdate and onPostExecute is executed in the UI thread.
Handle UI elements in the methods I mentioned above, or post a runnable like TofferJ suggested.
You need to use the UI Thread when doing things that affects the UI. Depending on where the background thread is started from either use:
runOnUiThread(new Runnable() {
#Override
public void run() {
imageLoader.setImageBitmap(bm);
imageLoader.setImageBitmap(bm);
}
});
or
imageLoader.post(new Runnable() {
#Override
public void run() {
imageLoader.setImageBitmap(bm);
imageLoader.setImageBitmap(bm);
}
});
Both of the snippets above will make sure that the correct thread is used to update your UI. Make sure to always do this when modifying the UI (setting images, updating texts etc) from another tread and you will stay out of trouble. :)

Android : Loading an image from the Web with Asynctask

How do I replace the following lines of code with an Asynctask ?
How do you "get back" the Bitmap from the Asynctask ? Thank you.
ImageView mChart = (ImageView) findViewById(R.id.Chart);
String URL = "http://www...anything ...";
mChart.setImageBitmap(download_Image(URL));
public static Bitmap download_Image(String url) {
//---------------------------------------------------
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e("Hub","Error getting the image from server : " + e.getMessage().toString());
}
return bm;
//---------------------------------------------------
}
I thought about something like this :
replace :
mChart.setImageBitmap(download_Image(graph_URL));
by something like :
mChart.setImageBitmap(new DownloadImagesTask().execute(graph_URL));
and
public class DownloadImagesTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) {
return download_Image(urls[0]);
}
#Override
protected void onPostExecute(Bitmap result) {
mChart.setImageBitmap(result); // how do I pass a reference to mChart here ?
}
private Bitmap download_Image(String url) {
//---------------------------------------------------
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e("Hub","Error getting the image from server : " + e.getMessage().toString());
}
return bm;
//---------------------------------------------------
}
}
but How do I pass a reference to mChart in onPostExecute(Bitmap result) ???
Do I need to pass it with the URL in some way ?
I would like to replace all my lines of code :
mChart1.setImageBitmap(download_Image(URL_1));
mChart2.setImageBitmap(download_Image(URL_2));
with something similar ... but in Asynctask way !
mChart1.setImageBitmap(new DownloadImagesTask().execute(graph_URL_1));
mChart2.setImageBitmap(new DownloadImagesTask().execute(graph_URL_2));
Is there an easy solution for this ?
Do I get something wrong here ?
If there is no good reason to download the image yourself then I would recommend to use Picasso.
Picasso saves you all the problems with downloading, setting and caching images.
The whole code needed for a simple example is:
Picasso.with(context).load(url).into(imageView);
If you really want to do everything yourself use my older answer below.
If the image is not that big you can just use an anonymous class for the async task.
This would like this:
ImageView mChart = (ImageView) findViewById(R.id.imageview);
String URL = "http://www...anything ...";
mChart.setTag(URL);
new DownloadImageTask.execute(mChart);
The Task class:
public class DownloadImagesTask extends AsyncTask<ImageView, Void, Bitmap> {
ImageView imageView = null;
#Override
protected Bitmap doInBackground(ImageView... imageViews) {
this.imageView = imageViews[0];
return download_Image((String)imageView.getTag());
}
#Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
private Bitmap download_Image(String url) {
...
}
Hiding the URL in the tag is a bit tricky but it looks nicer in the calling class if you have a lot of imageviews that you want to fill this way. It also helps if you are using the ImageView inside a ListView and you want to know if the ImageView was recycled during the download of the image.
I wrote if you Image is not that big because this will result in the task having a implicit pointer to the underlying activity causing the garbage collector to hold the whole activity in memory until the task is finished. If the user moves to another screen of your app while the bitmap is downloading the memory can't be freed and it may make your app and the whole system slower.
Try this code:
ImageView myFirstImage = (ImageView) findViewById(R.id.myFirstImage);
ImageView mySecondImage = (ImageView) findViewById(R.id.mySecondImage);
ImageView myThirdImage = (ImageView) findViewById(R.id.myThirdImage);
String URL1 = "http://www.google.com/logos/2013/estonia_independence_day_2013-1057005.3-hp.jpg";
String URL2 = "http://www.google.com/logos/2013/park_su-geuns_birthday-1055005-hp.jpg";
String URL3 = "http://www.google.com/logos/2013/anne_cath_vestlys_93rd_birthday-1035005-hp.jpg";
myFirstImage.setTag(URL1);
mySecondImage.setTag(URL2);
myThirdImage.setTag(URL3);
new DownloadImageTask.execute(myFirstImage);
new DownloadImageTask.execute(mySecondImage);
new DownloadImageTask.execute(myThirdImage);
public class DownloadImagesTask extends AsyncTask<ImageView, Void, Bitmap> {
ImageView imageView = null;
#Override
protected Bitmap doInBackground(ImageView... imageViews) {
this.imageView = imageViews[0];
return download_Image((String)imageView.getTag());
}
#Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
private Bitmap download_Image(String url) {
Bitmap bmp =null;
try{
URL ulrn = new URL(url);
HttpURLConnection con = (HttpURLConnection)ulrn.openConnection();
InputStream is = con.getInputStream();
bmp = BitmapFactory.decodeStream(is);
if (null != bmp)
return bmp;
}catch(Exception e){}
return bmp;
}
}
you can create a class say..BkgProcess which contains an inner class that extends AsyncTask. while instantiating BkgProcess pass the context of your Activity class in BkgProcess constructor. for eg:
public class BkgProcess {
String path;
Context _context;
public Download(Downloader downloader, String path2){
this.path = path2;
_context = downloader;
}
public void callProgressDialog(){
new BkgProcess().execute((Void)null);
}
class Downloads extends AsyncTask<Void, Void, Boolean> {
private ProgressDialog dialog = new ProgressDialog(_context);
protected void onPreExecute(){
dialog.setMessage("Downloading image..");
dialog.show();
}
protected void onPostExecute(Boolean success) {
dialog.dismiss();
if(success)
Toast.makeText(_context, "Download complete", Toast.LENGTH_SHORT).show();
}
#Override
protected Boolean doInBackground(Void... params) {
return(startDownload(path));
}
public boolean startDownload(String img_url) {
// download img..
return true;
}
}
}
from your activity class..
BkgProcess dwn = new BkgProcess (Your_Activity_class.this, img_path);
dwn.callProgressDialog();
This will get you images of any size...
if you dont want the progress dialog just comment the codes in onPreExecute();
for(int i = 0 ; i < no_of_files ; i++ )
new FetchFilesTask().execute(image_url[i]);
private class FetchFilesTask extends AsyncTask<String, Void, Bitmap> {
private ProgressDialog dialog = new ProgressDialog(FileExplorer.this);
Bitmap bitmap[];
protected void onPreExecute(){
dialog.setMessage("fetching image from the server");
dialog.show();
}
protected Bitmap doInBackground(String... args) {
bitmap = getBitmapImageFromServer();
return bitmap;
}
protected void onPostExecute(Bitmap m_bitmap) {
dialog.dismiss();
if(m_bitmap != null)
//store the images in an array or do something else with all the images.
}
}
public Bitmap getBitmapImageFromServer(){
// fetch image form the url using the URL and URLConnection class
}

Categories

Resources