Why should we use RequestQueue in android? [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I am an android beginner learner .I want to know why should we use RequestQueue in our codes and pass JsonObjectRequest to RequestQueue as an argument .
enter image description here

The Volley uses two classes, RequestQueue and Request
RequestQueue is where all the requests are queued up that has to be executed,
it also manages the worker threads
and maintain network call in the background
also it handles reading from and writing to the cache
and also parsing the response and delivering the parsed response to mainthread.
Request is where network request is constructed.The request object has 3 major request:
JSON requests
JsonObjectRequest — A request for retrieving a JSONObject response body at a given URL
.
JsonArrayRequest — For retrieving JSON Array from the server.
Request takes 3 parameters that are passed to the constructor.
Request Method Type(GET,POST,PUT...).
Resource URL of the required object.
ResponseListener whose callback method contains the response.
ErrorListener whose callback method has an error has been occurred with request (provided error code and optional user-readable).
The snippet for the implementation of both JsonObjectRequest and JsonArrayRequest is as below:
String mJSONURLString= "json_url";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, mJSONURLString, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//add JsonObjectRequest request to queue
requestQueue.add(jsonObjectRequest);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//add JsonArrayRequest to queue
requestQueue.add(jsonArrayRequest);
StringRequest — To retrieve response body as String from the server.
Method Type(GET,POST,...).
The Resource URL.
The Event Listeners.
Code snippet as below:
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Do something with the response
}
},
ImageRequest-To receive an image from the server,the network call has the similar structure as other network requests.
Code snippet as below:
String mImageURLString= "";
ImageRequest imageRequest = new ImageRequest(mImageURLString= , new Response.Listener<Bitmap>() {
#Override
public void onResponse(Bitmap response) {
// Assign the response to an ImageView
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(response);
}
}, 0,0, null);//Image width,Image height
//add request to queue
requestQueue.add(imageRequest);

When you're using Volley, RequestQueue will queue your requests on worker thread and then delivers the response to main thread. The reason why you need it is that you are not allowed to perform network operations on the main thread if your application targeting the Honeycomb SDK or higher. Thus you will not get NetworkOnMainThreadException.

Related

How to access Volley response in another Class or Scope?

Hi there I am struggling to understand how exactly Volley request works. I have done similar things in NodeJs and the process seemed more intuitive.
String url = "http://my-json-feed";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//All I want is to use the response outside this scope
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
}
});
MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
//Example: How can I access the response here or in any other class?
In NodeJS this same process looks similar to this (with the help of node-fetch)
const response = await fetch(url);
const json = await response.json();
console.log(json);
And I can basically access json from anywhere in the same file or I can return it from the current function and use it anywhere where I call that function. I want to ask how can I do something similar in Java?

Volley string request returns random character

I'm new to HTTP requests.
In my app I want to send a simple GET request from my API, which I first test in an API tester, and the response looks like this.
and for now I want to print out the exact same response with my app, so I use a StringRequest from the Android Volley Library. Here's my code.
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.GET, TEST_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.println(Log.INFO, "SONGTUBEAPI", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.println(Log.ERROR, "SONGTUBEAPI", error.toString());
}
});
queue.add(stringRequest);
but now my response contains random characters.
2019-10-07 17:59:34.929 5140-5140/com.steven_wang.audioplayer I/SONGTUBEAPI: ������ftypdash��������iso6mp41����xmoov������lmvhd��������ØóíÜØóíÜ����¬D��¯������������������������������������������������������������������������������������������#������������������������������������������������������������������(mvex������ trex������������������������������������������������Ütrak������\tkhd������ØóíÜØóíÜ����������������¯��������������������������������������������������������������������������������������������#��������������������������xmdia������ mdhd��������ØóíÜØóíÜ����¬D��¯��Ç����������hdlr����������������soun������������������������ISO Media file produced by Google Inc. Created on: 05/04/2019.��������ñminf������$dinf������dref��������������������url ������������µstbl������istsd��������������������Ymp4a������������������������������������������¬D����������5esds��������'����#��������������������������������������������������������stts����������������������stsc����������������������stco����������������������stsz������������������������������smhd��������������������dsidx������������������¬D������������������������xä��¸����������w&��¸����������w'��¸����������vä��¸����������wl��¸����������vÕ��¸����������wZ��¸����������w!��¸����������w!��¸����������wG��¸����������w,��¸����������w:��¸����������w3��¸����������wA��¸����������v°��¸����������w¤��¸����������vð��¸����������w��¸����������wR��¸����������væ��¸����������w¦��¸����������v��¸����������wó��¸����������wm��¸����������v��¸����������vó��¸������������æ����T������������moof������mfhd��������������������traf������tfhd����*��������������������������������tfdt��������������������Ìtrun��������®���� ����s����t������������­����é����Ò����Ú����¹������������a����Q��������[����i��������|����������������v����²����;����p����2����H����J����P����e����c��������i����s����n��������Í��������{����j��������Y����X����U����f������������s����n����s��������H����8����R����P����Q��������g����h����Ú��������V����j������������¼����^����j����p����E����F����b����X��������ø����©������������Y����¢����T����N����a����H����Y����^����g������������f����s����e��������­����j����u��������V����p����b��������c������������u����W����|����h����¼����C����N����N����V����R����h����h����^��������b����h����j������������z����j����Y����Y����m��������g����c����É����ª��������j��������l����}����J����G����N����U����X����]��������a������������v����r����´����Ì��������j����a����e��������d����h����Z��������¦����c����i����Y��������M����F����p����Z����Q����c����a����q��������k����l����v����{��������¸����l����p����X����X����U����e����g����^����ó����È����l��������}����©����9����R����w����X����W��������S����h��������l����c����x��������à��������e����p����<����c����e����}����P��������������������r����U����r����I����Y����B����Y����h��������g����o����¬����f����s������������©����d����v����v����H����J����a����[����e����ö������������a����Y����}����X����S����P����V����n����f����\����v����Ï����c����w����h����k����©����³����B����m����H����\����h����f����k����o����î��������~��������N����¼����H����b����k����Y����a����_����W����b����Æ����l����j����W����l��������±����c����o����I����M����^����i����h����Ä����±����N����p��������c����­����C����p����T����_����]��������s����q����¡����b����{����d����{����Ð����\����l����d����Z����Z����c����\����k��������Ë����t����j����{��������Y����=����g����E����Z����S����`��������¯����[����V����h����s��������Ë����k����R���
What am I doing wrong? I tried fixing the encoding to utf-8 but the result is still the same.

