Downloading many pictures from a server in android - android

I don't know how to get several images from a URL.
Those images come in as Bitmap; I need to convert them to drawable, but I don't know how.
Drawable icon = getResources().getDrawable(R.drawable.icon);
Am I doing it correctly calling the url(images), or is there a better way to do that?
This is the asynctask where I get the images
private class BajarImagenTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) {
return BajarImagen(urls[0]);
}
protected void onPostExecute(Bitmap result){
Drawable icon = getResources().getDrawable(R.drawable.icon);
point.setImage(d);
}
}
This the connection:
private Bitmap BajarImagen (String URL)
{
Bitmap bitmap = null;
InputStream in = null;
try {
in=OpenHttpConnection(URL);
bitmap=BitmapFactory.decodeStream(in);
in.close();
}
catch (IOException e1) {
}
return bitmap;
}
Here is the method with a "FOR" inside to get several URLs and calling many times the asynctask
public void datosDesdeElXML(String[][] datos) {
for(int i = 0; i < moteles.length;i++){
String motel[] = moteles[i];
double lat = Double.valueOf(motel[0].trim());
double lng = Double.valueOf(motel[1].trim());
String name = motel[2].trim();
String address = motel[3].trim();
**String urldefotoglobo = motel[4].trim();**
// here i get url from server in a xml format
String aidis = motel[5].trim();
**new BajarImagenTask().execute(urldefotoglobo);**
// Here i call the asynctask
}
}

Related

Running multiple async tasks returns task to wrong handler

I create several picture objects that each download their own image. But frequently, the same image shows up for several (or all) of the objects.
public class Picture {
private String userID;
private String fileName;
private String baseURI;
private Bitmap img;
public Picture () {
this.userID = "";
this.fileName = "";
this.baseURI = "";
}
/**
* Retrieves the UUID of the User
*
* #return - String
*/
public String getUserID() {return userID;}
public void setUserID(String _userID) {userID = _userID;}
/**
* Retrieves the Filename of the Picture
*
* #return - String
*/
public String getFileName() {return fileName;}
public void setFileName(String fileName) {
this.fileName = fileName;
//Don't retrieve a file from the server if the filename is empty or it is a placeholder
if (fileName != "" && fileName != "NoNewPicure" && fileName != "NewPicture") {
new RetrieveImageTask(getFileNameURI(), img) {
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
setPreview(result);
}
}.execute();
}
}
private URI getFileNameURI() {
return URI.create(baseURI.concat(fileName));
}
private void setBaseURI(String baseURI) {
this.baseURI = baseURI;
}
/**
* Accesors for preview image
* #return - Image
*/
#Bindable
public Bitmap getPreview() {return img;}
public void setPreview(Bitmap img) {
this.img = img;
notifyPropertyChanged(BR.preview);
}
private static class RetrieveImageTask extends AsyncTask<URI, Void, Bitmap> {
static URI uriString;
static Bitmap myBitmap;
private Exception exception;
RetrieveImageTask(URI uri, Bitmap bitmap) {
uriString = uri;
this.myBitmap = bitmap;
}
protected Bitmap doInBackground(URI... src) {
try {
Log.e("src",uriString.toString());
URL url = new URL(uriString.toString());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
Log.e("Bitmap","returned");
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
Log.e("Exception",e.getMessage());
return null;
}
}
protected void onPostExecute(Bitmap result) {
//Do nothing
}
}
}
In code the images are called from a for loop:
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Picture pic = new Picture();
pic.fromJSON(json_data);
result.add(pic);
}
It appears as though when the Async task returns, several (or all) of the handlers fire. Any ideas on how to fix this? I've tried adding in this:
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
URI thisURI = getFileNameURI();
if (uriString.equals(thisURI)) {
setPreview(result);
}
}
But then only one Picture object actually gets an image.
The answer was quite simple after hearing Another brick in the wall. You can't have any pudding if you don't eat your meat! I can't have my bitmap if the file hasn't downloaded. But I CAN put my bowl where the pudding is going to be so that after I eat my meat, I can eat my pudding. I changed my AsynTask like such:
private class RetrieveImageTask extends AsyncTask<URI, Void, Boolean> {
public URI uriString;
public Picture pic;
RetrieveImageTask(URI uri) {
uriString = uri;
}
protected Boolean doInBackground(URI... src) {
try {
Log.e("src",uriString.toString());
URL url = new URL(uriString.toString());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
Log.e("Bitmap","returned");
pic.setPreview(bitmap);
return true;
} catch (IOException e) {
e.printStackTrace();
Log.e("Exception",e.getMessage());
return null;
}
}
protected void onPostExecute() {
//Do nothing
}
}
Note the public variables in the class wrapper. Now when I call my task (code changed from above):
RetrieveImageTask task = new RetrieveImageTask(getFileNameURI());
task.pic = this;
task.execute();
my bowl will be where the pudding is going to be. IE. I put the calling object as a variable in the private AsyncTask class which populates what I need when it is finished running. :D My bowl of pudding is full after I eat my meat!!!!

