@snitron
Учуcь программировать на Android, IOS и Unity.

Как устранить ошибку при загрузке картинки с сервера?

Загружаю файл с помощью этого метода:
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;
        }
    }


Выдаёт ошибку:
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)


Метод запускаю в отдельном потоке, картинку пытаюсь загрузить весом ~870 КБ.
  • Вопрос задан
  • 58 просмотров
Решения вопроса 1
@AlexeyID
Начинающий Android разработчик
Для каких целей вы загружаете изображение?

Из оф. документации:

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.

Если для того чтобы отобразить в ImageView я вам советую использовать (впрочем как и google) популярные библиотеки, например picasso square.github.io/picasso

Если нет, то вот вам будет полезно https://developer.android.com/topic/performance/gr...
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы