Search code examples
androidimageurldownloadcorrupt

Can't save images from URL. Android


first, sorry for my bad english and second, I have a "little" problem. I tested a lot of codes from StackOverFlow but i continue with the same problem.

I'm trying to download some images from URL. I have an ExpandableListView and I use a class named Downloadusers to download all information about users. In this class I get the user's photo URL and I download the images with the following code:

 private void downloadFile(String url) {

    String filepath = null;
    try
    {   
      URL nurl = new URL(url);
      HttpURLConnection urlConnection = (HttpURLConnection) nurl.openConnection();
      urlConnection.setRequestMethod("GET");
      urlConnection.setDoOutput(true);                   
      urlConnection.connect();                  
      File SDCardRoot = getExternalFilesDir(null);
      String filename = url.substring(url.lastIndexOf('/') + 1);  
      Log.i("Local filename:",""+filename+"  SDCardRoot: "+SDCardRoot.toString());
      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[PHOTO_FILE_MAX_SIZE];
      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();
      if(downloadedSize==totalSize) filepath=file.getPath();    
    } 
    catch (MalformedURLException e) 
    {
      e.printStackTrace();
    } 
    catch (IOException e)
    {
      filepath=null;
      e.printStackTrace();
    }
    Log.i("filepath:"," "+filepath);
}

I have also verified that the URLs are correct and I have loaded in the browser. With Log.i("filepath:"," "+filepath); I can see that filepath is correct, so I think that images are downloaded correctly but no, image files are corrupt files, so when I go to load the images into my ImageView I have a NullPointException because bMap readed is null due to corrupt images.

I have all permissions: Internet, Write and read external storage and phone state.

I tried too download images with AsyncTask, but I have the same problem.

Someone know what can be my problem? Thanks.


Solution

  • I solved my problem using library nostra13 "universal-image-loader-1.9.2.jar". My code is now:

        // If the user photo exists and is public, download and show it. 
        if (Utils.connectionAvailable(activity)
                && (photoFileName != null) && !photoFileName.equals("")
                && !photoFileName.equals(Constants.NULL_VALUE)) {
    
            // Create options. Setting caché = true (default = false)
            DisplayImageOptions options = new DisplayImageOptions.Builder()
                                .cacheInMemory(true)
                                .build();
    
             // Create global configuration and initialize ImageLoader 
             // with this configuration
            ImageLoaderConfiguration config = new ImageLoaderConfiguration
                                     .Builder(activity.getApplicationContext()) 
                                     .defaultDisplayImageOptions(options)
                                     .build();
    
            ImageLoader.getInstance().init(config);
    
            // Load image, decode it to Bitmap and display Bitmap in ImageView 
            // (or any other view 
            // which implements ImageAware interface)
            ImageLoader.getInstance().displayImage(photoFileName, image);
       }
    

    With that code I can load the image on caché and show in my imageview without problems.

    Thanks to all.