Android volley DefaultRetryPolicy do not work as intended - android

So, I have this Volley PUT request:
private boolean syncCall(JSONObject jsonObject, final VolleyCallback
callback) {
final ProgressDialog progDailog = new ProgressDialog(context);
final Boolean[] success = {false};
progDailog.setMessage("...");
progDailog.setIndeterminate(false);
progDailog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progDailog.setCancelable(false);
progDailog.show();
final SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
RequestQueue queue = Volley.newRequestQueue(context, new HurlStack());
final String token = prefs.getString("token", null);
String URL = Constants.getUrlSync();
String param1 = String.valueOf(prefs.getInt("pmp", 1));
String param2 = String.valueOf(prefs.getInt("ei", 1));
URL = URL.replace("[x]", param1);
URL = URL.replace("[y]", param2);
//pegar id pmp e IE corretas
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request
.Method.PUT, URL, jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
callback.onSuccess(response + "");
success[0] = true;
progDailog.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
callback.onFailure(error);
tokenFailure(error);
success[0] = false;
progDailog.dismiss();
}
}) {
#Override
public Map<String, String> getHeaders() throws
AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Token", token);
return headers;
}
};
int socketTimeout = 30000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
jsObjRequest.setRetryPolicy(policy);
queue.add(jsObjRequest);
return success[0];
}
My problem is that I send a very large JSON, so the default timeout of 5 seconds is not enough. So, I tried to increase the timeout to 30 seconds and messing with the DefaultRetryPolicy to increase the number of retries.
The thing is, it keeps timeouting in 5s and it doesn't even retry once!
Do I have to have a listener or a callback for the retries ? I'm doing something wrong with the DefaultRetryPolicy ? Please help, this issue is driving me nuts...

Do you need to use the DefaultRetryPolicy?
Because you could define your own.
Instead of this:
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
Try this:
jsObjRequest.setRetryPolicy(new RetryPolicy() {
#Override
public int getCurrentTimeout() {
// Here goes the new timeout
return mySeconds;
}
#Override
public int getCurrentRetryCount() {
// The max number of attempts
return myAttempts;
}
#Override
public void retry(VolleyError error) throws VolleyError {
// Here you could check if the retry count has gotten
// To the max number, and if so, send a VolleyError msg
// or something
}
});

