Android: Volley JsonRequest Keeps Whole Object On Memory - android

I'm using volley to get a JsonObject from a URL. My problem is that often I get an OutOfMemory Exception. I used to MAT to analyze the memory leaks and I see that the whole object on response after downloaded and used it is still on memory. What I'm doing wrong?
Volley Code
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
item = parser.parse(response);
updateLayout();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
bar.setVisibility(View.GONE);
if(!isNetworkAvailable()){
Toast.makeText(act, "No Internet Connection.", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(act, "The Server Is Down. Try Again.", Toast.LENGTH_SHORT).show();
}
}
});
// Adding request to request queue
VolleySingleton.getInstance().addToRequestQueue(jsonObjReq);
MAT screenshot

Ok i think your problem is here:
Network dispatcher is a thread that his duty is to send the request to the server and getting results, he manages the http connection and he is your outside interface, so each objects in this thread is those who their request are in the flight and have been sent to the server and are waiting to get back the result , these are other requests no the one that you get the result in on response. Network response is the one that manages parsing the response and delivers it to you after response delivered to network dispatcher. i suggest you to look at the source code to better understand this beautiful framework. i think your problem is coused by parser or your long json so you can eliminate it by providing bigger cache for volley or another joson parser technique.
Update:
i mean that those hashmaps are not memory leak, those are your other requests to the server, you have not specify any memory leak in your image. what you have shown on the picture is your other requests that you sent to volley. when you send your request to this library, this library creates multiple request connections to the server to make your network operation be speedy. those multiple requests take time to go from your device to the server and come back with response. those request and connection are all managed by network dispatcher. it makes multiple connections and sends requests to the server. so what you see on the image is those requests that have not gotten results yet from server. so those 3 items must be into the memory because those are requests that you want the results for them.
after you exit from response block {} imean last brace your response automatically removed from memory, so do not worry about your response. i think your problem dose not relate to volley buges or any thing else about this library. i think you must check other aspect of your apps like the method of parsing json or ...

After finising my app leak search, I finally understand why volley keeps request in memory . In my case, I use volley singleton mode. Volley has 4 threads do network dispatch, and each thread keeps a request.
when you do more than 4 times request, there will always be 4 requests keep in memory. without other leak problem ,request would not raise .
Usually, we use new Anonymous Inner Class request , which will keep a strong reference to outer class . so we will see Activity not GC after onDestory().
As a result, Volley not have big problem, if you do not want request Keep strong reference to your class ,so use weakReference.
Your OOM problem must be something else caused.

Related

What is the response order in Volley request queue?

I have a for loop , which is creating different url and then i am pushing the urls in the Volley RequestQueue using add function.
I have a question that , will the response listner will be responding in the order of the request added to the RequestQueue or it will be random based on the server responses of the requests made?
I am using VolleySingleton approach.
Volley RequestQueue class manage asynchonous requests queue.
It means Volley send requests on a FIFO (first in first out) model, but since responses can be quite long to come back, it handle responses in no particular order.
You can't use it if you want the result of a first request to be used in a second request.
However, you can visibly use RequestFuture class to use Volley on a synchonous model:
Can I do a synchronous request with volley?
By default, Volley RequestQueue will use 4 concurrent Threads to process the Requests added to the Queue. This may be changed by extending the RequestQueue class and passing the desired Thread pool size as the third parameter to super contructor.
Passing 1 to the constructor will result in the RequestQueue processing one Request at a time :-)
Reference
No! Android volley process each requests in request queue Asynchronously:
Refer the architecture image:
Each requests in the request queue will be processed by the network threads and also you can limit the network dispatcher thread count check here
Assuming that the default behavior is to send multiple requests on separate concurrent threads, then the order of the responses then becomes dependent on the total response time for each individual request.
As to identifying the responses (other than the data itself), it seems like you should be able to instantiate a Response.Listener implementation with a unique request identifier (original URL or int) such that when the response handler is invoked it is able to differentiate the original request.
public class JSONProcessor implements Response.Listener<JSONObject> {
private String url;
private int reqCode;
public JSONProcessor (String reqUrl) {
this.url = reqUrl
}
public JSONProcessor (int reqCode) {
this.reqCode = reqCode;
}
public void onResponse(JSONObject response) {
// use this.url or this.reqCode to determine original request
// process response
}
}
Alternatively, use different implementations of Response.Listener for each endpoint you expect to be processing.
In general, in my opinion it is best to be completely data driven if at all possible.

what is the method used to fetch the cached string response using android -volley?

