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!
Related
i am trying to send the Jsonobject request to the server and i am getting a reply of volley timeouterror
I read something on volley RetryPolicy, that i should increase the time limit of my request and till getting the same error. please guys help to look through my code, and assist me with the right request.
Thanks in advance
private void getpay() {
prgDialog.show();
final String amount = Fund_amount;
final String number = Card.getText().toString().trim();
final String year = Year.getText().toString().trim();
final String month = Month.getText().toString().trim();
final String cvv = CVV.getText().toString().trim();
final String pin = Pin.getText().toString().trim();
aaaaaa
JsonObjectRequest obreq = new JsonObjectRequest(Request.Method.POST, "https://api.myflex.ng/wallet/fund",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
prgDialog.cancel();
String data = response.getString("status");
JSONObject obj = response.getJSONObject("data");
JSONObject transfer = obj.getJSONObject("transfer");
Payment_massage = transfer.getString("flutterChargeResponseMessage");
Payment_ref = transfer.getString("flutterChargeReference");
if (data.equalsIgnoreCase("error")) {
prgDialog.cancel();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.AppCompatAlertDialogStyle);
builder.setTitle("myFlex");
builder.setMessage("Connection Error. Please check Your Network Connection");
builder.setCancelable(false);
builder.setPositiveButton("OK", null);
builder.show();
} else {
prgDialog.cancel();
FragmentTransaction trans = getFragmentManager().beginTransaction();
trans.replace(R.id.change_transfer, new card_token());
trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
trans.addToBackStack(null);
trans.commit();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), error.toString(),Toast.LENGTH_LONG).show();
prgDialog.cancel();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.AppCompatAlertDialogStyle);
builder.setTitle("myFlex");
builder.setCancelable(false);
builder.setMessage("Connection Error. Please check Your Internet Connection ");
builder.setPositiveButton("OK", null);
builder.show();
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", User_Token);
headers.put("Content-Type", "application/json");
return headers;
}
#Override
public String getBodyContentType() {
return "application/json";
}
#Override
public byte[] getBody() {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("amount", amount);
jsonObject.put("card", come());
} catch (JSONException e) {
e.printStackTrace();
}
Log.i("Volley", "Error" + String.valueOf(jsonObject));
return jsonObject.toString().getBytes();
}
private JSONObject come() throws JSONException {
JSONObject params = new JSONObject();
try {
params.put("number", number);
params.put("expiry_month", month);
params.put("expiry_year", year);
params.put("cvv", cvv);
params.put("pin", pin);
Log.i("Volley", "Error" + String.valueOf(params));
} catch (JSONException e) {
Log.e("Volley", "Error" + params);
}
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
obreq.setRetryPolicy(new DefaultRetryPolicy(100 * 1000, 0,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(obreq);
}
Try to configure retry policy. Give a large timeout and try
String tag_json_obj = "json_obj_req";
obreq.setRetryPolicy(new DefaultRetryPolicy(30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.addToRequestQueue(obreq, tag_json_obj);
You can try
add volley library to build.gradle
compile 'com.mcxiaoke.volley:library:1.0.19'
You can call like bellow using volley
private void doLoginAction() {
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) {
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);
}
Timeout in Volley is represented in milliseconds. Default time out is 25000 milliseconds or 25 seconds.
int timeOut = 120; // 2 min
int timeOutInMillis = timeOut * 1000;
obreq .setRetryPolicy(new DefaultRetryPolicy(timeOutInMillis,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(obreq);
For more details:Transmitting Network Data Using Volley
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;
}
};
How do I check if this text appears or not
{"cod":"404","message":"city not found"}
url : http://api.openweathermap.org/data/2.5/weather?q=fddfgdfgdfgdfg&units=metric&appid=efb8013262db1b77b0431909b8b173e1
My try
public void btn_search(View view) {
CheckInternet checkInternet = new CheckInternet(MainActivity.this);
boolean ci = checkInternet.isconnecting();
if(ci)
{
EditText ed_Search = (EditText)findViewById(R.id.ed_Search);
if(ed_Search.getText().length() > 0)
{
String urlOpenWeatherMap = "http://api.openweathermap.org/data/2.5/weather?q=fddfgdfgdfgdfg&units=metric&appid=efb8013262db1b77b0431909b8b173e1";
progressBar = (ProgressBar)findViewById(R.id.progressBar);
btn_search = (ImageView)findViewById(R.id.btn_search);
btn_search.setVisibility(View.INVISIBLE);
progressBar.setVisibility(View.VISIBLE);
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
JsonObjectRequest jsonobjectrequest = new JsonObjectRequest(Request.Method.GET, urlOpenWeatherMap, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String x = response.getString("message");
if(x.contains("404") || x.contains("city not found") )
{
Toast.makeText(MainActivity.this, "error", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "welcome", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonobjectrequest);
}
else
{
Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(MainActivity.this, "no Internet", Toast.LENGTH_SHORT).show();
}
}
I am trying to solve the problem 4 hours ago but no use
I think the problem here
String x = response.getString("message");
I need help please
You are getting json text in the response body, but the server is responding with 404 code which is an error, therefore the logic needs to be inside the overridden method:
#Override
public void onErrorResponse(VolleyError error) {
String body;
String statusCode = String.valueOf(error.networkResponse.statusCode);
if(statusCode == "400") {
// do your thing
}
// do something else
}
Json Might be look like
{"loginNodes":[{"message":"Welcome To Alamofire","name":Enamul Haque,"errorCode":"0","photo":null}]}
Your code should be ..
StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://api.openweathermap.org/data/2.5/weather",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//pDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray loginNodes = jsonObject.getJSONArray("loginNodes");
pDialog.dismiss();
for (int i = 0; i < loginNodes.length(); i++) {
JSONObject jo = loginNodes.getJSONObject(i);
String message= jo.getString("message");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
try {
} catch (Exception e) {
}
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("q", "fddfgdfgdfgdfg");
params.put("units", "metric");
params.put("appid", "efb8013262db1b77b0431909b8b173e1");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
Check response from GET OR Post.You can debug the error onErrorResponse
try {
if (error instanceof TimeoutError ) {
}else if(error instanceof NoConnectionError){
} else if (error instanceof AuthFailureError) {
} else if (error instanceof ServerError) {
//TODO
} else if (error instanceof NetworkError) {
//TODO
} else if (error instanceof ParseError) {
//TODO
}
} catch (Exception e) {
}
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
}