I'm not sure exactly why the retry time doesn't work on your code, I did find a similar issue here though.
Instead, I can tell you some things that I don't believe to be ok in your code and suggest you to adopt my model of Volley use.
First of all, you're creating a new request queue for every request you're making. That's not cool, you should have a RequestManager singleton that holds one request queue and use that.
Second of all, I don't know if this is what affects the retry time, I have a base request class and set the retry time in the constructor. Then, I extend this class whenever I have to implement a new type of request. Then, I create an instance of the request, set the callbacks, and pass it to the request manager. The request manager adds it to the one request queue I was talking about.
More over, if you don't already, I suggest you use the Gson library to parse the JSON objects.
This is my base request class I'm using:
/**
* Created by Daniel on 2/6/2016.
*/
public class GsonRequest<T> extends Request<T> {
protected Context context;
protected final Gson gson = new Gson();
protected final Class<T> clazz;
protected final TypeToken typeToken;
protected Map<String, String> headers;
protected Map<String, String> params;
protected final Response.Listener<T> listener;
/**
* Make a GET request and return a parsed object from JSON.
*
* #param url URL of the request to make
* #param clazz Relevant class object, for Gson's reflection
*/
public GsonRequest(final Context context, final int requestMethod, String url, Class<T> clazz, Response.Listener<T> listener, Response.ErrorListener errorListener) {
super(requestMethod, url, errorListener);
this.context = context;
this.clazz = clazz;
this.listener = listener;
this.headers = new HashMap<>();
typeToken = null;
setRetryPolicy();
}
/**
* Make a GET request and return a parsed object from JSON.
*
* #param url URL of the request to make
* #param typeToken Relevant typeToken object, for Gson's reflection
*/
public GsonRequest(final Context context, final int requestMethod, String url, TypeToken typeToken, Response.Listener<T> listener, Response.ErrorListener errorListener) {
super(requestMethod, url, errorListener);
this.context = context;
this.typeToken = typeToken;
this.listener = listener;
this.headers = new HashMap<>();
clazz = null;
setRetryPolicy();
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return params != null ? params : super.getParams();
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
//TODO add headers here
return headers;
}
#Override
protected void deliverResponse(T response) {
listener.onResponse(response);
}
#Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
JSONObject jsonObject = new JSONObject(json);
if (clazz != null) {
return Response.success(gson.fromJson(json, clazz), HttpHeaderParser.parseCacheHeaders(response));
} else {
return Response.success((T) gson.fromJson(json, typeToken.getType()), HttpHeaderParser.parseCacheHeaders(response));
}
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
} catch (JSONException e) {
return Response.error(new ParseError(e));
}
}
protected void setRetryPolicy() {
//TODO set your retry policy here
setRetryPolicy(new DefaultRetryPolicy(
30000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
}`enter code here`
This works like a charm for me. Hope it helps, if you need any further help, contact me

Related

Request Raw Data with Volley [duplicate]

I saw Google IO 2013 session about Volley and I'm considering switching to volley. Does Volley support adding POST/GET parameters to request? If yes, how can I do it?
For the GET parameters there are two alternatives:
First: As suggested in a comment bellow the question you can just use String and replace the parameters placeholders with their values like:
String uri = String.format("http://somesite.com/some_endpoint.php?param1=%1$s&param2=%2$s",
num1,
num2);
StringRequest myReq = new StringRequest(Method.GET,
uri,
createMyReqSuccessListener(),
createMyReqErrorListener());
queue.add(myReq);
where num1 and num2 are String variables that contain your values.
Second: If you are using newer external HttpClient (4.2.x for example) you can use URIBuilder to build your Uri. Advantage is that if your uri string already has parameters in it it will be easier to pass it to the URIBuilder and then use ub.setQuery(URLEncodedUtils.format(getGetParams(), "UTF-8")); to add your additional parameters. That way you will not bother to check if "?" is already added to the uri or to miss some & thus eliminating a source for potential errors.
For the POST parameters probably sometimes will be easier than the accepted answer to do it like:
StringRequest myReq = new StringRequest(Method.POST,
"http://somesite.com/some_endpoint.php",
createMyReqSuccessListener(),
createMyReqErrorListener()) {
protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("param1", num1);
params.put("param2", num2);
return params;
};
};
queue.add(myReq);
e.g. to just override the getParams() method.
You can find a working example (along with many other basic Volley examples) in the Andorid Volley Examples project.
In your Request class (that extends Request), override the getParams() method. You would do the same for headers, just override getHeaders().
If you look at PostWithBody class in TestRequest.java in Volley tests, you'll find an example.
It goes something like this
public class LoginRequest extends Request<String> {
// ... other methods go here
private Map<String, String> mParams;
public LoginRequest(String param1, String param2, Listener<String> listener, ErrorListener errorListener) {
super(Method.POST, "http://test.url", errorListener);
mListener = listener;
mParams = new HashMap<String, String>();
mParams.put("paramOne", param1);
mParams.put("paramTwo", param2);
}
#Override
public Map<String, String> getParams() {
return mParams;
}
}
Evan Charlton was kind enough to make a quick example project to show us how to use volley.
https://github.com/evancharlton/folly/
CustomRequest is a way to solve the Volley's JSONObjectRequest can't post parameters like the StringRequest
here is the helper class which allow to add params:
import java.io.UnsupportedEncodingException;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
public class CustomRequest extends Request<JSONObject> {
private Listener<JSONObject> listener;
private Map<String, String> params;
public CustomRequest(String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
public CustomRequest(int method, String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
protected Map<String, String> getParams()
throws com.android.volley.AuthFailureError {
return params;
};
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
#Override
protected void deliverResponse(JSONObject response) {
// TODO Auto-generated method stub
listener.onResponse(response);
}
}
thanks to Greenchiu
This helper class manages parameters for GET and POST requests:
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
public class CustomRequest extends Request<JSONObject> {
private int mMethod;
private String mUrl;
private Map<String, String> mParams;
private Listener<JSONObject> mListener;
public CustomRequest(int method, String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(method, url, errorListener);
this.mMethod = method;
this.mUrl = url;
this.mParams = params;
this.mListener = reponseListener;
}
#Override
public String getUrl() {
if(mMethod == Request.Method.GET) {
if(mParams != null) {
StringBuilder stringBuilder = new StringBuilder(mUrl);
Iterator<Map.Entry<String, String>> iterator = mParams.entrySet().iterator();
int i = 1;
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
if (i == 1) {
stringBuilder.append("?" + entry.getKey() + "=" + entry.getValue());
} else {
stringBuilder.append("&" + entry.getKey() + "=" + entry.getValue());
}
iterator.remove(); // avoids a ConcurrentModificationException
i++;
}
mUrl = stringBuilder.toString();
}
}
return mUrl;
}
#Override
protected Map<String, String> getParams()
throws com.android.volley.AuthFailureError {
return mParams;
};
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
#Override
protected void deliverResponse(JSONObject response) {
// TODO Auto-generated method stub
mListener.onResponse(response);
}
}
Dealing with GET parameters I iterated on Andrea Motto' solution.
The problem was that Volley called GetUrl several times and his solution, using an Iterator, destroyed original Map object. The subsequent Volley internal calls had an empty params object.
I added also the encode of parameters.
This is an inline usage (no subclass).
public void GET(String url, Map<String, String> params, Response.Listener<String> response_listener, Response.ErrorListener error_listener, String API_KEY, String stringRequestTag) {
final Map<String, String> mParams = params;
final String mAPI_KEY = API_KEY;
final String mUrl = url;
StringRequest stringRequest = new StringRequest(
Request.Method.GET,
mUrl,
response_listener,
error_listener
) {
#Override
protected Map<String, String> getParams() {
return mParams;
}
#Override
public String getUrl() {
StringBuilder stringBuilder = new StringBuilder(mUrl);
int i = 1;
for (Map.Entry<String,String> entry: mParams.entrySet()) {
String key;
String value;
try {
key = URLEncoder.encode(entry.getKey(), "UTF-8");
value = URLEncoder.encode(entry.getValue(), "UTF-8");
if(i == 1) {
stringBuilder.append("?" + key + "=" + value);
} else {
stringBuilder.append("&" + key + "=" + value);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
String url = stringBuilder.toString();
return url;
}
#Override
public Map<String, String> getHeaders() {
Map<String, String> headers = new HashMap<>();
if (!(mAPI_KEY.equals(""))) {
headers.put("X-API-KEY", mAPI_KEY);
}
return headers;
}
};
if (stringRequestTag != null) {
stringRequest.setTag(stringRequestTag);
}
mRequestQueue.add(stringRequest);
}
This function uses headers to pass an APIKEY and sets a TAG to the request useful to cancel it before its completion.
Hope this helps.
This may help you...
private void loggedInToMainPage(final String emailName, final String passwordName) {
String tag_string_req = "req_login";
StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://localhost/index", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
try {
JSONObject jsonObject = new JSONObject(response);
Boolean error = jsonObject.getBoolean("error");
if (!error) {
String uid = jsonObject.getString("uid");
JSONObject user = jsonObject.getJSONObject("user");
String email = user.getString("email");
String password = user.getString("password");
session.setLogin(true);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
Toast.makeText(getApplicationContext(), "its ok", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
System.out.println("volley Error .................");
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "login");
params.put("email", emailName);
params.put("password", passwordName);
return params;
}
};
MyApplication.getInstance().addToRequestQueue(stringRequest,tag_string_req);
}
For Future Readers
I love to work with Volley. To save development time i tried to write small handy library Gloxey Netwok Manager to setup Volley with my project. It includes JSON parser and different other methods that helps to check network availability.
Use ConnectionManager.class in which different methods for Volley String and Volley JSON request are available.
You can make requests of GET, PUT, POST, DELETE with or without header. You can read full documentation here.
Just put this line in your gradle file.
dependencies {
compile 'io.gloxey.gnm:network-manager:1.0.1'
}
Volley StringRequest
Method GET (without header)
ConnectionManager.volleyStringRequest(context, isDialog, progressDialogView, requestURL, volleyResponseInterface);
How to use?
Configuration Description
Context Context
isDialog If true dialog will appear, otherwise not.
progressView For custom progress view supply your progress view id and make isDialog true. otherwise pass null.
requestURL Pass your API URL.
volleyResponseInterface Callback for response.
Example
ConnectionManager.volleyStringRequest(this, false, null, "url", new VolleyResponse() {
#Override
public void onResponse(String _response) {
/**
* Handle Response
*/
}
#Override
public void onErrorResponse(VolleyError error) {
/**
* handle Volley Error
*/
}
#Override
public void isNetwork(boolean connected) {
/**
* True if internet is connected otherwise false
*/
}
});
Volley StringRequest
Method POST/PUT/DELETE (without header)
ConnectionManager.volleyStringRequest(context, isDialog, progressDialogView, requestURL, requestMethod, params, volleyResponseInterface);
Example
Use Method : Request.Method.POST
Request.Method.PUT
Request.Method.DELETE
Your params :
HashMap<String, String> params = new HashMap<>();
params.put("param 1", "value");
params.put("param 2", "value");
ConnectionManager.volleyStringRequest(this, true, null, "url", Request.Method.POST, params, new VolleyResponse() {
#Override
public void onResponse(String _response) {
/**
* Handle Response
*/
}
#Override
public void onErrorResponse(VolleyError error) {
/**
* handle Volley Error
*/
}
#Override
public void isNetwork(boolean connected) {
/**
* True if internet is connected otherwise false
*/
}
});
Bonus
Gloxey JSON Parser
Feel free to use gloxey json parser to parse your api response.
YourModel yourModel = GloxeyJsonParser.getInstance().parse(stringResponse, YourModel.class);
Example
ConnectionManager.volleyStringRequest(this, false, null, "url", new VolleyResponse() {
#Override
public void onResponse(String _response) {
/**
* Handle Response
*/
try {
YourModel yourModel = GloxeyJsonParser.getInstance().parse(_response, YourModel.class);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onErrorResponse(VolleyError error) {
/**
* handle Volley Error
*/
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
showSnackBar(parentLayout, getString(R.string.internet_not_found), getString(R.string.retry), new View.OnClickListener() {
#Override
public void onClick(View view) {
//handle retry button
}
});
} else if (error instanceof AuthFailureError) {
} else if (error instanceof ServerError) {
} else if (error instanceof NetworkError) {
} else if (error instanceof ParseError) {
}
}
#Override
public void isNetwork(boolean connected) {
/**
* True if internet is connected otherwise false
*/
if (!connected) {
showSnackBar(parentLayout, getString(R.string.internet_not_found), getString(R.string.retry), new View.OnClickListener() {
#Override
public void onClick(View view) {
//Handle retry button
}
});
}
});
public void showSnackBar(View view, String message) {
Snackbar.make(view, message, Snackbar.LENGTH_LONG).show();
}
public void showSnackBar(View view, String message, String actionText, View.OnClickListener onClickListener) {
Snackbar.make(view, message, Snackbar.LENGTH_LONG).setAction(actionText, onClickListener).show();
}
To provide POST parameter send your parameter as JSONObject in to the JsonObjectRequest constructor. 3rd parameter accepts a JSONObject that is used in Request body.
JSONObject paramJson = new JSONObject();
paramJson.put("key1", "value1");
paramJson.put("key2", "value2");
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,url,paramJson,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);

I am creating roomdatabase object in in intentservice which has its worker threak according to me then too Room gives me an error saying

"Cannot access database on the main thread since it may potentially lock the UI for a long period of time" but
when i allow room to execute queries on main thread then it doesn't give error
// MyIntentService.java:
public class MyIntentService extends IntentService {
String URL = "http://192.168.1.102/android/Document%20Sharing/getServerData.php";
String course;
AppDatabase appDatabase;
public MyIntentService() { super("MyIntentService"); }
#Override
public void onCreate() {
Log.i("tagg","onCreate");
super.onCreate();
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
appDatabase = AppDatabase.getAppDatabase(this);
course = intent.getStringExtra("course");
getServerData();
Log.i("tagg","onHandleIntentBefore");
}
private void getServerData() {
Log.i("tagg","here");
final RequestQueue requestQueue = Volley.newRequestQueue(this);
final StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Gson gson = new Gson();
IT_Subjects[] itSubjects = gson.fromJson(response, IT_Subjects[].class);
appDatabase.itSubjectsDao().insertAll(itSubjects);
//Log.i("tagg", response);
Log.i("tagg","here");
requestQueue.stop();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Toast.makeText(MyIntentService.this, error.toString(), Toast.LENGTH_LONG).show();
requestQueue.stop();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> prams = new HashMap<>();
prams.put("course", course);
return prams;
}
};
requestQueue.add(stringRequest);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
Log.i("tagg","onStartCommand");
return super.onStartCommand(intent,flags,startId);
}
#Override
public void onDestroy() {
Log.i("tagg","onDestroy");
AppDatabase.destroyInstance();
super.onDestroy();
}
}
//AppDatabase.java
#Database(entities = IT_Subjects.class, version = 1 )
public abstract class AppDatabase extends RoomDatabase {
public abstract IT_SubjectsDao itSubjectsDao();
private static AppDatabase INSTANCE;
public static AppDatabase getAppDatabase(Context context) {
if (INSTANCE == null) {
INSTANCE =
Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, "IT_Students")
.build();
}
return INSTANCE;
}
public static void destroyInstance() {
INSTANCE = null;
}
}
You enqueue a request - the request is processed asynchronously, so onHandleIntent returns immediately. (Then onDestroy is called and your cached static database instance lost!) Then onResponse is called on the main thread and data written to appDatabase.
requestQueue.add(stringRequest);
When you call add(), Volley runs one cache processing thread and a pool of network dispatch threads. When you add a request to the queue, it is picked up by the cache thread and triaged: if the request can be serviced from cache, the cached response is parsed on the cache thread and the parsed response is delivered on the main thread. If the request cannot be serviced from cache, it is placed on the network queue. The first available network thread takes the request from the queue, performs the HTTP transaction, parses the response on the worker thread, writes the response to cache, and posts the parsed response back to the main thread for delivery.
Source Send a simple request | Android Developers, emphasis mine.
A naïve workaround would be to execute the request synchronously (or enqueue it and await result). This has been explained in this answer (I didn't verify it so take it with a pinch of salt).
RequestFuture<JSONObject> future = RequestFuture.newFuture();
JsonObjectRequest request = new JsonObjectRequest(URL, new
JSONObject(), future, future);
requestQueue.add(request);
JSONObject response = future.get(); // this will block
A better approach might be to not use IntentService at all. Volley already does what you need - do the network stuff on worker thread, deliver the result to main thread, and even process the raw response on worker thread between those two.
You should create a custom Request class and override parseNetworkResponse as best described here: Implementing a custom request | Android Developers
Here's an example implementation of GsonRequest copied verbatim from the link above. It's not super efficient but should be good to start with.
public class GsonRequest<T> extends Request<T> {
private final Gson gson = new Gson();
private final Class<T> clazz;
private final Map<String, String> headers;
private final Listener<T> listener;
/**
* Make a GET request and return a parsed object from JSON.
*
* #param url URL of the request to make
* #param clazz Relevant class object, for Gson's reflection
* #param headers Map of request headers
*/
public GsonRequest(String url, Class<T> clazz, Map<String, String> headers,
Listener<T> listener, ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.clazz = clazz;
this.headers = headers;
this.listener = listener;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers != null ? headers : super.getHeaders();
}
#Override
protected void deliverResponse(T response) {
listener.onResponse(response);
}
#Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
String json = new String(
response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(
gson.fromJson(json, clazz),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
}
}
}

Android volley implementing custom request with getParams that accepts JSONArray param

I am using Google's Volley to make GET and POST requests using the following custom request class:
public class GsonRequest<T> extends Request<T> {
private static final int SOCKET_TIMEOUT_MS = 30000;
private static final int MAX_RETRIES = 3;
private final Gson gson = new Gson();
private final Type type;
private final Map<String, String> params;
private final Response.Listener<T> listener;
/**
* Make a GET request and return a parsed object from JSON.
*
* #param url URL of the request to make
* #param type Relevant type object, for Gson's reflection
* #param params Map of request params
*/
public GsonRequest(int method, String url, Type type, Map<String, String> params,
Response.Listener<T> listener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.type = type;
this.params = params;
this.listener = listener;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers;
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
// Here is my question, can I add a param value as JSONArray? like this:
params.put("orderValue", "35");
params.put("price", ""price": ["13.00", "22.00"]");
return params != null ? params : super.getParams();
}
#Override
public Request<?> setRetryPolicy(RetryPolicy retryPolicy) {
final RetryPolicy policy = new DefaultRetryPolicy(SOCKET_TIMEOUT_MS, MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
return super.setRetryPolicy(policy);
}
#Override
public String getBodyContentType() {
return "application/json";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
Log.i("" + gson.toJson(params).getBytes("utf-8"));
return gson.toJson(params).getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", gson.toJson(params), "utf-8");
return super.getBody();
}
}
#Override
protected void deliverResponse(T response) {
listener.onResponse(response);
}
#Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
final String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return (Response<T>) Response.success(gson.fromJson(json, type), HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
}
}
}
The Json I'm trying to send:
{
"orderValue": "35",
"price": [
"13.00",
"22.00"
]
}
What is really sent as I get from getBody() method log is:
{
"price": "[\"23.00\",\"55.00\"]",
"orderValue": "35"
}
Any help with this issue?
You need change extends Request to ** JsonObjectRequest** or create JSONArrayRequest object.
public class VolleyJSONObjectRequest extends JsonObjectRequest {
private Context context;
private int timeOut = 10000;
private int maxRetries = 1;
public VolleyJSONObjectRequest(int method, Context context, String url, JSONObject jsonObject, Listener<JSONObject> listener, ErrorListener errorListener) {
super(method, url, jsonObject, listener, errorListener);
super.setRetryPolicy(new DefaultRetryPolicy(timeOut, maxRetries, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
public void startRequest() {
VolleyHandler.get(context).addToRequestQueue(this);
}
}
Example method:
private void saveItems(){
if (itens != null && itens.size() > 0) {
try {
JSONArray itensJson = new JSONArray();
for (SalesOrderItem item : itens) { // your loop
JSONObject jsonObject = new JSONObject();
jsonObject.put("price", this.priceOne);
jsonObject.put("price", this.priceTwo);
itensJson.put(jsonObject);
}
JSONObject headerJSON = new JSONObject();
headerJSON.put("price", itensJson);
VolleyJSONObjectRequest request = new VolleyJSONObjectRequest(Request.Method.POST, context, context.getString(R.string.URL_SALES_ORDER_ITENS_INSERT), headerJSON, onResponseItem, onErrorResponseItem);
request.startRequest();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
request = new VolleyStringRequest(context, context.getString(R.string.URL_FINISH_SALES_ORDER_DRAFT), onResponseFinishSalesOrderDraft, onErrorResponseFinishSalesOrderDraft);
request.startRequest();

how to make post call with custom object using volley in android

am new to android can any one answer for this question please, i tried alot but didn't find correct stuff.i want to send a my custom user object to spring rest service
Employee Object:
in android and spring
public class Employee{
String firstname;
String lastname;
//setters and getter goes here
}
GsonRequest:
public class GsonRequest<T> extends Request<T> {
public final Gson gson = new Gson();
private final Class<T> clazz;
private final Map<String, String> headers;
private final Response.Listener<T> listener;
private final Object dataIn;
/**
* Make a GET request and return a parsed object from JSON.
*
* #param url URL of the request to make
* #param clazz Relevant class object, for Gson's reflection
* #param headers Map of request headers
*/
public GsonRequest(String url, Class<T> clazz, Map<String, String> headers,
Response.Listener<T> listener, Response.ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.clazz = clazz;
this.headers = headers;
this.listener = listener;
this.dataIn = null;
}
public GsonRequest(String url, Object dataIn, Class<T> clazz, Map<String, String> headers,
Response.Listener<T> listener, Response.ErrorListener errorListener) {
super(Method.POST, url, errorListener);
this.dataIn = dataIn;
this.clazz = clazz;
this.headers = headers;
this.listener = listener;
}
#Override
public byte[] getBody() throws AuthFailureError {
return gson.toJson(dataIn).getBytes();
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers != null ? headers : super.getHeaders();
}
#Override
protected void deliverResponse(T response) {
listener.onResponse(response);
}
#Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
String json = new String(
response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(
gson.fromJson(json, clazz),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}
}
Main Activity:
public class MainActivity extends AppCompatActivity {
Button clickbtn;
TextView resText;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
clickbtn=(Button)findViewById(R.id.mybutton);
resText=(TextView)findViewById(R.id.mytext);
clickbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Employee emp=new Employee();
emp.setFirstname("naresh");
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
GsonRequest<Employee> myReq = new GsonRequest<Employee>("http://192.168.10.37:8088/adduser",
emp,
Employee.class,
new HashMap<String, String>(),
new Response.Listener<Employee>() {
#Override
public void onResponse(Employee response) {
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"error", Toast.LENGTH_SHORT).show();
Log.i("post error","post error",error);
resText.setText(error.getMessage());
Log.d("post error","post error",error);
}
});
queue.add(myReq);
}
});
}
}
spring rest service:
#RequestMapping("adduser")
public void addUser(#Requestbody User user){
Sysetm.out.println(user.getFirstname());
}
Exception:
at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:112)
E/Volley: [216] BasicNetwork.performRequest: Unexpected response code 415 for http://192.168.10.37:8088/adduser
I/post error: post error
com.android.volley.ServerError
at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:163)
at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:112)
D/post error: post error
com.android.volley.ServerError
at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:163)
at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:112)
As my comment, please add headers.put("Content-Type", "application/json; charset=utf-8"); inside getHeaders().

