5

I am trying to create a very simple Image Downloading app. in which i want to download all images from this url to sd card: https://www.dropbox.com/sh/5be3kgehyg8uzh2/AAA-jYcy_21nLBwnZQ3TBFAea

this code works to load image in imageview:

package com.example.imagedownloadsample;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.ImageView;

import com.squareup.picasso.Picasso;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.image_download);

        final ImageView img = (ImageView) (findViewById(R.id.imageView1));

        // File file = new File(Environment.getExternalStorageDirectory(),
        // "Android/data/com.usd.pop");

        Picasso.with(getApplicationContext())
                .load("http://8020.photos.jpgmag.com/3456318_294166_528c960558_m.jpg")
                .into(img);

    }

}

but when i tried like this to download image to sd card i end-up with unfortunatelly app stopped error:

package com.example.imagedownloadsample;

import java.io.File;

import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;

import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.image_download);

        //final ImageView img = (ImageView) (findViewById(R.id.imageView1));

         File file = new File(Environment.getExternalStorageDirectory(),
         "Android/data/com.usd.pop");

        Picasso.with(getApplicationContext())
                .load("http://8020.photos.jpgmag.com/3456318_294166_528c960558_m.jpg")
                .into((Target) file);

    }

}
Amarjit
  • 4,327
  • 2
  • 34
  • 51
user3739970
  • 591
  • 2
  • 13
  • 28

5 Answers5

16

You can use this AsyncTask, so that you don't get OnMainThread exception.

  class DownloadFile extends AsyncTask<String,Integer,Long> {
    ProgressDialog mProgressDialog = new ProgressDialog(MainActivity.this);// Change Mainactivity.this with your activity name. 
    String strFolderName;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mProgressDialog.setMessage("Downloading");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setMax(100);
        mProgressDialog.setCancelable(true);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.show();
    }
    @Override
    protected Long doInBackground(String... aurl) {
        int count;
        try {
            URL url = new URL((String) aurl[0]);
            URLConnection conexion = url.openConnection();
            conexion.connect();
            String targetFileName="Name"+".rar";//Change name and subname
            int lenghtOfFile = conexion.getContentLength();
            String PATH = Environment.getExternalStorageDirectory()+ "/"+downloadFolder+"/";
            File folder = new File(PATH);
            if(!folder.exists()){
                folder.mkdir();//If there is no folder it will be created.
            }
            InputStream input = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream(PATH+targetFileName);
            byte data[] = new byte[1024];
            long total = 0;
            while ((count = input.read(data)) != -1) {
                total += count;
                       publishProgress ((int)(total*100/lenghtOfFile));
                output.write(data, 0, count);
            }
            output.flush();
            output.close();
            input.close();
        } catch (Exception e) {}
        return null;
    }
    protected void onProgressUpdate(Integer... progress) {
         mProgressDialog.setProgress(progress[0]);
         if(mProgressDialog.getProgress()==mProgressDialog.getMax()){
            mProgressDialog.dismiss();
            Toast.makeText(fa, "File Downloaded", Toast.LENGTH_SHORT).show();
         }
    }
    protected void onPostExecute(String result) {
    }
}

Copy this class into your activity. It mustn't be in another method.

And you can call this like new DownloadFile().execute(“yoururl”);

Also, add these permissions to your manifest.

  <uses-permission android:name="android.permission.INTERNET"> </uses-permission>
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
 <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
toadflakz
  • 7,764
  • 1
  • 27
  • 40
OmerFaruk
  • 292
  • 2
  • 13
14

Use Picasso and load into a Target

I agree with Ichigo Kurosaki's answer above. Here is a detailed example of how you can use Picasso and a Picasso Target.


How you call the Picasso code

Picasso.with(ImageDetailActivity.this).load(
galleryObjects.get(mViewPager.getCurrentItem()).fullImagePath).into(target);


Picasso Target example

