Volley - more than one request in the same Activity android - android

I want to send two different requests and handle two different responses in one Activity using Volley library.
My activity implements onResponseListener, so i have only one onResponse method and both responses are handled here. As they are completely same in structure i cant tell which is which.
How can i tell from which request i have received the response so i can handle them differently? Is there a way to "tag" a request or something like that?
I could set some kind of check variable, e.g. boolean firstRequestIsSent when i send the request, and then check it in the onResponse method, but its a pretty ugly solution.
Many thanks

Instead of implementing onResponse as part of the class, you can instantiate a new Response.Listener with the request. This way you will have a separate listener for each request.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener() {
#Override
public void onResponse(String response) {
// individual response here
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error here
}
});

Related

JsonObjectRequest Synchronisation?

I have to make several requests to an API for an Android App and I am having the following problem:
I have a list of items and I have to make a request for each in order to get some data and show it in the app. When my list's size is 1 (in case I have only one item), the app works perfectly but if I have more I get the data mixed and one item have the value of other and things like that.
I am using JsonObjectRequest and Volley. I use callback interfaces for sending back the request data to the activities. I think it's probably a synchronisation problem but I'm not sure and I'm a bit frustrated. I've tried everything!
Request Code:
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, urlMarket, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject singleResult;
singleResult = response.getJSONArray("result").getJSONObject(0);
coin.setHigh(singleResult.getDouble("High"));
coin.setLow(singleResult.getDouble("Low"));
coin.setLast(singleResult.getDouble("Last"));
coin.setVolInBtc(singleResult.getDouble("BaseVolume"));
coin.setBid(singleResult.getDouble("Bid"));
coin.setAsk(singleResult.getDouble("Ask"));
coin.setPrevDay(singleResult.getString("PrevDay"));
callback.onSuccess(coin);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
requestQueue.add(request);
Any kind of help would be appreciated!!
PD.: if there's a better way for doing that instead of JsonObjectRequest, please tell me!
Consider either of these two options:
Extend JSONObjectRequest that accepts a id/token field which is returned as part of the Success/Error callback.
Use a final field as an identifier before you make an API call. Assuming you are making these calls in a loop, you can then refer to this final field from your anonymous callbacks to identify the specific Stock. For example, you can use the ISIN, database ID or ticker symbol to identify the response.

How to handle the response of Volley in Android

I use volley in the Android Activity, and make a request and got the response, but I want to handle the response maybe in an another method,but it won't work, what should i do ?
public class TestActivity extends Activity {
RequestQueue queue;
private String result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String url = "www.google.com/something/I/need";
queue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Do something with the response
Log.i("resp", response);
// I want to do sth with the response out of here
// maybe like this, let result = response
// and see the log at the end of the code
// but it failed, what should I do?
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle error
Log.e("error", error.toString());
}
});
queue.add(stringRequest);
Log.e("result", result);
}
The Volley requests are asynchronous, so the program after sending the request, continues execution without waiting for the answer. So the code that processes the result is inserted into the OnResponse method. For more precise help explain why you would like to log out of the method OnResponse
Think about what you're doing: You're creating a StringRequest, then you add it to the request queue, but then you immediately try to check the result. Obviously, this won't work because the request hasn't been processed yet.
Your response will arrive in the onResponse method, and only then you'll be able to do something with it. You can set result = response here, but you'll only be able to see the value when the onResponse is called which could take some time.
Hope this clarifies things.

Rest Service Access inside fragment class

In my application i need to display the data in list view from rest service . I have gone through many samples but am not satisfied with that so can somebody help me ? Need sample or explanation . Thanks in advance!
In android you can use libraries to consuming REST
Volley
Retrofit
Your question is very general. Try one from above.
Sample use Volley:
in gradle: compile 'com.mcxiaoke.volley:library:1.0.19'
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";
// 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) {
// Display the first 500 characters of the response string.
mTextView.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mTextView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
you can call api in fragments.
if you are new to android,
1)first fetch the data from api with a asynctask(check android json parsing with url in learn2crack).
2)after step 1 you have your data to populate to your list,if you want to make a custom list the same site also gives an example for android custom list(learn2crack)
you can call json on asynctask class.
call the async task in onCrateView of your fragment

What is the best way to coordinate Volley requests

I'm trying to use Volley to execute multiple HTTP request where each one of them relies on the result of the previous one, what is the best option as a design?
1-Firing the next request in the onResponse callback of the previous request?
2-Writing some coordinator class that have callbacks that get called in the onResponse method of a request and fires the next request
skeleton code for the second option
coodrinator = new Coordinator();
JsonObjectRequest firstRequest = new JSONObjectRequest(Request.Method.GET,firstURL),new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//handle the responsee
coordinator.onFirstRequestRecieved();
}
},
errorListener);
private void doSecondRequest(){
JsonObjectRequest secondRequest = new JSONObjectRequest(Request.Method.GET,secondURL),new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//handle the responsee
coordinator.onSecondRequestRecieved();
}
},
errorListener);
}
private class Coordinator{
public void onFirstReequestRecieved(){
doSecondRequest();
}
public void onSecondRequestRecieved(){
//do Something
}
}
If first request response parameters are needed for making second request and so on then you can go for synchronous way. That can be achieved by making second request in onResponse on First request can there is no good or bad practise for it.
The thing is volley is asynchronous and request what is added in the queue execute without depending on other request and we are going to make it synchronous request and it can be achieved by many ways seeing your requirement.

How to make a synchronous GET request with volley library? And how to parse it afterwards?

I've seen answer to both of these questions, however, when I tried to put them together, I couldn't make it work. The problem itself is pretty simple: I want to get a string from one site and use it in a post request. That means I can only make the post request after I've finished parsing the GET request. The main ideas I'm using are these ones:
How to return response header field to main method using Google Volley for HTTP GET request in Android / Java?
Can I do a synchronous request with volley?
However the synchronous request is blocked and doesn't go on, and the first one is Async.
I believe this to be a simple thing to do, but still, I haven't be able to do it...
Thanks for any help!
Why not do something like this:
// send first request
requestQueue.add(firstRequest, null, new Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// ** code to parse response **
// send second request
requestQueue.add(secondRequest, null, new Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// ** code to parse response **
}
}, new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// ** code to handle errors **
}
}));
}
}, new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// ** code to handle errors **
}
}));

Categories

Resources