Mobi Malik
Mobi Malik

Reputation: 49

How to download multiple images from server?

This is my code and downloadFile(String URLS) is downloading function. I am using istagram API to download popular images but just one image is downloaded and the rest of the images are not being downloaded.

How to download images from server? I knew that there is an issue in downloadFile(String URLS) function but I am not able to solve this issue.

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mInstagram          = new Instagram(this, CLIENT_ID, CLIENT_SECRET, REDIRECT_URI);

        mInstagramSession   = mInstagram.getSession();

        if (mInstagramSession.isActive()) {
            setContentView(R.layout.activity_user);

            InstagramUser instagramUser = mInstagramSession.getUser();

            mLoadingPb  = (ProgressBar) findViewById(R.id.pb_loading);
            mGridView   = (GridView) findViewById(R.id.gridview);

            ((TextView) findViewById(R.id.tv_name)).setText(instagramUser.fullName);
            ((TextView) findViewById(R.id.tv_username)).setText(instagramUser.username);

            ((Button) findViewById(R.id.btn_logout)).setOnClickListener(new View.OnClickListener() {                
                @Override
                public void onClick(View arg0) {
                    mInstagramSession.reset();

                    startActivity(new Intent(MainActivity.this, MainActivity.class));

                    finish();
                }
            });
            ((Button) findViewById(R.id.btn_slideshow))
            .setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    Intent i = new Intent(MainActivity.this,
                            SlideshowActivity.class);
                    startActivity(i);

                    finish();

                }
            });

            ImageView userIv = (ImageView) findViewById(R.id.iv_user);

            DisplayImageOptions displayOptions = new DisplayImageOptions.Builder()
                    .showImageOnLoading(R.drawable.ic_user)
                    .showImageForEmptyUri(R.drawable.ic_user)
                    .showImageOnFail(R.drawable.ic_user)
                    .cacheInMemory(true)
                    .cacheOnDisc(false)
                    .considerExifParams(true)
                    .build();

            ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)                                               
                    .writeDebugLogs()
                    .defaultDisplayImageOptions(displayOptions)             
                    .build();

            ImageLoader imageLoader = ImageLoader.getInstance();
            imageLoader.init(config);

            AnimateFirstDisplayListener animate  = new AnimateFirstDisplayListener();

            imageLoader.displayImage(instagramUser.profilPicture, userIv, animate);
            imageLoader.destroy();
            new DownloadTask().execute();

        } else {
            setContentView(R.layout.activity_main);

            ((Button) findViewById(R.id.btn_connect)).setOnClickListener(new View.OnClickListener() {           
                @Override
                public void onClick(View arg0) {                    
                    mInstagram.authorize(mAuthListener);    
                }
            });
        }
    }

    private void showToast(String text) {
        Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
    }

    private Instagram.InstagramAuthListener mAuthListener = new Instagram.InstagramAuthListener() {         
        @Override
        public void onSuccess(InstagramUser user) {
            finish();

            startActivity(new Intent(MainActivity.this, MainActivity.class));
        }

        @Override
        public void onError(String error) {     
            showToast(error);
        }

        @Override
        public void onCancel() {
            showToast("OK. Maybe later?");

        }
    };

    public static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {

        static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());

        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            if (loadedImage != null) {
                ImageView imageView = (ImageView) view;
                boolean firstDisplay = !displayedImages.contains(imageUri);
                if (firstDisplay) {
                    FadeInBitmapDisplayer.animate(imageView, 500);
                    displayedImages.add(imageUri);
                }
            }
        }
    }

    public class DownloadTask extends AsyncTask<URL, Integer, Long> {
        ArrayList<String> photoList;

        protected void onCancelled() {


        }

        protected void onPreExecute() {

        }

        protected Long doInBackground(URL... urls) {         
            long result = 0;

            try {
                 params = new ArrayList<NameValuePair>(1);

                params.add(new BasicNameValuePair("count", "10"));
                System.out.println("PARAMS==="+params);

                InstagramRequest request = new InstagramRequest(mInstagramSession.getAccessToken());
                response= request.createRequest("GET", "/media/popular", params);
                System.out.println("RESPONCE VALUE ==="+response);
                rootPath = Environment.getExternalStorageDirectory().toString()+File.separator+"InstagramFavourites";
                rootFileDirectory= new File (rootPath);
                rootFileDirectory.mkdir();


                Log.w("TAG", "Folder Created: " + rootPath);
                System.out.println("IMAGES DOWNLOADED IN FOLDER=="+rootFileDirectory);
                if (!response.equals("")) {
                    JSONObject jsonObj  = (JSONObject) new JSONTokener(response).nextValue();                   
                    JSONArray jsonData  = jsonObj.getJSONArray("data");

                    int length = jsonData.length();

                    if (length > 0) {
                        photoList = new ArrayList<String>();

                        for (int i = 0; i < length; i++) {
                            JSONObject jsonPhoto = jsonData.getJSONObject(i).getJSONObject("images").getJSONObject("low_resolution");

                            photoList.add(jsonPhoto.getString("url"));

                        downloadFile(jsonPhoto.getString("url"));
                            //downloadFile(jsonObj.toString());
                            //downloadFile(photoList.get(i));


                        }

                    }

                }
            } catch (Exception e) { 
                e.printStackTrace();
            }

            return result;
        }

        protected void onProgressUpdate(Integer... progress) { 

        }

        protected void onPostExecute(Long result) {
            mLoadingPb.setVisibility(View.GONE);

            if (photoList == null) {
                Toast.makeText(getApplicationContext(), "No Photos Available", Toast.LENGTH_LONG).show();
            } else {
                DisplayMetrics dm = new DisplayMetrics();

                getWindowManager().getDefaultDisplay().getMetrics(dm);

                int width   = (int) Math.ceil((double) dm.widthPixels / 2);
                width=width-50;
                int height  = width;

                PhotoListAdapter adapter = new PhotoListAdapter(MainActivity.this);

                adapter.setData(photoList);
                adapter.setLayoutParam(width, height);

                mGridView.setAdapter(adapter);
            }
        }     




        void downloadFile(String URLS){
            count=count++;

              HttpURLConnection urlConnection = null;
            try {
               URL url = new URL(URLS.toString());
                System.out.println("URL VALUES"+url);
                 urlConnection = (HttpURLConnection) url.openConnection();

                urlConnection.setRequestMethod("GET");
                urlConnection.setDoOutput(true);

                //connect
                urlConnection.connect();



String fileName=rootPath+File.separator+"abc"+ count+".png" ;

File fs=new File(fileName);

fs.createNewFile();

                FileOutputStream fileOutput = new FileOutputStream(fs);
                int status = urlConnection.getResponseCode();
                InputStream inputStream;


                if(status >= HttpStatus.SC_BAD_REQUEST)
                {
                    inputStream = urlConnection.getErrorStream();
                    System.out.println("ERROR");
                }
                else
                    inputStream = urlConnection.getInputStream();           

                //Stream used for reading the data from the internet
                // inputStream = urlConnection.getInputStream();

                //this is the total size of the file which we are downloading
                totalsize = urlConnection.getContentLength();

                runOnUiThread(new Runnable() {
                    public void run() {
                     //   pb.setMax(totalsize);
                    }               
                });


                byte[] buffer = new byte[1024];
                int bufferLength = 0;

                while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
                    fileOutput.write(buffer, 0, bufferLength);
                    downloadedSize += bufferLength;
                    // update the progressbar //
                    runOnUiThread(new Runnable() {
                        public void run() {
                           // pb.setProgress(downloadedSize);

//                            float per = ((float)downloadedSize/totalsize) * 100;
//                            System.out.println("Float per value=="+per);
                            //cur_val.setText("Downloaded " + downloadedSize + "KB / " + totalSize + "KB (" + (int)per + "%)" );
                        }
                    });
                }
                //close the output stream when complete //
                fileOutput.close();
                runOnUiThread(new Runnable() {
                    public void run() {
                        // pb.dismiss(); // if you want close it..
                    }
                });         

            } catch (final MalformedURLException e) {
                showError("Error : MalformedURLException " + e);        
                e.printStackTrace();
            } catch (final IOException e) {
                showError("Error : IOException " + e);          
                e.printStackTrace();
            }
            catch (final Exception e) {
                showError("Error : Please check your internet connection " + e);
            }  
            finally
            {
                  urlConnection.disconnect();
            }
        }
        void showError(final String err){
            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(getApplicationContext(), err, Toast.LENGTH_LONG).show();

                }
            });
        }
    }
}


    enter code here

Upvotes: 0

Views: 2736

Answers (4)

Nii Laryea
Nii Laryea

Reputation: 1221

My answer is very late, but still "better late than never!"

This tutorial on using ThreadPoolExecutor to download multiple files was of great help to me: Downloading Multiple Files In Android Using ThreadPoolExecutor

Upvotes: 0

theJango
theJango

Reputation: 1108

I would suggest to use Universal Image Loader, it fast ,easy to use and take care most of the stuff.

Upvotes: 0

andDev
andDev

Reputation: 66

I recommend you to use: Picasso its a great library for images on android.

Upvotes: 1

RBK
RBK

Reputation: 2417

instead of use AsyncTask you would any Image Loader like Universal-Image-Loader. in loop like

for(...)
{
   Bitmap bmp = imageLoader.loadImageSync(imageUri);
   // save bitmap here.
}

or you can use Download Manager as like here. you can do same in loop for multiple image download.

Upvotes: 0

Related Questions