1)I am caching the string network response from the server using the method
request.setShouldCache(true);
2)I am trying to access the cached data using
System.out.println("the cached data"+new String(request.getCacheEntry().data));
This throws a null pointer exception .
3)I printed a output statment in HTTPHeaderparser.java .The data is printed properly .
System.out.println("the data value is"+new String(entry.data) );
4)So i guess I made some mistake while fetching the cached data .
Can some one help me out ?
The cache entry in the request it's not filled until you run the request, so you should directly call the cache to test if it contains a value with
mQueue.getCache().get(request.getCacheKey())
as bogdan put in the comment if what you want to do is get a value from cache without making a network request.
this method is fast and you can call from the UI Thread. It will return the cache entry if available even if it's expired, but you can call the isExpired() method to know if the response it's outdated.
It returns the data even if stale, because you can choose to show it while you refresh the data in the background.
Take a look at the method parseCacheHeaders(NetworkResponse) from the class HttpHeaderParser. There are some conditions there for caching the response, so the library will only cache the response if the server will provide some headers. If you want to override this, you will have to override the method parseNetworkResponse(NetworkResponse) from the Request class and call a different method for parsing the cache headers from the server.
Update
It seems I misunderstood the question a bit, for accessing Volley cache, assuming your RequestQueue instance is mQueue, you can do mQueue.getCache().get(request.getCacheKey()).

Volley and AsyncTask

I read a post about Volley and I know it's great networking library. But I couldn't understand one thing.
All requests are Async Task or not?
When I want to send asyncTask request using Volley do I need put Volley request in AsyncTask?
or should I just call Volley Request if it is already AsyncTask request?
private class MyClass extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// do Volley request
}
}
Is this right approach?
You don't need to run Volley request on AsyncTask.
Why:
They manage all network related task on separate thread.
If you look closely at library project they did not picture the AsyncTask.
But they intelligently handle all network related task efficiently.
Check RequestQueue.java class in Volley's main package
here I am pasting java doc.
/**
* A request dispatch queue with a thread pool of dispatchers.
*
* Calling {#link #add(Request)} will enqueue the given Request for dispatch,
* resolving from either cache or network on a worker thread, and then delivering
* a parsed response on the main thread.
*/
Edited:
Forming a Request:
With Volley, network communication is managed by the RequestQueue. The best way to utilize the RequestQueue and all of its tools, especially the cache, is by instantiating it once and keeping it around as a singleton. At this point you can then add or cancel requests, stop or start requests, and access the response cache(s).
RequestQueue queue =Volley.newRequestQueue(this);
Once the RequestQueue has been instantiated a request must be formed. This can be done utilizing a few different “out of the box” request classes included with the Volley Library or by extending Volley’s request class into your own custom request. The request classes already included in Volley are a String request, JSON requests, and an Image Request. Most of the request classes included in Volley library utilize constructors much like the one below.
Parameters being passed into constructor:
RequestMethod(get, post, delete, ect)
JSONObject-An optional object that will be posted with your request
ResponseListener- Where your data will go after the request is complete
ErrorListener – What will be told when there was a problem with your request.
JsonObjectRequest request = JsonObjectRequest(Requestmethod, url, null, new ResponseListener(), new ErrorListener());
Listners to receive response:
Successful Response Listener
private class ResponseListener implements Response.Listener{
#Override
public void onResponse(JSONObject response){
}
}
Error Response Listener
private class ErrorListener implements Response.ErrorListener{
#Override
public void onErrorResponse(VolleyError error){
}
}
Finally add your request to Request queue, rest of everything Volley will handle for you.
Making call:
Now, that we have made our request and response classes we are ready to add the request to the queue and retrieve the data. To do so we simply add the request to the queue.
queue.add(request);
The response or error will then be delivered to the response/error classes that we defined in our request. You can add as many requests to the queue that you would like at one time and the responses will be delivered to their respective response/error classes
When you use Volley, there's no need to combine it with AsyncTask. It does the networking stuff on another thread for you.
Here is a basic example of a network call using Volley. As you can see, all the code is just in the Activity, without any need to define an AsyncTask.
Volley cannot be inserted inside AsyncTask because,
Volley is initiating background thread(s) on its own so all the network requests are executed off the UI thread so primarily you don't need to extend AsyncTask anymore. Of course you will have to take care to cancel the running requests on rotation or when user exits your activity..
As Volley is mainly used for minor Networking purposes in Android (for major use DownloadManager). It does similar working of AsyncTask Class. Implement Singleton in Volley.
Images can also be sent in Volley.
The whole point of introducing Volley library was to make sure user doesnt have to worry about all the "obvious" stuff while sending a network request. This means that volley takes care of the following on its own
Switching Background thread
Transparent disk and memory response
Multiple concurrent network connections. etc
To answer your question- You don't need to worry about switching to background thread, Volley takes care of this on its own. Also once the request is completed the success or failure callback is invoked on the main thread.Hence with Volley developer need not worry about switching threads
This tutorial here gives a good step by step explanation of Working with Volley Library

