0

Hi could you help me find out why my app stops working when I want to download image from url, here is the code

    public void getOnClick(View view) throws IOException {

    urlAdress = new URL("http://www.cosmeticsurgerytruth.com/blog/wp-     content/uploads/2010/11/Capri.jpg");
    InputStream is = urlAdress.openStream();
    filename = Uri.parse(urlAdress.toString()).getLastPathSegment();
    outputFile = new File(context.getCacheDir(),filename);
    OutputStream os = new FileOutputStream(outputFile);
    byte[] b = new byte[2048];
    int length;

    while ((length = is.read(b)) != -1) {
        os.write(b, 0, length);

        is.close();
        os.close();

I was also trying to use some code from similar topics but I get same message

Your app has stopped working

and it shuts down

davejal
  • 6,009
  • 10
  • 39
  • 82
1. 618
  • 81
  • 1
  • 9

1 Answers1

0
Caused by: android.os.NetworkOnMainThreadException

The problem is that you are trying to download the image from the UIThread. You have to create a class which extends to AsyncTask class and make the download on the doInBackground method

private class DownloadAsync extends AsyncTask<Void, Void, Void> {

        private Context context;

        DownloadAsync(Context context) {
            this.context = context;
        }

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

                URL urlAdress = urlAdress = new URL("http://www.cosmeticsurgerytruth.com/blog/wp-     content/uploads/2010/11/Capri.jpg");
                InputStream is = urlAdress.openStream();
                String filename = Uri.parse(urlAdress.toString()).getLastPathSegment();
                File outputFile = new File(context.getCacheDir(), filename);
                OutputStream os = new FileOutputStream(outputFile);
                byte[] b = new byte[2048];
                int length;

                while ((length = is.read(b)) != -1) {
                    os.write(b, 0, length);

                    is.close();
                    os.close();

                    return null;
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

    }

Then you can execute like this

public void getOnClick(View view){
   new DownloadAsync(this).execute();
}
Vasileios Pallas
  • 4,801
  • 4
  • 33
  • 50