Volley priority doesn't work properly - android

I have to make two calls with volley. My problem is that I need to be done the first call and then the second. The calls are on a for loop. So I put on the first call Priority.IMMEDIATE and on the second Priority.LOW. But sometimes the second call is done before the first and I doesn't have the data that I need from the first call. What am I missing?
for (int i = 0; i < SiteData.getSites().size(); i++) {
firstCall();
secondCall();
}
the firstCall method
private void firstCall(){
JsonObjectRequest siteDataRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// do something with json
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(membership_id_tag, error.getMessage());
}
})
{
#Override
public Priority getPriority() {
return Priority.IMMEDIATE;
}
};
AppController.getInstance().addToRequestQueue(siteDataRequest, membership_id_tag);
}
the secondCall method
private void secondCall(){
JsonArrayRequest pagesRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
// do something with json
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(membership_page_tag, error.getMessage());
}
})
{
#Override
public Priority getPriority() {
return Priority.LOW;
}
};
AppController.getInstance().addToRequestQueue(pagesRequest, membership_page_tag);
}
Do I have to make the first call on a loop and the second on other?

Try doing the serving call in the response if the first, also the priority might be happening because there are 2 different request queue that are being used.

Related

Appending string at the end of url in GET method :Volley

I am working with volley library in my android app development.
I have a base url and I need to append some value at the end of the url,click here,
So, this value "ZGxb87HuJK" keeps changing dynamically in my program and need to append this value at the end of url. How to add this in params?
Use this way.
StringRequest strreq = new StringRequest(Request.Method.GET,
"https://sample.com/testing/" + Hear Your dynamic value,
new Response.Listener<String>() {
#Override
public void onResponse(String Response) {
// get response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError e) {
e.printStackTrace();
}
});
Volley.getInstance(this).addToRequestQueue(strreq);
String URL = "https://sample.com/testing/" + "dynamic value e.g ZGxb87HuJK";
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
URL, null,
new Response.Listener() {
#Override
public void onResponse(JSONObject response) {
//Success Callback
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Failure Callback
}
});
// Adding the request to the queue along with a unique string tag
MyApplication.getInstance().addToRequestQueue(jsonObjectReq, "getRequest");
Change your code like this

Volly: Implemetation of methods by following DRY principle

I need to call an api to get a json data using android volly. I have a method implemented inside class A to call the get request as shown
class A{
public static String getList(Context context,String url)
{
final String[] result = new String[1];
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e("response",response.toString());
result[0] =response.toString();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("responseerror",error.toString());
result[0] =error.toString();
}
});
MySingleton.getInstance(context).addToRequestQueue(req);
return result[0];
}
}
Inside class B i am accesing this method
class B {
String responce= A.getList(activity,url);
}
Here i can pass the context and url to get json data. But the problem is getList() method ruturs result even before it gets any response from the server. The app have more than one class which needs to call get request. If i will use this code snippet inside every such class then it will be against DRY principle. So what is the proper procudure to follow in this scenario?
Use an interface like below.
class A {
private final WeakReference<ResponseListener> responseListenerWeakRef;
public A(ResponseListener responseListener) {
responseListenerWeakRef = new WeakReference<ResponseListener>(responseListener);
}
public String getList(Context context, String url) {
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e("response",response.toString());
if (responseListener!=null && responseListener.get()!=null) {
responseListener.get().onResponse(response.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("responseerror",error.toString());
if (responseListener!=null && responseListener.get()!=null) {
responseListener.get().onResponse(error.toString());
}
}
}
);
MySingleton.getInstance(context).addToRequestQueue(req);
}
public interface ResponseListener {
void onResponse(String response);
}
}
class B implements A.ResponseListener {
private void makeApiCall() {
new A(this).getList(activity, url);
}
#Override
public void onResponse(String response) {
// Do something with the response.
}
}

how to return from doInBackground only after the the thread inside it is finished