Android Get Image.png from JSON

I have a JSON that contains strings and image.png objects.
I can get the string the usual way, but how do I get the Images? All tutorials I found use jsons with specific image URLs instead of the png. Look at the JSON and you will understand it:
{
"draw": 0,
"recordsTotal": 8,
"recordsFiltered": 8,
"data": [{
"start_date": "2017-03-08 17:45:00",
"competition_name": "Primera Divisi\u00f3n",
"competition_logo": "laliga.png",
"home_team": "Deportivo La Coru\u00f1a",
"home_team_logo": "deportivo-la-coruna-2018.png",
"home_team_slug": "deportivo-la-coruna-640",
"event_status": "",
"away_team": "Real Betis",
"away_team_logo": "real-betis-2025.png",
"away_team_slug": "real-betis-639",
"event_id": "3404",
"game_minute": ""
},
My code has the usual format to get json objects from array.
try {
JSONObject jsonObject = new JSONObject(result);
if (jsonObject.length() > 0) {
JSONArray jsonArray = jsonObject.getJSONArray("data");
if (jsonArray.length() > 0){
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonPart = jsonArray.getJSONObject(i);
String start_date= jsonPart.getString("start_date");
I want the home_team_logo and away_team_logo images to put on a ImageView.
If you have the path in which those images are, you can just download the images in asynchronous manner, like so:
import java.lang.ref.WeakReference;
public static class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
public ImageDownloaderTask(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
#Override
protected Bitmap doInBackground(String... params) {
return downloadBitmap(params[0], params[1]);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
ImageView imageView = imageViewReference.get();
if (imageView != null) {
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
Drawable placeholder = imageView.getContext().getResources().getDrawable(R.drawable.potch_app_logo_icon);
imageView.setImageDrawable(placeholder);
}
}
}
}
private static Bitmap downloadBitmap(String url, String localPath) {
HttpURLConnection urlConnection = null;
try {
URL uri = new URL(url);
urlConnection = (HttpURLConnection) uri.openConnection();
int statusCode = urlConnection.getResponseCode();
if (statusCode != 200) {
return null;
}
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(localPath));
return bitmap;
}
} catch (Exception e) {
e.printStackTrace();
Log.w("ImageDownloader", "Error downloading image from " + url);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
Then in your code:
String away_tema_logo_image_name = jsonPart.getString("away_team_logo");
new ImageDownloaderTask(yourImageView).execute(yourUrl, yourLocalPath);
This will save the image to local storage on device, so you need
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
As far as you write above, you can get the PNG files name just like this:
String start_date= jsonPart.getString("home_team_logo");
May be the problem is you want show the picture in the view, I think first you want add the URL prefix where from you load the JSON result, and then pass the URL to Glide/ImageLoader like framework to show it on the imageView.

Display Image in android Imageview using Asynctask

I have an image being sent to me through a JSON string. I want to convert that string into an image in my android app and then display that image in my imageview.I have a problem, I am using Asynctask and this is my code in the doInBackground method:
protected Boolean doInBackground(final String... args){
JsonParser jsonParser = new JsonParser();
JSONArray json = jsonParser.getJSONFromUrl(url);
if(json!=null){
for (int i = 0; i < json.length(); i++){
try{
JSONObject c = json.getJSONObject(i);
String displayImageFromUrl = c.getString(imageUrl);
String clearUrl = displayImageFromUrl.substring(displayImageFromUrl.indexOf(",")+1);
byte[] decodingString = Base64.decode(clearUrl, Base64.DEFAULT);
bitmap = BitmapFactory.decodeByteArray(decodingString, 0 , decodingString.length);
String showCreatedDate = c.getString(createdDate);
String showArticleTitle = c.getString(articleTitle);
HashMap<String, String> map = new HashMap<String, String>();
map.put(createdDate, showCreatedDate);
map.put(articleTitle, showArticleTitle);
jsonlist.add(map);
}catch (Exception e){
e.printStackTrace();
}
}
}else{
}
return null;
}
and this is my code in the onPostExecute() method:
protected void onPostExecute(final Boolean success){
if (dialog.isShowing()) {
dialog.dismiss();
}
Log.d("image please",bitmap.toString());
ImageView showImage = (ImageView) findViewById(R.id.imageShow);
showImage.setImageBitmap(bitmap);
ListAdapter adapter = new SimpleAdapter(context, jsonlist, R.layout.activity_news,
new String[] {createdDate, articleTitle},
new int[] { R.id.createDate, R.id.articleTitle});
setListAdapter(adapter);
lv = getListView();
}
Unfortunately nothings shows up in my logcat. Can you help me?
What do I miss??
Here is a pseudocode. If you use it in project it should be working.
//my image (android logo)
private String base64 = "iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAACgUlEQVRIiZ2Wv4vUQBTHP2/ZBFlEFrGS44iniLCggggWh4yVoIX4F9gIFtYiFgqWNgqChfoXHBYWXuWJF05rwe0UMWE5RI7lEJUguSPPYvJjkk32xAcbvjPz8n3v++ZlZqHDYuMRG/9+bPxBt4+/LzLevdj4XS5I54olOK/oCSAUWFY4al/RSJANRY0gX4IwfdvF0Z8XQCEW5AnwCBiInUMQFE1AJqAX53F0KoiNfxp4CQSNoA4SgInA1SBMP7Tx9NrJvSHoCmgPeAhk6lCLVTEWeCZwGHQlMt7BfwoQGR+FWyDHgc/Ac9BUZsTqWNEXQApyDLjdttkzJYqNPwT9CLKojkOBCyXFfjh4U5BTQZhuz1UAGoAsdJBgt1jQolAlZkHRpSbbTBcpMhW4WY4cDQXO1WR1LBnwvcknAJHxLwncAcbAuqJP5yuwtM0n6A2QC6AnQR4cCdPVfv7yNYVlgXOgnwSpdcRsL0utp6okZAG4rogPfANWiz3o5eJn9kQ6cJvlgQqOfvkAeq78lo8Jt4/2Kl7u06sFqLJzO74tf2nxajZCtdaz02XOGZBVCtyjwWItc9QWLM7YCVCX1kZWS6LTtEZtrShRVgivcDlu4HklshVwAxQ7Ps1zSID0/0tECiT5eOoquAv6DmSi6AHq3VDDe9gmcEWQRdDXzRoAEBt/CXgFHAKGQHFE/gF+5ngA7M9xprAt6BTkchCmX12+mQ8rdzgLjBQ2nBK9sXM6UvSxU5aJwAg40ySHjiszCNMESCLjJc5pkwThzhQgMt6vwlftXbEVhDttVPPvZGDX6ZXdEtmTs/QJwrSToPXKrEzWgB/5b91ZeA+6BfwG7fxHAfAXfJIQh9RXB18AAAAASUVORK5CYII=";
//somewhere in code
imageView = (ImageView) view.findViewById(R.id.imageView);//layout params are wrap and wrap
//weak reference is for safe using imageView when app i.e will exit and task will still be running
weakReferenceImageView = new WeakReference<ImageView>(imageView);
new AsyncTask<Void, Void, Bitmap>() {
#Override
protected Bitmap doInBackground(Void... params) {
byte[] encode = Base64.decode(base64.getBytes(), 0);
Bitmap bitmap = BitmapFactory.decodeByteArray(encode, 0, encode.length);
return bitmap;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if (bitmap != null) {
if (weakReferenceImageView != null) {
ImageView weak = weakReferenceImageView.get();
if (weak != null) {
weak.setImageBitmap(bitmap);
}
}
}
}
}.execute();
If decoding is wrong, returned bitmap will be null.
Please try with my image (it is very small) if it works. If it works it means something is wrong with your based64 image.
Fixed example, added weakReference as a good sample of coding.
ImageView image = (ImageView) findViewById(R.id.image);
String image_url = "http://api.androidhive.info/images/sample.jpg";
ImageLoader imgLoader = new ImageLoader(getApplicationContext());
imgLoader.DisplayImage(image_url, loader, image);
Use the library found on the url.
http://www.androidhive.info/2012/07/android-loading-image-from-url-http/
ImageLoader.java, FileCache.java, and Utils.java
Just Use Picasso
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
Couldn't be easier than this.

How can i get a value returned by doInBackground() from AsyncTask class

I need to use a bitmap image as Marker.icon .
i have 2 AsyncTask class , MyTask and BitmapTask , the first one retrieve a JSONArray with value { double,double,string,string = url of my bitmap icon } and the second one use the last string of JSONArray (in other words the url) as parameter the get the bitmap icon .
Trying to get it this way failed :
MyTask class
public class MyTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
// updateDisplay("Starting task");
//tasks.add(this);
}
#Override
protected String doInBackground(String... params) {
String content = HttpManager.getData(params[0]);
return content;
}
#Override
protected void onPostExecute(String result) {
double JsonLat = 0.0 ;
double Jsonlong = 0.0 ;
String JsonName = "" ;
String JsonIconurl = "" ;
Bitmap JsonIcon = null;
try {
JSONArray cast = new JSONArray(result);
BitmapTask icontask = new BitmapTask();
for (int i=0; i<cast.length(); i++) {
JSONObject Marker = new JSONObject(cast.get(i).toString());
stringJsonLat = Marker.getString("latitude");
stringJsonLng = Marker.getString("longitude");
Jsonlong = Double.parseDouble(stringJsonLng);
JsonLat = Double.parseDouble(stringJsonLat);
JsonName = Marker.get("title").toString();
JsonIconurl = Marker.get("icone").toString();
icontask.execute(JsonIconurl);
JsonIcon = icontask.doInBackground();
if (InArea(JsonLat,Jsonlong)) {
mMap.addMarker(new MarkerOptions().position(new LatLng(JsonLat,Jsonlong)).title(JsonName).icon(BitmapDescriptorFactory.fromBitmap(JsonIcon)));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected void onProgressUpdate(String... values) {
// updateDisplay(values[0]);
}
}
BitmapTask class
public class BitmapTask extends AsyncTask<String, Void, Bitmap>{
#Override
protected Bitmap doInBackground(String... params) {
Bitmap bmImg = null;
try {
URL url = new URL(params[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
}
catch (IOException e)
{
e.printStackTrace();
bmImg = null;
}
return bmImg;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
// TODO: do what you need with resulting bitmap - add marker to map
}
};
I suggest to make all the download operations in one AsyncTask (downloading the JSON string and the icon).
You need to have a class to wrap the download results:
Wrapper class:
private class JSONMarkerObject {
double lat = 0.0;
double lng = 0.0;
String name = "";
String iconURL = "";
Bitmap iconBitmap = null;
}
Helper functions:
private ArrayList<JSONMarkerObject> parseJSON(String content) {
ArrayList<JSONMarkerObject> markers = new ArrayList<MainActivity.JSONMarkerObject>();
try {
JSONArray array = new JSONArray(content);
for (int i = 0; i < array.length(); i++) {
JSONObject Marker = array.getJSONObject(i);
JSONMarkerObject obj = new JSONMarkerObject();
obj.lat = Double.parseDouble(Marker.getString("latitude"));
obj.lng = Double.parseDouble(Marker.getString("longitude"));
obj.name = Marker.getString("title");
obj.iconURL = Marker.getString("icone");
obj.iconBitmap = downloadIcon(obj.iconURL);
markers.add(obj);
}
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return markers;
}
private Bitmap downloadIcon(String iconURL) {
Bitmap bmImg = null;
try {
URL url = new URL(iconURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
} catch (IOException e) {
e.printStackTrace();
bmImg = null;
}
return bmImg;
}
Download task:
public class MyTask extends AsyncTask<String, String, ArrayList<JSONMarkerObject>> {
#Override
protected void onPreExecute() {
}
#Override
protected ArrayList<JSONMarkerObject> doInBackground(String... params) {
String content = HttpManager.getData(params[0]);
ArrayList<JSONMarkerObject> markers = parseJSON(content);
return markers;
}
#Override
protected void onPostExecute(ArrayList<JSONMarkerObject> result) {
try {
for (int i = 0; i < result.size(); i++) {
JSONMarkerObject obj = result.get(i);
if (InArea(obj.lat, obj.lng)) {
mMap.addMarker(new MarkerOptions().position(new LatLng(obj.lat, obj.lng)).title(obj.name)
.icon(BitmapDescriptorFactory.fromBitmap(obj.iconBitmap)));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected void onProgressUpdate(String... values) {
// updateDisplay(values[0]);
}
}
I see no need for downloading the text first in a single task, and then downloading the icons in another single task, because the markers will appear on the map when the icons are downloaded, so there is no problem in downloading everything in one shot.
Edit
The simplest way to add an info window is to set the title() and
snippet() methods of the corresponding marker.
mMap.addMarker(new MarkerOptions()
.position(new LatLng(obj.lat, obj.lng))
.title(obj.name)
.icon(BitmapDescriptorFactory.fromBitmap(obj.iconBitmap)))
.setTitle(obj.name)
.snippet(obj.name);
Run your MyTask AsyncTask, and in onPostExecute of MyTask class run your BitmapTask AsyncTask.
MyTask's onPostExecute
#Override
protected void onPostExecute(String result) {
new BitmapTask().execute(params); //params if any
}
Inside your BitmapTask class, include the following:
public interface BitmapTaskListener{
public void onResult(Bitmap bmImg);
}
private BitmapTaskListener bitmapListener;
public void setBitmapListener (BitmapTaskListener listener){
bitmapListener = listener;
}
Of course you don't have to use the same names. Your onPostExecute should be:
#Override
protected void onPostExecute(Bitmap result) {
if (bitmapListener!=null)
bitmapListener.onResult(result);
}
And finally, you should use the setBitmapListener to set the listener. You will have to implement the method onResult where you will do whatever it is you want with the Bitmap you got.
Edit: Actually, you are calling the BitmapTask from within MyTask. You can either propagate the listener or I would suggest getting the result from the first task in your UI and initialize from there the second task.
Also, don't this: JsonIcon = icontask.doInBackground();. doInBackground is called internally, after onPreExecute. You should start the task simply by task.execute(params)

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