How to maintain progress bar state when using volley?

It is easy to maintain progress bar state when i use AysncTask with fragments Callback but how should i achieve it with volley? I can;t use AsyncTask because it is outdated and volley is better and faster.
Any Help or Hint will be grateful.
I am using google's volley to Post and Get Requests
I think there are misconceptions here.
First off, Volley faster than AsyncTask.
This is comparing apples and oranges. They both use threads. Volley threads are not any faster than the threads in async task. The queues are separate but that is about it. In API 11 & higher you are allowed to use your own threadpool for AsyncTask instances.
Second, define better.
Volley is designed for sending a lot of light payloads (GET/POST) to a server and getting back pretty quick responses. These responses can then be used by the caller.
AsyncTask is designed to complete a given task off the UI thread and provide various callbacks as to the state of that task.
For your ProgressBar I am assuming you are trying to determine the progress of a request that is being executed. In the Volley world, since these are expected to be tiny, you have pretty much 3 states.
Not Started
Executing(also contains start parsing)
Done (comprised of success, error and cancelled and such)
As you know with AsyncTask there is a callback for onProgress when using publishProgress. So your instance can define anything it wants to send through as an indication of progress.
If your payload is big and will take time to transfer to the server, Volley may not be appropriate. Volley doesn't do a great job or even try to do a great job of sending large payloads to and from a server. The reason is that this just isn't what it is meant for. Like it requires that all payloads, upload and receive can fit in memory entirely. So If you have a few volley requests going all over, and each one with like a 1MB payload and a 1MB response, you could see this adding up pretty quickly. You would need a streaming option to better handle that.
Volley is great library but consider what it is recommended to be used for. Read the documentation and implementation of the code for more info.
If you are doing something that is going to take a rather long time, I would write a specific request type in volley that sends and streams content to and from. That way you can tell how much work is left with the request. I am assuming you are using bytes sent and receive as the measure for progress.
you can add a listener to the queue which is executed when the request end
mRequestQueue.add(yourRequest);
mRequestQueue.addRequestFinishedListener(new RequestQueue.RequestFinishedListener<String>() {
#Override
public void onRequestFinished(Request<String> request) {
if (progressDialog != null && progressDialog.isShowing())
progressDialog.dismiss();
}
});
It's a pretty simple fix. Before you make your volley request, call the method progress.show(), and then on your response, call progress.dismiss() Just did this and it works great!
It's very easy to do that.. see the below code snippet
sendJsonRequest(){
///ENABLE PROGRESS BAR HERE
enableProgressBar();
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
hideProgressDialog();
System.out.println(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideProgressDialog();
}
});
queue.add(jsObjRequest);
}

improving speed performance on a data call

I am making an API call to a web service from the android application the problem is that it returns around 22000 records, I am loading this into an array after i convert each record into an object then assign that Array to a ListView. What is the fastest/best way to fetch this data from the web service? (buffer) ? and what are the best practices for this type of issues.
I would recommend using a library to handle your data call...
Please try using Android Query; specifically, see the section entitled Asynchronous Network.
This AQuery library (AndroidQuery) is lightweight, and requires only 1 jar SMALL jar file. It can be used with Maven or Gradle Android projects as well. It allows you to EASILY fetch XML or JSON data from a remote server in either asynchronous or synchronous fashion. I have used it many times with a JSON back-end, and it is a real timesaver.
This library also allows you to specify a ProgressBar that will automatically appear and disappear during the network download process.
Here is an example of an HTTP call to a JSON back-end, asynchronously:
public void asyncJson(){
//perform a Google search in just a few lines of code
String url = "http://www.google.com/uds/GnewsSearch?q=Obama&v=1.0";
aq.ajax(url, JSONObject.class, this, "jsonCallback");
}
public void jsonCallback(String url, JSONObject json, AjaxStatus status) {
if(json != null) {
//successful ajax call
} else {
//ajax error
}
}
AQuery can also simplify other aspects of Android programming (such as eliminating the findViewById() calls for many scenarios).

Categories

Resources