Coas Mckey
Coas Mckey

Reputation: 709

How to download the series of Images from Server

I have my own Server and I want to download the images one by one automatically. Right now what I have tried is downloading and saving the image on the device and that is working 100 percent perfectly. But that is working for single image here is the good link on it. But It is working but downloading only one image or you can say one image for one link .

The Idea came into my mind and that is to make the string array of the Url and then apply the for loop and then it would download and execute that much Asynctask.

But this is not a good practice, as it would launch too many async task.

What I want

  1. I want that if I have 10 Url , then it should download images from first url to last url but one by one , I mean when First Image has been downloaded then it should start second image after saving the first Image on device.

  2. It should Show Progress bar progress collectively for all images. and should Update the progress let say there are 10 images then it should show 10 percent completed when first images has been successfully downloaded and it should show 20 percent if 2 images has been downloaded.

Please give me source code or anything which can Help me. Thanks.

Upvotes: 0

Views: 3857

Answers (2)

LilaQ
LilaQ

Reputation: 350

If you have single download already up an running, what is the problem with chaining downloads for several images then? If you don't care about precise progress (atleast that is what I'm understanding here), you can simply do this by a for-loop.

Pseudo-Code:

String[] urlStack = {"http://www.myimage.com/1.jpg", "http://www.myimage.com/2.jpg", "http://www.myimage.com/3.jpg"};
for(int i = 0; i < urlStack.length; i++)
{
   yourAlreadyDoneDownloadProcedure(updateProgressCallback);
}

... updateProgressCallback method of course gets called within your download procedure, once your download is done. ...

private void updateProgressFallback()
{
   progressBarText += 100 / urlStack.length;
}

This is just to demonstrate how you could / should approach this.


Edit to your first comment:

In this case you should use FutureTask.

FutureTask objects can wait for completion, without any while()...sleep

e.g.

for(int i = 0; i < urlStack.length; i++)
{
   // fTask is an array of your download procedure objects

   // get() will wait until the Task is done, no manual sleep commands necessary
   fTask[i].get();

   // since we have a concatenation of downloads, we can update progress here
   progessBarText += 100 / urlStack.length;
}

Edit to your second comment:

You would have a Class that implements Callable, where all your magic happens:

public class MyCallable implements Callable<String>
{
    String url;

    public MyCallable(String s)
    {
        url = s;
    }

    @Override
    public String call() throws Exception
    {
        // Download image here, you have the URL stored in `url`
        return "I'm done";
    }
}

Your FutureTask then runs that object:

MyCallable img1 = new MyCallable("http://www.myimage.com/1.jpg");    
MyCallable img2 = new MyCallable("http://www.myimage.com/2.jpg");    
FutureTask<String> fTask = new FutureTask<String>(img1);
fTask.get();
fTask = new FutureTask<String>(img2);
fTask.get();

Does this make it any clearer? The above code can be optimized a lot, this is just to get across what you need to know about FutureTask

Upvotes: 1

Nouran S. Ahmad
Nouran S. Ahmad

Reputation: 503

why dont you try this for loop inside the aysncTask, as this wont create multiple aysncTask objects, less memory use.

 public class httpDownloadImages extends AsyncTask<Void,Void,String> {
        Bitmap myBitmap[]=new Bitmap[10];
@Override
    protected void onPreExecute() {
        super.onPreExecute();
        showProgressDialog();

    }

        @Override
        protected String doInBackground(Void... params) {
            try {

                for(int i=1; i<=10; i++){
                    String src="http://"+ip+"/images/"+i+".jpg";
                    java.net.URL url = new java.net.URL(src);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setDoInput(true);
                    connection.connect();
                    InputStream input = connection.getInputStream();
                    myBitmap[i] = BitmapFactory.decodeStream(input);
                    if(myBitmap[i]!=null)
                        saveimagetoFile(myBitmap[i],i);
                }

            } catch (IOException e) {

                return null;
            }
            return "successful";
        }
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            progress_dialog.hide();

        }
    }

and define a method for saving the images to sd card if you want:

void saveimagetoFile(Bitmap bmp,int num){
        try {
            String path = Environment.getExternalStorageDirectory().toString();
            OutputStream fOut = null;
            File file = new File(path, "PriceChecker/pc"+num+".jpg"); // the File to save to
            fOut = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fOut); //save image to jpeg file
            fOut.flush();
            fOut.close();
        }catch (Exception e){

        }
    }

but in my case the images where named 1.jpg , 2.jpg, 3.jpg ...etc Hope this helps

EDIT: method for showing progress dialog:

private void showProgressDialog(){
 AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);

        View promptView;
        LayoutInflater layoutInflater = LayoutInflater.from(OrderActivity_gridstyle.this);
        promptView = layoutInflater.inflate(R.layout.progress_dialog, null);

        alertDialogBuilder.setView(promptView);
        alertDialogBuilder.setCancelable(true);
        progress_dialog=alertDialogBuilder.create();
        progress_dialog.show();}

the progress dialog I used is of shape: wheel, of course you can use different shape or type.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:id="@+id/progress_time">

    <ProgressBar
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:id="@+id/prog_circle"
        android:max="100"
        android:progress="0"
        android:indeterminate="true"
        android:indeterminateDrawable="@drawable/progress_wheel"
        android:layout_below="@+id/textView11"
        android:layout_centerHorizontal="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Please Wait"
        android:id="@+id/textView11"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:textColor="@color/blue_" />

</RelativeLayout>

which looks like this: enter image description here

Upvotes: 1

Related Questions