N
N
Nikita2018-07-23 14:09:37
Android
Nikita, 2018-07-23 14:09:37

How to fix an error when downloading an image from the server?

I upload a file using this method:

try {
            String fileName = url.substring(url.lastIndexOf('/') + 1, url.length());
            Log.w("isInCache", manager.hasImageInCache(fileName) + " " + fileName + " " + path + File.separator + fileName);
            if (!manager.hasImageInCache(fileName)) {
                URL urlConnect = new URL(url);
                ReadableByteChannel byteChannel = Channels.newChannel(urlConnect.openStream());
                FileOutputStream outputStream = new FileOutputStream(path + File.separator + fileName);
                outputStream.getChannel().transferFrom(byteChannel, 0, Integer.MAX_VALUE);
                outputStream.close();
                byteChannel.close();
                return manager.putImage(fileName, BitmapFactory.decodeFile(path + File.separator + fileName));
            } else {
                return manager.getImage(fileName);
            }

        } catch (IOException e) {
            Log.w("Download Exception: ", e.getMessage());
            return null;
        }
    }

Gives an error message:
E/AndroidRuntime: FATAL EXCEPTION: Thread-408
                  Process: *package*, PID: 7527
                  java.lang.OutOfMemoryError: Failed to allocate a 2147483659 byte allocation with 4194304 free bytes and 290MB until OOM
                      at java.nio.ByteBuffer.allocate(ByteBuffer.java:56)
                      at java.nio.FileChannelImpl.transferFrom(FileChannelImpl.java:397)
                      at *package*.Util.HttpGetUtility.downloadFile(HttpGetUtility.java:87)
                      at *package*.NewsActivity$1.run(NewsActivity.java:100)
                      at java.lang.Thread.run(Thread.java:818)

I run the method in a separate thread, I try to load a picture weighing ~ 870 KB.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
AlexeyID, 2018-07-23
@snitron

For what purpose are you uploading the image?
From office. documentation:
Note: There are several libraries that follow best practices for loading images. You can use these libraries in your app to load images in the most optimized manner. We recommend the Glide library, which loads and displays images as quickly and smoothly as possible. Other popular image loading libraries include Picasso from Square and Fresco from Facebook. These libraries simplify most of the complex tasks associated with bitmaps and other types of images on Android.
If, in order to display in ImageView, I advise you to use (however, like google) popular libraries, for example picasso square.github.io/picasso
If not, then it will be useful for youhttps://developer.android.com/topic/performance/gr...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question