blurbs78 blurbs78 - 6 months ago 47
Android Question

Android Studio OutOfMemoryError when trying to get image through Picasso

EDIT: So apparently the images I'm trying to use are too large. Anyway I can get around this? I'm trying to eventually crop them and set them as my wallpaper programmatically. I've tried a smaller image and it works. Any tips for larger images?

So I'm trying to get an image from a url using Picasso, but when I use the .get() method I'm getting this:

java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.OutOfMemoryError
at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
at android.graphics.BitmapFactory.decodeStreamInternal(BitmapFactory.java:601)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:577)
at com.squareup.picasso.BitmapHunter.decodeStream(BitmapHunter.java:142)
at com.squareup.picasso.BitmapHunter.hunt(BitmapHunter.java:217)
at com.squareup.picasso.RequestCreator.get(RequestCreator.java:385)


I'm executing the Picasso code in AsyncTask because that's where I have some network code fetching the url I need. However, even if I comment out everything and give the url to Picasso directly, the problem persists. With everything commented out my code looks like this:

protected Bitmap doInBackground(String... name) {
try {
return Picasso.with(myContext)
.load("https://i.redd.it/4l2boppcmn1x.jpg")
.get();

} catch (Exception e) {
android.util.Log.e(TAG, "Failed to retrieve submissions", e);
return null;
}
}


I've tried everything I could think of including increasing the heap size, adding the largeHeap tag to the manifest, etc. Is this a problem with my code or Android Studio? When using the Memory Monitor while my app is running it says "Free[0.35 MB] Allocated[15.02 MB]" before I even do anything. That can't be right can it? I'm still new to all this so if I am misunderstanding something please let me know. Thanks.

Answer

Use resize with Picasso

return Picasso.with(myContext)
                .load("https://i.redd.it/4l2boppcmn1x.jpg")
                .resize(500, 300)
                .get();