Search code examples
javaandroidnetworkonmainthreadimagedownload

Save image to SD card from url throws NetworkOnmainThread Exception in android


I am a new to Android programming and working on an app in which I want to store an image from an URL to the SD card when the user taps a button.

I found a method for it and used it but it throws NetworkOnMainThread exceptions causing the app to crash. What am I doing wrong?

Here's my code:

void DownloadPost(){
        try
        {
            URL url = new URL( mPost.postImagePath);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(true);
            urlConnection.connect();
            File SDCardRoot = Environment.getExternalStorageDirectory().getAbsoluteFile();
            String filename="downloadedFile.png";
            Log.i("Local filename:",""+filename);
            File file = new File(SDCardRoot,filename);
            if(file.createNewFile())
            {
                file.createNewFile();
            }
            FileOutputStream fileOutput = new FileOutputStream(file);
            InputStream inputStream = urlConnection.getInputStream();
            int totalSize = urlConnection.getContentLength();
            int downloadedSize = 0;
            byte[] buffer = new byte[1024];
            int bufferLength = 0;
            while ( (bufferLength = inputStream.read(buffer)) > 0 )
            {
                fileOutput.write(buffer, 0, bufferLength);
                downloadedSize += bufferLength;
                Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;
            }
            fileOutput.close();
           Toast.makeText(PostListItem.this.getContext(),"Post saved to gallery",Toast.LENGTH_SHORT).show();
        }
        catch (MalformedURLException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
          //  filepath=null;
            e.printStackTrace();
        }
       // Log.i("filepath:"," "+filepath) ;
    }

Solution

  • You can not run network request main thread.

           AsyncTask asyncTask=new AsyncTask() {
                @Override
                protected Object doInBackground(Object[] params) {
                   DownloadPost();
                }
            };
            asyncTask.execute();
    

    Or use Thread :

    Thread thread = new Thread(new Runnable()
    {
        @Override
        public void run() 
        {
            try 
            {
                 DownloadPost();
            } 
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    });
    
    thread.start();