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.
Related
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;
}
}
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;
}
}
what I have to do is to play videos on a single activity, the number of videos is undefined, could be from 1 to 8, a video in my case is an image sequence, where every image is downloaded from a cam on the internet using a fixed time interl.
Do a single video activity is not a problem, I can make it using ImageView and a AsyncTask, using many instances of this method when I try to make multiple videos activities does not work, only one of the video plays. I don't know exactly what it happens but I think it could be a cuncurrency related issue due to the UIThread.
Here the used AsyncTask code:
private class AsyncTask_LiveView extends AsyncTask<String, Integer, Void>
{
private String sImageMessage = "";
private final WeakReference<ImageView> imageViewReference;
private Bitmap bmImage = null;
private String url = "";
private String usr = "";
private String pwd = "";
private utils u = new utils();
public AsyncTask_LiveView(ImageView imageView, String Url, String Usr, String Pwd)
{
imageViewReference = new WeakReference<ImageView>(imageView);
url = Url;
usr = Usr;
pwd = Pwd;
}
// automatically done on worker thread (separate from UI thread)
#Override
protected Void doInBackground(final String... args)
{
while(!isCancelled())
{
if(isCancelled())
return null;
SystemClock.sleep(200);
Log.v("ImageDownload","test");
bmImage = u.DownloadBitmapFromUrl(url, usr, pwd);
publishProgress(0);
}
return null;
}
// can use UI thread here
#Override
public void onProgressUpdate(Integer... i)
{
Log.v("Image", "Setup Image");
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(bmImage);
}
}
}
}
I start the AsyncTasks in this way:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layoutliveviewdouble);
this.imgV1 = (ImageView ) findViewById(R.id.imageView1);
aTaskImgV1 = new AsyncTask_LiveView(imgV1,
URL1,
"",
"");
this.imgV2 = (ImageView ) findViewById(R.id.imageView2);
aTaskImgV2 = new AsyncTask_LiveView(imgV2,
URL2,
"root",
"jenimex123");
aTaskImgV1.execute();
aTaskImgV2.execute();
}
The DownloadBitmapFromUrl method is:
public Bitmap DownloadBitmapFromUrl(String imageURL, final String usr, final String pwd) { //this is the downloader method
try {
URL url = new URL(imageURL);
/* Open a connection to that URL. */
HttpURLConnection ucon = (HttpURLConnection) url.openConnection();
ucon.setRequestMethod("GET");
ucon.setDoOutput(true);
Authenticator.setDefault (new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication (usr, pwd.toCharArray());
}
});
ucon.connect();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(100000);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
Bitmap bmp = BitmapFactory.decodeByteArray(baf.toByteArray(), 0, baf.length());
return bmp;
} catch (Exception e) {
//Log.d("ImageManager", "Error: " + e);
return null;
}
}
Any Ideas?
Solution : (21/01/11)
The bounch of lines:
Authenticator.setDefault (new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication (usr, pwd.toCharArray());
}
});
were braking the mechanism. In fact only one credentials pair a could have been set globally, and the other download processes stucked in requesting using the wrong credentials.
The solution is:
String authString = usr + ":" + pwd;
byte[] authEncBytes = Base64.encode(authString.getBytes(), Base64.DEFAULT);
String authStringEnc = new String(authEncBytes);
ucon = (HttpURLConnection) url.openConnection();
if(_usr != "")
ucon.setRequestProperty("Authorization", "Basic " + authStringEnc);
Thanks to all.
I think yuo should use unique AsyncTask_LiveView for each ImageView.
Does this function support multiple threads?
bmImage = u.DownloadBitmapFromUrl(url, usr, pwd);
It looks like some of the methods you call in downloadBitmapFromUrl(..) method involve synchronization by some common object. Try adding some extra logging to each part of this method and see where each thread gets stuck. I would do it this way:
public Bitmap downloadBitmapFromUrl(String imageURL, final String usr, final String pwd) { //this is the downloader method
try {
...
Log.i(toString() + " in " + Thread.currentThread(), "is about to open connection...");
HttpURLConnection ucon = (HttpURLConnection) url.openConnection();
Log.i(toString() + " in " + Thread.currentThread(), "has opened connection");
...
and so on.
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. :)
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
}