Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download Images From URL to SD Card

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);

    }

}
like image 653
user3739970 Avatar asked Aug 09 '14 10:08

user3739970


Video Answer


1 Answers

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>
like image 88
OmerFaruk Avatar answered Oct 09 '22 04:10

OmerFaruk