private Target target = new Target() {
    @Override
    public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
        new Thread(new Runnable() {
            @Override
            public void run() {

                File file = new File(
                    Environment.getExternalStorageDirectory().getPath() 
                    + "/saved.jpg");
                try {
                        file.createNewFile();
                        FileOutputStream ostream = new FileOutputStream(file);
                        bitmap.compress(Bitmap.CompressFormat.JPEG,100,ostream);
                        ostream.close();
                }
                catch (Exception e) {
                        e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    public void onBitmapFailed(Drawable errorDrawable) {}

    @Override
    public void onPrepareLoad(Drawable placeHolderDrawable) {}
};
Codeversed
  • 9,287
  • 3
  • 43
  • 42
1

Check these links

Why use Android Picasso library to download images?

http://www.opensourcealternative.org/tutorials/android-tutorials/android-picasso-save-image-tutorial/

http://www.101apps.co.za/articles/gridview-tutorial-using-the-picasso-library.html

http://www.youtube.com/watch?v=tRTFwzUH_ek

http://square.github.io/picasso/

Using Picasso, your code will be of only 1 line

Picasso.with(context).load("your URL").into(your_imageView);

To store into external sd card

Android saving file to external storage

Write a file in external storage in Android

http://www.javatpoint.com/android-external-storage-example

Community
  • 1
  • 1
Aniruddha
  • 4,477
  • 2
  • 21
  • 39
  • can i use picasso to download images to sd card not imageview – user3739970 Aug 09 '14 at 10:38
  • You can, you need to come up with your own logic. – Aniruddha Aug 09 '14 at 10:47
  • ok as your code: `Picasso.with(context).load("your URL").into(your_imageView);` how to use this `your_imageview` to save image to sd – user3739970 Aug 09 '14 at 11:01
  • Post it as different question. You can accept this first. – Aniruddha Aug 09 '14 at 11:02
  • depending on your code i tried something like this: `File file = new File(Environment.getExternalStorageDirectory(), "Android/data/com.usd.pop"); file.mkdirs(); Picasso.with(context).load("your URL").into(file);` **got these errors:** 1. context cannot be resolved to a variable 2. Picasso cannot be resolved ` – user3739970 Aug 09 '14 at 11:27
  • hey i need little help i added Picasso library to my app and i am having problem with context getting error: `context cannot be resolved to a variable` why i am getting this error: i put this code in button click: `File file = new File(Environment.getExternalStorageDirectory(), "Android/data/com.usd.pop"); file.mkdirs(); Picasso.with(context).load("your URL").into(file);` – user3739970 Aug 09 '14 at 12:13
  • I cannot help you anymore because you did not appreciate. Accept my answer first. – Aniruddha Aug 10 '14 at 05:58
1

Using picasso to save images in sd card, you can do something like following

private Target mTarget = new Target() {
      @Override
      public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
          // Perform simple file operation to store this bitmap to your sd card
      }

      @Override
      public void onBitmapFailed(Drawable errorDrawable) {
      }

      @Override
      public void onPrepareLoad(Drawable placeHolderDrawable) {
      }
}

...

Picasso.with(this).load("url").into(mTarget);

Here "Target" is a class provided by picasso, and it has very simple method to understand...
Hope this will meet your needs

Ichigo Kurosaki
  • 3,765
  • 8
  • 41
  • 56
  • Hey, say if I download images in for loop, how do I save these images using same target ? – Y M Mar 08 '15 at 05:04
  • Its hard to say, how the code will behave in a loop, but i think it will not create the problem, as different Bitmap object will be generated in onBitmapLoaded() response... let's hope this will happen.. have you tried this case ? – Ichigo Kurosaki Mar 08 '15 at 05:08
  • Not yet because I thought since these work Async, I do not have any reference to what image is being downloaded. so suppose: for(int i=0; i – Y M Mar 08 '15 at 05:22
1

Aquery is the Fastest and Easiest way to download image from url to sdcard.

try 
{
    String url=" ";   \\Paste the Url.
    aq.id(R.id.img).progress(R.id.progress).image(Url, true,   true, 0, 0, new BitmapAjaxCallback()
    {
        @Override
        public void callback(String url, ImageView iv,Bitmap bm, AjaxStatus status)   
        {
            iv.setImageBitmap(bm);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bm.compress(Bitmap.CompressFormat.PNG, 100, baos);                           
            byte[] b = baos.toByteArray();
            String EnString = Base64.encodeToString(b,Base64.DEFAULT);          
            File SDCardRoot = Environment.getExternalStorageDirectory().getAbsoluteFile();         
            File dir = new File(SDCardRoot.getAbsolutePath()+ "/Aquery" + "/Image");         
            //Download the Image In Sdcard
            dir.mkdirs();    
            try 
            {        
                if (!SDCardRoot.equals("")) 
                {
                    String filename = "img"+ new Date().getTime() + ".png";
                    File file = new File(dir, filename);
                    if (file.createNewFile())                              
                    {
                        file.createNewFile();
                    }
                    if (EnString != null)          
                    {
                        FileOutputStream fos = new FileOutputStream(file);
                        byte[] decodedString = android.util.Base64.decode(EnString,
                        android.util.Base64.DEFAULT);                  
                        fos.write(decodedString);      
                        fos.flush();
                        fos.close();
                    }
                }
            }
        } catch (Exception e) {
        }
    });
} catch (Exception e) {
}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Dhina k
  • 1,481
  • 18
  • 24