i have an android app in which i hit a web service and gets the result.
Now i want is if result is getting to long to be fetched or in between request internet connection is gone then i show a message or a dialog to the user that Your connection timed out
I've tried this code but this is not working
Any help would be appreciated
blic void getVolleyTask(Context context,
final IVolleyReponse responseContext, String URL) {
RequestQueue request = Volley.newRequestQueue(context);
StringRequest strReq = new StringRequest(Request.Method.GET, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
if (response != null) {
JSONArray _array = new JSONArray(response);
responseContext.ResponseOk(_array);
} else {
responseContext.ResponseOk(null);
}
} catch (Exception e) {
e.printStackTrace();
responseContext.ResponseOk(null);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
responseContext.ErrorBlock();
}
});
strReq.setRetryPolicy(new DefaultRetryPolicy(socketTimeout, maxTries,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
request.add(strReq);
}
public void getVolleyPostTask(Context context,
final IVolleyJSONReponse jsonResponseContext, String URL,
JSONObject obj) {
RequestQueue request = Volley.newRequestQueue(context);
JsonObjectRequest myRequest = new JsonObjectRequest(
Request.Method.POST, URL, obj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
jsonResponseContext.ResponseOk(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
jsonResponseContext.ErrorBlock();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
myRequest.setRetryPolicy(new DefaultRetryPolicy(socketTimeout,
maxTries, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
request.add(myRequest);
}
thanks in advance!
VollyJson library have a capability to differentiate different network errors while communicating with webservices.When something went wrong with JSONObjectRequest onErrorResponse will be called,there you can differentiate the error as follows.
public void onErrorResponse(VolleyError error) {
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
//Write Your code here
} else if (error instanceof AuthFailureError) {
//TODO
} else if (error instanceof ServerError) {
//TODO
} else if (error instanceof NetworkError) {
//TODO
} else if (error instanceof ParseError) {
//TODO
}
Related
I have developed a php RestAPI and when i invoke them Postman, it is working fine. I am getting required responses:
http://192.168.23.33/wopo/v1/registerUser.php
When i am calling the above API call with volley, it is getting into "public void onErrorResponse(VolleyError error)" where error is also null.
I have configure the above same URL while sending the StringRequest? Is that fine?
stringRequest=new StringRequest(
Request.Method.POST, Constants.URL_Register, new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
progressDialog.dismiss();
try {
JSONObject json = new JSONObject(response);
Log.d("mysuccess","I saw success");
Toast.makeText(getApplicationContext(),json.getString("message"),Toast.LENGTH_LONG).show();
Intent intent=new Intent(SignupActivity.this,LandingScreenActivity.class);
startActivity(intent);
}catch (Exception e)
{
e.printStackTrace();
}
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
progressDialog.hide();
Log.d("myerror","I got some error");
NetworkResponse networkResponse = error.networkResponse;
Log.d("myerror1",error.getMessage());
// Toast.makeText(getApplicationContext(),error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError
{
int userRole=0;
if(buyerCheckbox.isChecked()) {
if (selleCheckbox.isChecked())
userRole = 3;
else
userRole = 2;
}else
if(selleCheckbox.isChecked())
userRole=2;
Map<String,String> params=new HashMap<>();
params.put("userid","1");
params.put("username",strUsername);
params.put("emailaddress",strEmail);
params.put("housenumber",strFlatNumber);
params.put("apartmentname",apartname);
params.put("apartmentaddress",useraddress);
params.put("usertype",String.valueOf(userRole));
return params;
}
};
RequestHandler.getInstance(this).addToRequestQueue(stringRequest);
StringRequest stringRequest = new StringRequest(Request.Method.POST, UrlEndPoints.interAd,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("Response::", response);
try {
int success;
JSONObject jsonObject = new JSONObject(response);
Log.e("jObj_AppURL", String.valueOf(jsonObject));
success = jsonObject.getInt(SUCCESS);
if (success == 1) {
JSONArray data = jsonObject.getJSONArray(RESPONSE);
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
appImg = c.getString(APPIMG);
appName = c.getString(APPNAME);
appPackages = c.getString(PKG);
InterAdModel interAdModel = new InterAdModel();
interAdModel.setAppImg(appImg);
interAdModel.setAppName(appName);
interAdModel.setAppPackages(appPackages);
interAdModelArrayList.add(interAdModel);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("erorr::", error.toString());
Toast.makeText(SplashActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
//for check service is correctly functioning use package name "com.whatsweb.whatscan.whatsappweb.whatscanforwhatweb"
Map<String, String> params = new HashMap<>();
params.put("task", "get_interad_apps");
params.put("package", getPackageName());
return params;
}
};
int socketTimeout = 30000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
RequestQueue requestQueue = Volley.newRequestQueue(SplashActivity.this);
requestQueue.add(stringRequest);
I am facing error while parsing the JSON object. I am adding two fields,ie. the task and the package name of the application using Map, but it is always throwing the Exceptions. Very rarely I get the actual data. Sometimes It throws only EOFException while sometimes NoConnection error.
Read NoConnectionError.
Error indicating that no connection could be established when
performing a Volley request.
#SuppressWarnings("serial")
public class NoConnectionError extends NetworkError {
public NoConnectionError() {
super();
}
public NoConnectionError(Throwable reason) {
super(reason);
}
}
You should add
public void onErrorResponse(VolleyError error)
{
if (error instanceof NoConnectionError)
{
// Your Code
}
}
You can check
Handle Volley Error.
So I've implemented google/volley in my apps. When i code the apps i accidentally mistyped the url address and the app just crash suddenly. So how can i avoid this kind of problem. Below are the code i've used.
String url_login = "http://10.0.2.2/test_sstem/public/login";
//Send Post data and retrieve server respond
StringRequest stringRequest = new StringRequest(Request.Method.POST, url_login,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(LoginActivity.this,"On Response "+response,Toast.LENGTH_LONG).show();
ValidateLogin(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null && networkResponse.data != null) {
String jsonError = new String(networkResponse.data);
String message_response=null;
try {
JSONObject object = new JSONObject(jsonError);
message_response= object.getString("error");
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(LoginActivity.this, "On Error " + message_response.toString(), Toast.LENGTH_LONG).show();
showProgress(false);
}
}
})
I know that it can be fixed by correcting the URL, but what if the URL are not alive and working how do we work around this problem.
I have used bellow method for volley which is work for me.. i have used wrong address but my app does not stop. Use bellow full method..
private void doLoginAction() {
pDialog.show();
String url_login = "http://10.0.2.2/test_sstem/public/login";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url_login,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//pDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray loginNodes = jsonObject.getJSONArray("ParentNode");
for (int i = 0; i < loginNodes.length(); i++) {
JSONObject jo = loginNodes.getJSONObject(i);
String key1 = jo.getString("key1");
String key2 = jo.getString("key2");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
try {
if (error instanceof TimeoutError ) {
//Time out error
}else if(error instanceof NoConnectionError){
//net work error
} else if (error instanceof AuthFailureError) {
//error
} else if (error instanceof ServerError) {
//Erroor
} else if (error instanceof NetworkError) {
//Error
} else if (error instanceof ParseError) {
//Error
}else{
//Error
}
//End
} catch (Exception e) {
}
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("uname", "era#gmail.com");
params.put("pass", "123456");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
There can be number of reasons why your app crashes with incorrect url, one could be that the host is un resolvable, you can check the validity of a Url by using the following code:
URLUtil.isValidUrl(url)
this gives me error as it expects only JSON object as parameter.is there a way to pass string in POST request? i need to pass an encrypted string.
public JsonObjectRequest addContact(String url, final String contactString, final AddContactCallback addContactCallback) {
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, contactString, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
if (response.length() > 0 && response.getString("status").equalsIgnoreCase("1")) {
if (response.getString("message").equalsIgnoreCase("success")) {// registration
addContactCallback.onAddContactRequestSuccess(....);
}
}else {
addContactCallback.onAddContactRequestError(new VolleyError());
}
} catch (JSONException e) {
e.printStackTrace();
addContactCallback.onAddContactRequestError(new VolleyError());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NetworkError || error instanceof NoConnectionError) {
addContactCallback.onNetworkError();
} else {
addContactCallback.onAddContactRequestError(error);
}
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
10000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
return jsonObjectRequest;
}
i am assuming u want pass a parameter in body of post request there is method for this in volley
#Override
protected Map<String,String> getParams(){
Map<String, String> params = new HashMap<String, String>();
params.put("stringKey", YOUR_ACTUAL_STRING);
return params;
}
for your case
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, contactString, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
if (response.length() > 0 && response.getString("status").equalsIgnoreCase("1")) {
if (response.getString("message").equalsIgnoreCase("success")) {// registration
addContactCallback.onAddContactRequestSuccess(....);
}
}else {
addContactCallback.onAddContactRequestError(new VolleyError());
}
} catch (JSONException e) {
e.printStackTrace();
addContactCallback.onAddContactRequestError(new VolleyError());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NetworkError || error instanceof NoConnectionError) {
addContactCallback.onNetworkError();
} else {
addContactCallback.onAddContactRequestError(error);
}
}
}){
#Override
protected Map<String,String> getParams(){
Map<String, String> params = new HashMap<String, String>();
params.put("stringKey", YOUR_ACTUAL_STRING);
return params;
};
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
10000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
return jsonObjectRequest;
}
if you want to send the string to server through jsonObjectRequest post methord so you need make the key and value pair to send over the server
like as:
JSonObject jsonobjest=new JSonObject();
jsonObject.put(Key_name,String_value);
and send this jsonobject over the server using the jsonObjectRequest same as over here.
its work me,you can use it.
I got the solution.override getBody method and pass the string as byteArray.in the JsonObjectRequest constructor pass null in place of jsonobject
{
#Override
public byte[] getBody() {
byte[] body = new byte[0];
try {
body = contactString.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
}
return body;
}
};
Im creating an application where i can make reports and,on button click nothing happens,even the response does not come,toast not showing up. This volley post i have used it before and it is correct,another thing i should write is that i have to send the token for authorization.
this is my code:
//this is button click
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
volley_send();
}
});
//-----------------------------------------------------
//this is volley post
private void volley_send(){
StringRequest stringRequest = new StringRequest(Request.Method.POST, "my_url",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// save_on_sharedPreference("email",email);
if(!response.isEmpty()){
try {
JSONObject jsonObject = new JSONObject(response);
error = jsonObject.getBoolean("error");
String message = jsonObject.getString("message");
if(!error){
//String token = jsonObject.getString("token");
//JSONObject data = jsonObject.getJSONObject("data");
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), Raport_Cat_NoPhoto.class);
startActivity(intent);
}
else{
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_SHORT).show();
}
// JSONArray feedArray = response.getJSONArray("data");
} catch (JSONException e) {
e.printStackTrace();
System.out.println("JSONException :"+e.toString() );
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
Toast.makeText(getApplicationContext(),getString(R.string.err_connection),Toast.LENGTH_SHORT).show();
} else if (error instanceof AuthFailureError) {
//TODO
//Toast.makeText(getApplicationContext(),"2",Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),getString(R.string.err_authentication),Toast.LENGTH_SHORT).show();
} else if (error instanceof ServerError) {
//TODO
//Toast.makeText(getApplicationContext(),"3",Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),getString(R.string.err_system),Toast.LENGTH_SHORT).show();
} else if (error instanceof NetworkError) {
//TODO
//Toast.makeText(getApplicationContext(),"4",Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),getString(R.string.err_network),Toast.LENGTH_SHORT).show();
} else if (error instanceof ParseError) {
//TODO
//Toast.makeText(getApplicationContext(),"5",Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),getString(R.string.err_processing),Toast.LENGTH_SHORT).show();
}
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Authorization","Bearer "+ApiKey);
return headers;
}
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("category","cat_ankese");
params.put("description",description.getText().toString());
params.put("city",Qyteti);
params.put("fshati",fshati.getText().toString());
params.put("address",address.getText().toString());
params.put("additional_information1",personidyshuar.getText().toString());
params.put("name",emer.getText().toString());
params.put("surname",mbiemer.getText().toString());
params.put("telephone",telefon.getText().toString());
params.put("email",email.getText().toString());
params.put("info_latt",my_latitude);
params.put("info_long",my_longitude);
params.put("file[]",image123);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
I don't know what it is wrong...
Sems like the problem was with the Authorization header,for any reason it requires only one parameter. Thank you all for replies!