Volley.newRequestQueue is causing OutOfMemoryError
-
21-12-2019 - |
Question
I am using Volley to set an image url. My code is crashing at:
mrq=Volley.newRequestQueue(this);
Log cat says that the exemption is at: com.android.volley.toolbox.DiskBasedCache.streamToBytes
If I comment the code out the program does not crash.
I have tried restarting my phone a couple times because in my research I found that has worked for some with this problem.
Why is creating a RequestQueue using so much memory?
How can I prevent the OutOfMemoryError from happening?
Do I need to empty the cache?
Thank you for your help and taking the time to read this.
Solution
How do you initialize your RequestQueue? I suspect that you are creating RequestQueues for each activity.So initiate it in your Application class as
public class ApplicationController extends Application {
private static ApplicationController sInstance;
private RequestQueue mRequestQueue;
@Override
public void onCreate() {
super.onCreate();
// initialize the singleton
sInstance = this;
}
public static synchronized ApplicationController getInstance() {
return sInstance;
}
public RequestQueue getRequestQueue() {
// lazy initialize the request queue, the queue instance will be
// created when it is accessed for the first time
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
//your code
}
And getRequest queue from your activity as
mrq = ApplicationController.getInstance().getRequestQueue();
OTHER TIPS
A key concept is that the RequestQueue must be instantiated with the Application context, not an Activity context. This ensures that the RequestQueue will last for the lifetime of your app, instead of being recreated every time the activity is recreated