Hello i am posting data to server in json format,
but it returns volley server error in error response`
RequestQueue queue = Volley.newRequestQueue(this);
JSONObject jobj=new JSONObject();
try {
jobj.put("id",”123”);
jobj.put("session","new");
JSONArray array = null;
array = new JSONArray();
for (int i = 0;i<3;i++){
JSONObject jsonObject = new JSONObject();
jsonObject.put("name","test");
jsonObject.put("content","test");
jsonObject.put("time"," 2016-04-07T11:44:22.407Z ");
array.put(jsonObject);
}
Log.e(" array "," arrr"+array.toString());
jobj.put("data",array);
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("jsondata",jobj.toString());
JsonObjectRequest sr= new JsonObjectRequest(post_url, jobj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#OveRequestQueue queue = Volley.newRequestQueue(this);
JSONObject jobj=new JSONObject();
try {
jobj.put("id",”123”);
jobj.put("session","new");
JSONArray array = null;
array = new JSONArray();
for (int i = 0;i<3;i++){
JSONObject jsonObject = new JSONObject();
jsonObject.put("name","test");
jsonObject.put("content","test");
jsonObject.put("time"," 2016-04-07T11:44:22.407Z ");
array.put(jsonObject);
}
Log.e(" array "," arrr"+array.toString());
jobj.put("data",array);
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("jsondata",jobj.toString());
JsonObjectRequest sr= new JsonObjectRequest(post_url, jobj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}rride
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/json");
return params;
}
};
queue.add(sr);`
Have a singleton which handles the request queue.
public class VolleySingleton {
// Singleton object...
private static VolleySingleton instance;
final private RequestQueue requestQueue;
private static ImageLoader imageLoader;
//Constructor...
private VolleySingleton(Context context) {
requestQueue = Volley.newRequestQueue(context);
imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap> cache = new LruCache<>(100000000);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
// Singleton method...
public static VolleySingleton getInstance(Context context) {
if (instance == null) {
instance = new VolleySingleton(context);
}
return instance;
}
public RequestQueue getRequestQueue(Context context) {
if (requestQueue != null) {
return requestQueue;
} else {
getInstance(context);
return requestQueue;
}
}
private RequestQueue getRequestQueue() {
return requestQueue;
}
public static ImageLoader getImageLoader(Context context) {
if (imageLoader != null) {
return imageLoader;
} else {
getInstance(context);
return imageLoader;
}
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag("App");
getRequestQueue().add(req);
}
}
Then using the below method you can send the request.
public void postVolley(final Context context, String url, JSONObject jsonObject) {
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject responseJson) {
Log.e("success", "" + responseJson.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error", "" + error);
}
}) {
/**
* Setting the content type
*/
#Override
public String getBodyContentType() {
return "application/json;charset=UTF-8";
}
};
VolleySingleton.getInstance(context).addToRequestQueue(jsonObjReq);
}
This works fine for me.
Related
This is my MainActivity, I am unable to understand and write the unit test code for this can someone help me by providing reference or the code for this problem.In the main activity I have created the methods to call the API how can I mock the API response and get the unit tests for this.
public class MainActivity extends AppCompatActivity {
private String TAG = "MainActivity";
private final String Url="https://dev-smartoffice-api.sharpb2bcloud.com/rmi/v1/checkVersion";
IResult mResultCallback = null;
public MainActivity(IResult iResult)
{
this.mResultCallback=iResult;
}
VolleyService mVolleyService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initVolleyCallback();
mVolleyService.getDataVolley("GETCALL",Url);
mVolleyService = new VolleyService(mResultCallback,this);
JSONObject sendObj = null;
try {
sendObj = new JSONObject("{'Test':'Test'}");
} catch (JSONException e) {
e.printStackTrace();
}
// mVolleyService.postDataVolley("POSTCALL", "http://localhost/androidphpmysql/registrationapi.php?apicall=login", sendObj);
}
void initVolleyCallback(){
mResultCallback = new IResult() {
#Override
public void notifySuccess(String request,JSONObject response) {
Toast.makeText(MainActivity.this,response.toString(),Toast.LENGTH_LONG).show();
}
#Override
public void notifyError(String requestType, VolleyError error) {
Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
// return error;
}
};
}
}
These are my interfaces,here there are two interfaces notify-success and notify error with return type void I don't know how to use them for mocking please help me
public interface IResult {
public void notifySuccess(String requestType, JSONObject response);
public void notifyError(String requestType, VolleyError error);
}
This is my volleyservice class
public class VolleyService {
IResult mResultCallback = null;
Context mContext;
JSONObject message;
public VolleyService(IResult resultCallback, Context context){
mResultCallback = resultCallback;
mContext = context;
}
public void postDataVolley(final String requestType, String url,JSONObject sendObj){
try {
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObj = new JsonObjectRequest(url,sendObj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if(mResultCallback != null)
mResultCallback.notifySuccess(requestType,response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null)
mResultCallback.notifyError(requestType,error);
}
})
{
#Override
public Map getHeaders() throws Error {
HashMap headers = new HashMap();
headers.put("Content-Type", "application/json");
headers.put("client-type","SYNAPPX");
headers.put("client-version","1.1.0");
headers.put("operating-system", "ANDROID");
headers.put("os-version", "8.0");
return headers;
}
};
queue.add(jsonObj);
}catch(Exception e){
}
}
public void getDataVolley(final String requestType, String url){
try {
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObj = new JsonObjectRequest( Request.Method.GET,url,null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if(mResultCallback != null)
mResultCallback.notifySuccess(requestType,response);
message=response;
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null)
mResultCallback.notifyError(requestType, error);
}
}){
#Override
public Map getHeaders() throws Error {
HashMap headers = new HashMap();
headers.put("Content-Type", "application/json");
headers.put("client-type","SYNAPPX");
headers.put("client-version","1.1.0");
headers.put("operating-system", "ANDROID");
headers.put("os-version", "8.0");
return headers;
}
};
queue.add(jsonObj);
}catch(Exception e){
e.printStackTrace();
}
}
}
I am trying to get posts from server based on a parameter i.e. email address. How do I send parameters in JSONArrayRequest so that only those posts are retrieved which are matched with the given parameter? Here is my code:
JsonArrayRequest:
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for(int i= 0; i<response.length(); i++){
try {
JSONObject object = response.getJSONObject(i);
Post post = new Post();
post.setContent(object.getString("Content"));
post.setDate(object.getString("PostDate"));
post.setTime(object.getString("PostTime"));
postArray.add(post);
PostList.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.getmInstance().addToRequestQueue(jsonArrayRequest);
And this is the AppController.Java class:
public class AppController extends Application {
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static AppController mInstance;
public static final String TAG = AppController.class.getSimpleName();
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getmInstance() {
return mInstance;
}
public RequestQueue getmRequestQueue()
{
if(mRequestQueue == null){
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public ImageLoader getmImageLoader(){
getmRequestQueue();
if(mImageLoader == null){
mImageLoader = new ImageLoader(this.mRequestQueue, new BitmapCache());
}
return mImageLoader;
}
public <T> void addToRequestQueue(Request<T> request, String tag ){
request.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getmRequestQueue(). add(request);
}
public <T> void addToRequestQueue(Request<T> request ){
request.setTag(TAG);
getmRequestQueue(). add(request);
}
public void cancelPendingRequest(Object tag){
if(mRequestQueue != null){
mRequestQueue.cancelAll(tag);
}
}
}
void MakePostRequest() {
StringRequest postRequest = new StringRequest(Request.Method.POST, EndPoints.BASE_URL_ADS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
value1= jsonResponse.getString("Your ID1");
value2= jsonResponse.getString("Your ID2");
} catch (JSONException e) {
e.printStackTrace();
banner_id = null;
full_id = null;
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
value1= null;
value2= null;
}
}
) {
// here is params will add to your url using post method
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("app", getString(R.string.app_name));
//params.put("2ndParamName","valueoF2ndParam");
return params;
}
};
Volley.newRequestQueue(this).add(postRequest);
}
this post request is using this compile 'com.mcxiaoke.volley:library:1.0.19' volley version.
i am just adding app name as parameter.you can add more params.
how to create a separate class in which define all about volley
and in another activity we directly pass URL,CONTEXT and Get Response...
First create callback interface to get result in Activity
public interface IResult {
public void notifySuccess(String requestType,JSONObject response);
public void notifyError(String requestType,VolleyError error);
}
Create a separate class with volley function to response the result through interface to activity
public class VolleyService {
IResult mResultCallback = null;
Context mContext;
VolleyService(IResult resultCallback, Context context){
mResultCallback = resultCallback;
mContext = context;
}
public void postDataVolley(final String requestType, String url,JSONObject sendObj){
try {
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObj = new JsonObjectRequest(url,sendObj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if(mResultCallback != null)
mResultCallback.notifySuccess(requestType,response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null)
mResultCallback.notifyError(requestType,error);
}
});
queue.add(jsonObj);
}catch(Exception e){
}
}
public void getDataVolley(final String requestType, String url){
try {
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObj = new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if(mResultCallback != null)
mResultCallback.notifySuccess(requestType, response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null)
mResultCallback.notifyError(requestType, error);
}
});
queue.add(jsonObj);
}catch(Exception e){
}
}
}
Then initialize callback interface into main activity
mResultCallback = new IResult() {
#Override
public void notifySuccess(String requestType,JSONObject response) {
Log.d(TAG, "Volley requester " + requestType);
Log.d(TAG, "Volley JSON post" + response);
}
#Override
public void notifyError(String requestType,VolleyError error) {
Log.d(TAG, "Volley requester " + requestType);
Log.d(TAG, "Volley JSON post" + "That didn't work!");
}
};
Now create object of VolleyService class and pass it context and callback interface
mVolleyService = new VolleyService(mResultCallback,this);
Now call the Volley method for post or get data also pass requestType which is to identify the service requester when getting result back into main activity
mVolleyService.getDataVolley("GETCALL","http://192.168.1.150/datatest/get/data");
JSONObject sendObj = null;
try {
sendObj = new JSONObject("{'Test':'Test'}");
} catch (JSONException e) {
e.printStackTrace();
}
mVolleyService.postDataVolley("POSTCALL", "http://192.168.1.150/datatest/post/data", sendObj);
Final MainActivity
public class MainActivity extends AppCompatActivity {
private String TAG = "MainActivity";
IResult mResultCallback = null;
VolleyService mVolleyService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initVolleyCallback();
mVolleyService = new VolleyService(mResultCallback,this);
mVolleyService.getDataVolley("GETCALL","http://192.168.1.150/datatest/get/data");
JSONObject sendObj = null;
try {
sendObj = new JSONObject("{'Test':'Test'}");
} catch (JSONException e) {
e.printStackTrace();
}
mVolleyService.postDataVolley("POSTCALL", "http://192.168.1.150/datatest/post/data", sendObj);
}
void initVolleyCallback(){
mResultCallback = new IResult() {
#Override
public void notifySuccess(String requestType,JSONObject response) {
Log.d(TAG, "Volley requester " + requestType);
Log.d(TAG, "Volley JSON post" + response);
}
#Override
public void notifyError(String requestType,VolleyError error) {
Log.d(TAG, "Volley requester " + requestType);
Log.d(TAG, "Volley JSON post" + "That didn't work!");
}
};
}
}
Find the whole project at following link
https://github.com/PatilRohit/VolleyCallback
JsonParserVolley.java
(A separate class where we will get the response)
public class JsonParserVolley {
final String contentType = "application/json; charset=utf-8";
String JsonURL = "Your URL";
Context context;
RequestQueue requestQueue;
String jsonresponse;
private Map<String, String> header;
public JsonParserVolley(Context context) {
this.context = context;
requestQueue = Volley.newRequestQueue(context);
header = new HashMap<>();
}
public void addHeader(String key, String value) {
header.put(key, value);
}
public void executeRequest(int method, final VolleyCallback callback) {
StringRequest stringRequest = new StringRequest(method, JsonURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
jsonresponse = response;
Log.e("RES", " res::" + jsonresponse);
callback.getResponse(jsonresponse);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return header;
}
}
;
requestQueue.add(stringRequest);
}
public interface VolleyCallback
{
public void getResponse(String response);
}
}
MainActivity.java
(Code Snippet written in onCreate method)
final JsonParserVolley jsonParserVolley = new JsonParserVolley(this);
jsonParserVolley.addHeader("Authorization", "Your value");
jsonParserVolley.executeRequest(Request.Method.GET, new JsonParserVolley.VolleyCallback() {
#Override
public void getResponse(String response) {
jObject=response;
Log.d("VOLLEY","RES"+jObject);
parser();
}
}
);
parser() is the method where the json response obtained is used to bind with the components of the activity.
you actually missed one parameter in the above VolleyService class. You needed to include, it is,...
JsonObjectRequest jsonObj = new JsonObjectRequest(Request.Method.GET, url,null,new Response.Listener() {
/..../
}
null is the parameter should be included else it gives error
Create Listeners(since they are interface they can't be instantiated but they can be instantied as an anonymous class that implement interface) inside the activity or fragment. And Pass this instances as parameters to the Request.(StringRequest, JsonObjectRequest, or ImageRequest).
public class MainActivity extends Activity {
private static final String URI = "";
// This is like BroadcastReceiver instantiation
private Listener<JSONObject> listenerResponse = new Listener<JSONObject>() {
#Override
public void onResponse(JSONObject arg0) {
// Do what you want with response
}
};
private ErrorListener listenerError = new ErrorListener() {
#Override
public void onErrorResponse(VolleyError arg0) {
// Do what you want with error
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Next, create a class that has request and pass this listeners to this class' request method , that's all. I don't explain this part this is same as creating a request object in any tutorials.But you can customize this class as you wish. You can create singleton RequestQueue to check priority, or set body http body parameters to this methods as paremeters.
public class NetworkHandler {
public static void requestJSON(Context context, String url, Listener<JSONObject> listenerResponse, ErrorListener listenerError) {
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, url, null, listenerResponse, listenerError);
Volley.newRequestQueue(context).add(jsonRequest);
}
}
public class VolleyService {
IResult mResultCallback = null;
Context mContext;
VolleyService(IResult resultCallback, Context context)
{
mResultCallback = resultCallback;
mContext = context;
}
//--Post-Api---
public void postDataVolley(String url,final Map<String,String> param){
try {
StringRequest sr = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(mResultCallback != null)
mResultCallback.notifySuccessPost(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null)
mResultCallback.notifyError(error);
}
}) {
#Override
protected Map<String, String> getParams() {
return param;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
AppController.getInstance(mContext).addToRequestQueue(sr);
}catch(Exception e){
}
}
//==Patch-Api==
public void patchDataVolley(String url,final HashMap<String,Object> param)
{
JsonObjectRequest request = new JsonObjectRequest(Request.Method.PATCH, url, new JSONObject(param),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if(mResultCallback != null)
mResultCallback.notifySuccessPatch(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null)
mResultCallback.notifyError(error);
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
return headers;
}
};
AppController.getInstance(mContext).addToRequestQueue(request);
}
}
public interface IResult {
void notifySuccessPost(String response);
void notifySuccessPatch(JSONObject jsonObject);
void notifyError(VolleyError error);
}
I want to send request to API and get a response in JSON format in Android. I use Volley for helping me. I intend to wrap JsonObjectRequest in VolleyHelper to make it easier for me to use it. The problem is that onResponse() of JsonObjectRequest is void so that I can't return JSON object. My idea is to make my api call a simple just like this.
JSONObject response = VolleyHelper.getInstance(this).get(url);
JSONObject response = VolleyHelper.getInstance(this).post(url, params);
Below is my helper code using singleton pattern as suggest by Google.
VolleyHelper
public class VolleyHelper {
private static VolleyHelper mInstance;
private RequestQueue mRequestQueue;
private static Context mCtx;
public static synchronized VolleyHelper getInstance(Context context) {
if (mInstance == null) {
mInstance = new VolleyHelper(context);
}
return mInstance;
}
private VolleyHelper(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
}
private RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
private <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
public JSONObject get(String url) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
//return jsonObject;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//return jsonerror
}
});
addToRequestQueue(request);
}
public JSONObject post(String url, Map<String, String> params) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
//return jsonObject;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//return jsonerror
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return params;
}
};
addToRequestQueue(request);
}
}
I don't think it's a good idea to return anything from an async-operation synchronously. The whole async-layer in android - be it plain AsyncTask or Volley - is built with another pattern -> the callback. The callback in this case is something which gets called upon completion of a "long-running" network task.
So, you should design your helper class so:
public interface OnFinishListener { public void onFinish( JSONObject o ); }
public class VolleyHelper {
public JSONObject get(String url, OnFinishListener ofl ) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
ofl.onFinish( jsonObject );
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//return jsonerror
}
});
addToRequestQueue(request);
}
}
and then:
OnFinishListener ofl = new OnFinishListener(){
#Override public void onFinish( JSONObject o ){
doSomethingOnJson( o );
}
}
JSONObject response = VolleyHelper.getInstance(this).get(url, ofl );
JSONObject response = VolleyHelper.getInstance(this).post(url, params, ofl );
I created a JsonObjectRequest that I use to send a JSONObject to my WebService. When I try send this JSONObject the object is sending but send 3 objects instead 1. Looking in my data base there's 3 objects added.
I can't understand why this problem, because I always send 1 JSONObject but in webservice there's 3 objects.
I tried to use Postman of Google Chrome, and using Postman send 1 JSONObject normally.
What can be ?
JsonObjectRequest
public JsonObjectRequest sendContatoToEmpresa(String nome,
String email,
String telefone,
String assunto,
String mensagem,
String idEmpresa,
final ContatoAdapter listener){
urlPost.append(WebServiceURL.getBaseWebServiceURL());
urlPost.append("/ws/contatos/contatos/add.json");
JSONObject jsObject = new JSONObject();
try {
JSONObject objs = new JSONObject();
objs.put("nome", nome);
objs.put("email", email);
objs.put("telefone", telefone);
objs.put("assunto", assunto);
objs.put("mensagem", mensagem);
objs.put("pessoa_id", idEmpresa);
jsObject.put("Contato", objs);
Log.i("JSONOBJECT->", jsObject.toString());
}catch(JSONException e){
Log.e("JSONException->", e.getLocalizedMessage());
}
Log.i("URL CONTATO EMPRESA->", urlPost.toString());
JsonObjectRequest apc = new JsonObjectRequest(Request.Method.POST,
urlPost.toString(),
jsObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
try {
Log.i("JSOBJECT->", jsonObject.toString());
if(jsonObject.getString("status").equals("999")){
listener.isSend(true);
}else{
listener.isSend(false);
}
} catch (JSONException e) {
Log.e("JSONException->", e.getLocalizedMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("ERROR METHOD:", "sendContatoToEmpresa in ContatoDAO: " + volleyError.getLocalizedMessage());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
String auth = new String(android.util.Base64.encode((BasicAuthenticationRest.USERNAME + ":" + BasicAuthenticationRest.PASSWORD).getBytes(), android.util.Base64.URL_SAFE | android.util.Base64.NO_WRAP));
headers.put("Content-Type", "application/json; charset=utf-8");
headers.put("Authorization", "Basic " + auth);
return headers;
}
};
return apc;
}
Activity
public Integer sendContatoToEmpresa(String nome,
String email,
String telefone,
String assunto,
String mensagem,
String idEmpresa){
final int[] send = {0};
if(nome.length() == 0 ||
email.length() == 0 ||
telefone.length() == 0 ||
assunto.length() == 0 ||
mensagem.length() == 0){
Toast.makeText(getView().getContext(), "Informe todos os campos", Toast.LENGTH_SHORT).show();
send[0] = 0;
}else{
final ProgressDialog progress = new CustomProgressDialog().getCustomProgress(null, getView().getContext());
progress.show();
JsonObjectRequest app = new ContatoDAO().sendContatoToEmpresa(nome,
email,
telefone,
assunto,
mensagem,
idEmpresa,
new ContatoAdapter(){
#Override
public void isSend(Boolean value) {
if(value){
send[0] = 1;
}
progress.dismiss();
}
});
CustomVolleySingleton.getInstance(getView().getContext()).addToRequestQueue(app);
}
return send[0];
}
CustomVolleySingleton
public class CustomVolleySingleton extends Application{
private static CustomVolleySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;
public static final String TAG = "VolleyPatterns";
private CustomVolleySingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
mImageLoader = new ImageLoader(mRequestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static synchronized CustomVolleySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new CustomVolleySingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
public ImageLoader getImageLoader() {
return mImageLoader;
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
Try to do the following:
app.setRetryPolicy(new DefaultRetryPolicy(
MY_SOCKET_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Here you can change the timeout (MY_SOCKET_TIMEOUT_MS) and change the number of attempts (DefaultRetryPolicy.DEFAULT_MAX_RETRIES)