Volley - POST/GET parameters

I saw Google IO 2013 session about Volley and I'm considering switching to volley. Does Volley support adding POST/GET parameters to request? If yes, how can I do it?
For the GET parameters there are two alternatives:
First: As suggested in a comment bellow the question you can just use String and replace the parameters placeholders with their values like:
String uri = String.format("http://somesite.com/some_endpoint.php?param1=%1$s&param2=%2$s",
num1,
num2);
StringRequest myReq = new StringRequest(Method.GET,
uri,
createMyReqSuccessListener(),
createMyReqErrorListener());
queue.add(myReq);
where num1 and num2 are String variables that contain your values.
Second: If you are using newer external HttpClient (4.2.x for example) you can use URIBuilder to build your Uri. Advantage is that if your uri string already has parameters in it it will be easier to pass it to the URIBuilder and then use ub.setQuery(URLEncodedUtils.format(getGetParams(), "UTF-8")); to add your additional parameters. That way you will not bother to check if "?" is already added to the uri or to miss some & thus eliminating a source for potential errors.
For the POST parameters probably sometimes will be easier than the accepted answer to do it like:
StringRequest myReq = new StringRequest(Method.POST,
"http://somesite.com/some_endpoint.php",
createMyReqSuccessListener(),
createMyReqErrorListener()) {
protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("param1", num1);
params.put("param2", num2);
return params;
};
};
queue.add(myReq);
e.g. to just override the getParams() method.
You can find a working example (along with many other basic Volley examples) in the Andorid Volley Examples project.
In your Request class (that extends Request), override the getParams() method. You would do the same for headers, just override getHeaders().
If you look at PostWithBody class in TestRequest.java in Volley tests, you'll find an example.
It goes something like this
public class LoginRequest extends Request<String> {
// ... other methods go here
private Map<String, String> mParams;
public LoginRequest(String param1, String param2, Listener<String> listener, ErrorListener errorListener) {
super(Method.POST, "http://test.url", errorListener);
mListener = listener;
mParams = new HashMap<String, String>();
mParams.put("paramOne", param1);
mParams.put("paramTwo", param2);
}
#Override
public Map<String, String> getParams() {
return mParams;
}
}
Evan Charlton was kind enough to make a quick example project to show us how to use volley.
https://github.com/evancharlton/folly/
CustomRequest is a way to solve the Volley's JSONObjectRequest can't post parameters like the StringRequest
here is the helper class which allow to add params:
import java.io.UnsupportedEncodingException;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
public class CustomRequest extends Request<JSONObject> {
private Listener<JSONObject> listener;
private Map<String, String> params;
public CustomRequest(String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
public CustomRequest(int method, String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
protected Map<String, String> getParams()
throws com.android.volley.AuthFailureError {
return params;
};
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
#Override
protected void deliverResponse(JSONObject response) {
// TODO Auto-generated method stub
listener.onResponse(response);
}
}
thanks to Greenchiu
This helper class manages parameters for GET and POST requests:
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
public class CustomRequest extends Request<JSONObject> {
private int mMethod;
private String mUrl;
private Map<String, String> mParams;
private Listener<JSONObject> mListener;
public CustomRequest(int method, String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(method, url, errorListener);
this.mMethod = method;
this.mUrl = url;
this.mParams = params;
this.mListener = reponseListener;
}
#Override
public String getUrl() {
if(mMethod == Request.Method.GET) {
if(mParams != null) {
StringBuilder stringBuilder = new StringBuilder(mUrl);
Iterator<Map.Entry<String, String>> iterator = mParams.entrySet().iterator();
int i = 1;
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
if (i == 1) {
stringBuilder.append("?" + entry.getKey() + "=" + entry.getValue());
} else {
stringBuilder.append("&" + entry.getKey() + "=" + entry.getValue());
}
iterator.remove(); // avoids a ConcurrentModificationException
i++;
}
mUrl = stringBuilder.toString();
}
}
return mUrl;
}
#Override
protected Map<String, String> getParams()
throws com.android.volley.AuthFailureError {
return mParams;
};
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
#Override
protected void deliverResponse(JSONObject response) {
// TODO Auto-generated method stub
mListener.onResponse(response);
}
}
Dealing with GET parameters I iterated on Andrea Motto' solution.
The problem was that Volley called GetUrl several times and his solution, using an Iterator, destroyed original Map object. The subsequent Volley internal calls had an empty params object.
I added also the encode of parameters.
This is an inline usage (no subclass).
public void GET(String url, Map<String, String> params, Response.Listener<String> response_listener, Response.ErrorListener error_listener, String API_KEY, String stringRequestTag) {
final Map<String, String> mParams = params;
final String mAPI_KEY = API_KEY;
final String mUrl = url;
StringRequest stringRequest = new StringRequest(
Request.Method.GET,
mUrl,
response_listener,
error_listener
) {
#Override
protected Map<String, String> getParams() {
return mParams;
}
#Override
public String getUrl() {
StringBuilder stringBuilder = new StringBuilder(mUrl);
int i = 1;
for (Map.Entry<String,String> entry: mParams.entrySet()) {
String key;
String value;
try {
key = URLEncoder.encode(entry.getKey(), "UTF-8");
value = URLEncoder.encode(entry.getValue(), "UTF-8");
if(i == 1) {
stringBuilder.append("?" + key + "=" + value);
} else {
stringBuilder.append("&" + key + "=" + value);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
String url = stringBuilder.toString();
return url;
}
#Override
public Map<String, String> getHeaders() {
Map<String, String> headers = new HashMap<>();
if (!(mAPI_KEY.equals(""))) {
headers.put("X-API-KEY", mAPI_KEY);
}
return headers;
}
};
if (stringRequestTag != null) {
stringRequest.setTag(stringRequestTag);
}
mRequestQueue.add(stringRequest);
}
This function uses headers to pass an APIKEY and sets a TAG to the request useful to cancel it before its completion.
Hope this helps.
This may help you...
private void loggedInToMainPage(final String emailName, final String passwordName) {
String tag_string_req = "req_login";
StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://localhost/index", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
try {
JSONObject jsonObject = new JSONObject(response);
Boolean error = jsonObject.getBoolean("error");
if (!error) {
String uid = jsonObject.getString("uid");
JSONObject user = jsonObject.getJSONObject("user");
String email = user.getString("email");
String password = user.getString("password");
session.setLogin(true);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
Toast.makeText(getApplicationContext(), "its ok", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
System.out.println("volley Error .................");
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "login");
params.put("email", emailName);
params.put("password", passwordName);
return params;
}
};
MyApplication.getInstance().addToRequestQueue(stringRequest,tag_string_req);
}
For Future Readers
I love to work with Volley. To save development time i tried to write small handy library Gloxey Netwok Manager to setup Volley with my project. It includes JSON parser and different other methods that helps to check network availability.
Use ConnectionManager.class in which different methods for Volley String and Volley JSON request are available.
You can make requests of GET, PUT, POST, DELETE with or without header. You can read full documentation here.
Just put this line in your gradle file.
dependencies {
compile 'io.gloxey.gnm:network-manager:1.0.1'
}
Volley StringRequest
Method GET (without header)
ConnectionManager.volleyStringRequest(context, isDialog, progressDialogView, requestURL, volleyResponseInterface);
How to use?
Configuration Description
Context Context
isDialog If true dialog will appear, otherwise not.
progressView For custom progress view supply your progress view id and make isDialog true. otherwise pass null.
requestURL Pass your API URL.
volleyResponseInterface Callback for response.
Example
ConnectionManager.volleyStringRequest(this, false, null, "url", new VolleyResponse() {
#Override
public void onResponse(String _response) {
/**
* Handle Response
*/
}
#Override
public void onErrorResponse(VolleyError error) {
/**
* handle Volley Error
*/
}
#Override
public void isNetwork(boolean connected) {
/**
* True if internet is connected otherwise false
*/
}
});
Volley StringRequest
Method POST/PUT/DELETE (without header)
ConnectionManager.volleyStringRequest(context, isDialog, progressDialogView, requestURL, requestMethod, params, volleyResponseInterface);
Example
Use Method : Request.Method.POST
Request.Method.PUT
Request.Method.DELETE
Your params :
HashMap<String, String> params = new HashMap<>();
params.put("param 1", "value");
params.put("param 2", "value");
ConnectionManager.volleyStringRequest(this, true, null, "url", Request.Method.POST, params, new VolleyResponse() {
#Override
public void onResponse(String _response) {
/**
* Handle Response
*/
}
#Override
public void onErrorResponse(VolleyError error) {
/**
* handle Volley Error
*/
}
#Override
public void isNetwork(boolean connected) {
/**
* True if internet is connected otherwise false
*/
}
});
Bonus
Gloxey JSON Parser
Feel free to use gloxey json parser to parse your api response.
YourModel yourModel = GloxeyJsonParser.getInstance().parse(stringResponse, YourModel.class);
Example
ConnectionManager.volleyStringRequest(this, false, null, "url", new VolleyResponse() {
#Override
public void onResponse(String _response) {
/**
* Handle Response
*/
try {
YourModel yourModel = GloxeyJsonParser.getInstance().parse(_response, YourModel.class);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onErrorResponse(VolleyError error) {
/**
* handle Volley Error
*/
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
showSnackBar(parentLayout, getString(R.string.internet_not_found), getString(R.string.retry), new View.OnClickListener() {
#Override
public void onClick(View view) {
//handle retry button
}
});
} else if (error instanceof AuthFailureError) {
} else if (error instanceof ServerError) {
} else if (error instanceof NetworkError) {
} else if (error instanceof ParseError) {
}
}
#Override
public void isNetwork(boolean connected) {
/**
* True if internet is connected otherwise false
*/
if (!connected) {
showSnackBar(parentLayout, getString(R.string.internet_not_found), getString(R.string.retry), new View.OnClickListener() {
#Override
public void onClick(View view) {
//Handle retry button
}
});
}
});
public void showSnackBar(View view, String message) {
Snackbar.make(view, message, Snackbar.LENGTH_LONG).show();
}
public void showSnackBar(View view, String message, String actionText, View.OnClickListener onClickListener) {
Snackbar.make(view, message, Snackbar.LENGTH_LONG).setAction(actionText, onClickListener).show();
}
To provide POST parameter send your parameter as JSONObject in to the JsonObjectRequest constructor. 3rd parameter accepts a JSONObject that is used in Request body.
JSONObject paramJson = new JSONObject();
paramJson.put("key1", "value1");
paramJson.put("key2", "value2");
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,url,paramJson,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);

Categories

Resources