如何从服务器下载多个图像?

时间:2015-05-24 06:39:45

标签: android image download server

这是我的代码,downloadFile(String URLS)正在下载功能。 我使用istagram API下载流行的图像,但只下载了一个图像,其余的图像没有被下载。

如何从服务器下载图像? 我知道downloadFile(String URLS)函数存在问题,但我无法解决此问题。

@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

4 个答案:

答案 0 :(得分:1)

我建议您使用:Picasso这是一个很棒的图书馆,可以安装在Android上。

答案 1 :(得分:0)

而不是使用AsyncTask,你可以像Universal-Image-Loader那样使用任何Image Loader。在循环中

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

或者您可以像here一样使用下载管理器。 你可以在循环中做同样的多个图像下载。

答案 2 :(得分:0)

我建议使用Universal Image Loader,它快速,易于使用并且可以处理大部分内容。

答案 3 :(得分:0)

我的回答很晚,但是迟到总比没有好!&#34;

使用ThreadPoolExecutor下载多个文件的教程对我有很大帮助:Downloading Multiple Files In Android Using ThreadPoolExecutor