Volley Request Tracking

I am using volley library for uploading images using Restful API
I made multiple image uploading request and add all these into RequestQueue.
when the request is completed I want to perform local db operation based on Request but
now the Question is how can I track the progress of each request
How can I know that which request is finished ?
How can I TAG the request ?
Any Way ?
Code :
StringRequest stringRequest = new StringRequest (Request.Method.POST, Constants.IMAGE_UPLOAD_URL,
new Response.Listener<String> ( ) {
#Override
public void onResponse(String s) {
Log.e (TAG, s.toString ( ));
}
},
new Response.ErrorListener ( ) {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Creating parameters
Map<String, String> params = new Hashtable<String, String> ( );
//Adding parameters
params.put ("file_contents", imageString);// image string
params.put ("file_name", filenameString);//profile image in name
return params;
}
};
stringRequest.setRetryPolicy (new DefaultRetryPolicy (DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
//Adding request to the queue
if (requestQueue==null)
requestQueue= Volley.newRequestQueue (this);
requestQueue.add (stringRequest);
}
Volley according to the documentation, is not good for long operations and this means that it's not suited for your need
you can extend the request type you're using and add a custom field and then write a RequestFilter that will find the next item according to the returned value of the response
Volley is not suitable for large download or streaming operations,
since Volley holds all responses in memory during parsing. For large
download operations, consider using an alternative like
DownloadManager.

How to make an asynchronous response a synchronous response (Java: Android Studio)

I'm quite new to using android studio. My question is, how do i change an asynchronous response into a synchronous response. I am currently using the volleyball library to return data from my database in JSON format.
The problem that I am experiencing is, representing that data into a graph format. You see, due to the structure of my code, the compiler waits for the response (essentially the data that is being sent from my database to android studio) but as its waiting, the compiler moves on to the other parts of the code which involves creating a graph and representing the data from my database into the graph.
But the graph is empty because it has not been fed any data, as we'r waiting for a response.
Here is the code:
private void sendRequest() {
System.out.println("Triggering send Request");
StringRequest stringRequest = new StringRequest(JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(BillReport.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
System.out.println("Send Request done");
}
The send request method is called before the implementation of the graph in the main method.
Bottom line is, I need to figure out how I can get an immediate response as opposed to waiting for a response.
Thank you for taking your time to read this post!
You will have to wait for the response to show the values in the graph. You can cache the data in volley and use it if the server data is not expected to change. You can have a progress bar that will rotate while the data is being retrieved. This is the standard practice.

Volley Request not working in this class, am I using it incorrectly?

Below is my class for handling http requests. I have tried the Volley Request in a new Android Project with no other code and the request is handled properly and I receive the result I expected. But for some reason when I use this code in my working project as a class, it doesn't return any response.
The way I call the request is:
HttpRequest request = new HttpRequest();
String url = "some-url";
String urlReturn = request.getFromURL(url, <ACTIVITY>.this);
where <ACTIVITY> is the activity I am calling the request from and "some-url" is a url that returns a string of data.
public class HttpRequest {
String response_test = "";
public String getFromURL (String url, Context context) {
RequestQueue requestQueue = Volley.newRequestQueue(context);
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("response1", response);
response_test = "1";
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Log.d("log2=", error.toString());
//requestQueue.stop();
}
});
// Add the request to the RequestQueue.
requestQueue.add(stringRequest);
requestQueue.start();
return response_test;
}
response_test never changes, so onResponse is never called. I thought there may be a timing issue, but when I add loop for it to wait until response_test is changed, it waits forever. Any idea what may be the issue? Anything I may have overlooked in how I'm calling this class?
Any help appreciated.
Volley is async library. It does work on another thread and when the call is ready it executes the code in onResponse. In the example you are returning imideately. Check your logcat for the messages they should be there

Categories