I started a Volley JsonObject Request from asynctak and i want to return from doinBackground after the volley request is completed. I know it return from the doInBackground after it successfully started the thread. But how do i return after the Volley Thread is finished!
In this code I am getting a null value of Weather object. All the functions are working correctly.
Code:
#Override
protected JSONObject doInBackground(Void... voids) {
String url=getURL();
final JSONObject[] mJsonWeather = {null};
JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
mJsonWeather[0]=response;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("Error","can't process json result");
}
});
MySingleton.getInstance(mContext.getApplicationContext()).addToRequestQue(jsonObjectRequest);
return mJsonWeather[0];
}
#Override
protected void onPostExecute(JSONObject jsonObjectWeather) {
super.onPostExecute(jsonObjectWeather);
Weather weather = getJsonWeatherData(jsonObjectWeather);
setWeatherobj(weather);
}
I think you've misunderstood something about the async part of AsyncTask. It means it runs asynchronously
Sure your code will run, but while Volley is running in a separate thread, you've gone ahead to return mJsonWeather[0];, which is null.
No AsyncTask needed. Call this section of code directly in the Activity
EDIT "Clean code"
// Can define this wherever
Response.Listener<JSONObject> dataListener = new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Weather weather = getJsonWeatherData(response);
setWeatherobj(weather);
}
};
// This error listener is almost always the same, anyway, right?
Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("Error","can't process json result");
}
}
JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, url,
null, // Data
dataListener, // onSuccess
errorListener // onError
);
MySingleton.getInstance(getApplicationContext())
.addToRequestQue(jsonObjectRequest); // Some RequestQueue
AsyncTask return results of operation in .onPostExecute() method. You should get result from there ( it is executed on main thread)
Volley already implements a separate thread for do the request. You can define a onPostExecute (a callback) and do it when the volley request is finished. For insance:
public void doRequest() {
String url=getURL();
final JSONObject[] mJsonWeather = {null};
JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
mJsonWeather[0]=response;
Weather weather = getJsonWeatherData(jsonObjectWeather);
setWeatherobj(weather);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("Error","can't process json result");
}
});
MySingleton.getInstance(mContext.getApplicationContext()).addToRequestQue(jsonObjectRequest);
return mJsonWeather[0];
}

Simultaneous volley request always returns Server error

I am trying to develop an android application in which I am hitting the server with an API using volley. I have made a singleton RequestQueue object and sending multiple JSON request one after other. When I send the first request, I receive the JSON object without any error. I am then parsing the JSON, extracting some ids and again making a url and making a volley request. This time, I am always getting "com.android.volley.ServerError". Below is my code:
JsonObjectRequest jReq = new JsonObjectRequest(Request.Method.GET, url, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
final VolleyParser vp = new VolleyParser();
ArrayList<Integer> searchIds = vp.parseJSONObject(jsonObject, kf, null);
r.cancelAll("saz");
for(Integer id : searchIds) {
final Fetch pf = new ProductFetch();
String url = pf.searchURL(id.toString());
JsonObjectRequest jReqNext = new JsonObjectRequest(Request.Method.GET, url, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonArray) {
Log.i("saz", "product rec");
vp.parseJSONObject(jsonArray, pf, null);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.i("saz", "pro "+volleyError.toString());
}
});
/**//*(Request.Method.POST, url, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Log.i("saz","product rec");
vp.parseJSONObject(jsonObject, pf, null);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.i("saz", volleyError.toString());
}
});*/
jReqNext.setRetryPolicy(new DefaultRetryPolicy(
9000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
r.add(jReqNext);
}
}}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.i("saz", "Search "+volleyError.toString());
}
});
r.add(jReq);
}
Please give more explanation what the server error is but it looks like that you are getting the Volley Server Timeout error. Please increase the request timeout to one min and see the results. Increase the timeout as
yourRequest.setRetryPolicy(new DefaultRetryPolicy(60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

Android: how to do a simple POST request with Volley, without expected result?

I want to send a POST request to my server, and there is no expected data for the result (just HTTP status code - standard behavior). How can I do that ?
(abstract base Request class (Volley) wants a result type)
try {
mRequest =
new XXXXXX(
Request.Method.POST,
url,
null, null,
new Response.Listener() {
#Override
public void onResponse() {
// ok
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError e) {
// ko
}
},
null
);
return mRestCoreVolley.addToRequestQueue(mRequest);
} catch (Exception e) {
// error
}
You could try something like in the code below for the response listener:
new Response.Listener<Void>() {
#Override
public void onResponse(Void response) {
}
}
I guess your code is right. You can use a String like:
RequestQueue rq = Volley.newRequestQueue(this);
StringRequest postReq = new StringRequest(Request.Method.POST,
your_url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// do nothing
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle error
}
}) ;
Hope it helps you!

Categories

Resources