How do we get response code and message of an errenous response from client? Here error.toString() returns: com.android.volley.ServerError error.getMEssage(): null error.getCause(): null parseNetworkResponse: never ever enters that function. When I add getParams() method, it may return ClientError but response code etc still doesnt work!!!!!!! I am trying this for the last 24 hours. No answer on anywhere.
private void getStudentInfo(String number){
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
final String url = organizationRoot+"/identity/detailed/" +number ;
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
txtTagContent.setText(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
txtTagContent.setText("ERROR " + error.toString() + error.getMessage() + error.getCause());
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return requestHeaders;
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
txtTagContent.setText("WORKED ");
return Response.success( "", HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
}
Could you try:
int statusCode = error.networkResponse.statusCode;
Log.e(TAG, String.valueOf(statusCode);
Maybe you can try this
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
String message = null;
if (error instanceof NetworkError) {
message = "Cannot connect to Internet...Please check your connection!";
} else if (error instanceof ServerError) {
message = "The server could not be found. Please try again after some time!!";
} else if (error instanceof AuthFailureError) {
message = "Cannot connect to Internet...Please check your connection!";
} else if (error instanceof ParseError) {
message = "Parsing error! Please try again after some time!!";
} else if (error instanceof NoConnectionError) {
message = "Cannot connect to Internet...Please check your connection!";
} else if (error instanceof TimeoutError) {
message = "Connection TimeOut! Please check your internet connection.";
}
Toast.makeText(LoginActivity.this, message, Toast.LENGTH_SHORT).show();
}
}
Related
I'm trying to send a JSON to web service using Google Cloud API but keep getting the error below;
ERROR == 415
"E/Volley: [293] BasicNetwork.performRequest: Unexpected response code 415 for http://172.17.1.169:8080/api/save"
Here the code:
mTextMod.setText(text);
JSONObject jsonParam = new JSONObject();
try {
jsonParam.put("text", text);
jsonParam.put("language", "gl-ES");
jsonParam.put("voice", "Vocalizer Expressive Carmela Harpo 22kHz");
jsonParam.put("rate", null);
jsonParam.put("volume", "90");
System.out.println("patata ->" + jsonParam.toString());
} catch (JSONException e) {
e.printStackTrace();
}
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.GET,
url,
jsonParam,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(MainActivity.this, response.toString(),
Toast.LENGTH_LONG).show();
System.out.println(response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
System.out.println(error.toString());
NetworkResponse networkResponse = error.networkResponse;
}
if (networkResponse != null) {
Log.e("Volley", "Error. HTTP Status Code:" + networkResponse.statusCode);
}
if (error instanceof TimeoutError) {
Log.e("Volley", "TimeoutError");
} else if (error instanceof NoConnectionError) {
Log.e("Volley", "NoConnectionError");
} else if (error instanceof AuthFailureError) {
Log.e("Volley", "AuthFailureError");
} else if (error instanceof ServerError) {
Log.e("Volley", "ServerError");
} else if (error instanceof NetworkError) {
Log.e("Volley", "NetworkError");
} else if (error instanceof ParseError) {
Log.e("Volley", "ParseError");
}
}
});
queue.add(jsonObjectRequest);
/**
* Pass request headers
*/
#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;
}
/**
*like below
*/
JSONObject jsonParam = new JSONObject();
try {
jsonParam.put("text", text);
jsonParam.put("language", "gl-ES");
jsonParam.put("voice", "Vocalizer Expressive Carmela Harpo 22kHz");
jsonParam.put("rate", null);
jsonParam.put("volume", "90");
System.out.println("patata ->" + jsonParam.toString());
} catch (JSONException e) {
e.printStackTrace();
}
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, jsonParam, new Response.Listener<JSONObject>(){
#Override
public void onResponse(JSONObject response) {
Toast.makeText(MainActivity.this, response.toString(), Toast.LENGTH_LONG).show();
System.out.println(response.toString());
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
System.out.println(error.toString());
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null) {
Log.e("Volley", "Error. HTTP Status Code:" + networkResponse.statusCode);
}
if (error instanceof TimeoutError) {
Log.e("Volley", "TimeoutError");
} else if (error instanceof NoConnectionError) {
Log.e("Volley", "NoConnectionError");
} else if (error instanceof AuthFailureError) {
Log.e("Volley", "AuthFailureError");
} else if (error instanceof ServerError) {
Log.e("Volley", "ServerError");
} else if (error instanceof NetworkError) {
Log.e("Volley", "NetworkError");
} else if (error instanceof ParseError) {
Log.e("Volley", "ParseError");
}
}
})
{
/**
* Passing some request headers
*/
#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;
}
};
queue.add(jsonObjectRequest);
I'm trying to get a list of tv shows from themovidedb api and I keep getting the error below I am new to android and this is my first time using an api, please let me know if I have to provide more code. Thanks for your help.
Please note I am note trying to populate a recyclerview with this information just yet.
Error
com.android.volley.ParseError: org.json.JSONException: Value {"page":1,"total_results":20000,"total_pages":1000,"results":[{"original_name":"Doom Patrol"....
My code
#Override
protected Void doInBackground(Void... voids) {
popularTvShows = "https://api.themoviedb.org/3/tv/popular?api_key=****my api key goes here****";
popularList = new ArrayList<>();
RequestQueue requestQueue = Volley.newRequestQueue(Objects.requireNonNull(getActivity()));
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
Request.Method.GET,
popularTvShows,
null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
Series series = new Series();
series.setId(jsonObject.getInt("id"));
series.setVoteAverage(jsonObject.getInt("vote_average"));
series.setVoteCount(jsonObject.getInt("vote_count"));
series.setOriginalTitle(jsonObject.getString("original_title"));
series.setTitle(jsonObject.getString("title"));
series.setPopularity(jsonObject.getDouble("popularity"));
series.setOverview(jsonObject.getString("overview"));
series.setReleaseDate(jsonObject.getString("release_date"));
series.setPosterPath(jsonObject.getString("poster_path"));
popularList.add(series);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#SuppressLint("ShowToast")
#Override
public void onErrorResponse(VolleyError error) {
Log.e("gggg", error.toString());
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
//This indicates that the reuest has either time out or there is no connection
Toast.makeText(getActivity(),"Check your internet and try again!", Toast.LENGTH_LONG);
} else if (error instanceof AuthFailureError) {
//Error indicating that there was an Authentication Failure while performing the request
Toast.makeText(getActivity(), "Authentication failure!", Toast.LENGTH_LONG);
} else if (error instanceof ServerError) {
//Indicates that the server responded with a error response
Toast.makeText(getActivity(), "Server error! Try again later", Toast.LENGTH_LONG);
} else if (error instanceof NetworkError) {
//Indicates that there was network error while performing the request
Toast.makeText(getActivity(), "Network error", Toast.LENGTH_LONG);
} else if (error instanceof ParseError) {
// Indicates that the server response could not be parsed
Toast.makeText(getActivity(), "Parse Error", Toast.LENGTH_LONG);
}
}
}
);
requestQueue.add(jsonArrayRequest);
return null;
}
your response is coming in JSONObject not in JSONArray as per your Exception:
com.android.volley.ParseError: org.json.JSONException: Value {"page":1,"total_results":20000,"total_pages":1000,"results":[{"original_name":"Doom Patrol"...
Do this :
#Override
protected Void doInBackground(Void... voids) {
popularTvShows = "https://api.themoviedb.org/3/tv/popular?api_key=****my api key goes here****";
popularList = new ArrayList<>();
RequestQueue requestQueue = Volley.newRequestQueue(Objects.requireNonNull(getActivity()));
JSONObjectRequest jsonObjectRequest = new JSONObjectRequest(
Request.Method.GET,
popularTvShows,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONObject json = new JSONObject(response);
JSONArray results = json.optJSONArray("results");
try {
for (int i = 0; i < results.length(); i++) {
JSONObject jsonObject = results.getJSONObject(i);
Series series = new Series();
.
.
.
popularList.add(series);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#SuppressLint("ShowToast")
#Override
public void onErrorResponse(VolleyError error) {
Log.e("gggg", error.toString());
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
//This indicates that the reuest has either time out or there is no connection
Toast.makeText(getActivity(),"Check your internet and try again!", Toast.LENGTH_LONG);
} else if (error instanceof AuthFailureError) {
//Error indicating that there was an Authentication Failure while performing the request
Toast.makeText(getActivity(), "Authentication failure!", Toast.LENGTH_LONG);
} else if (error instanceof ServerError) {
//Indicates that the server responded with a error response
Toast.makeText(getActivity(), "Server error! Try again later", Toast.LENGTH_LONG);
} else if (error instanceof NetworkError) {
//Indicates that there was network error while performing the request
Toast.makeText(getActivity(), "Network error", Toast.LENGTH_LONG);
} else if (error instanceof ParseError) {
// Indicates that the server response could not be parsed
Toast.makeText(getActivity(), "Parse Error", Toast.LENGTH_LONG);
}
}
}
);
requestQueue.add(jsonObjectRequest);
return null;
}
I am getting wrong response in volley while on the other hand postman getting correct response. Please help me where is the problem . Response i am getting from volley is "response= {"code":1020,"message":"Duplicate key not allowed","returnId":null}"
And in postman it is "{
"code": 1089,"message": "Activation Key sent in email, please activate your user/device","returnId": 438
}"
public void sendRegisterationReq("http://demo.innowi.com/v1/user/register",getJsonObject()) {
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, dataObj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Toast.makeText(context, "" + response.toString(), Toast.LENGTH_SHORT).show();
System.out.println("response= " + response.toString());
System.out.println(TAG + ":" + dataObj.toString());
try {
if (response.getString("code").equals("1020")){
Intent intent = new Intent(RegisterDeviceActivity.this,ActivateDeviceActivity.class);
startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
String message = null;
if (volleyError instanceof NetworkError) {
message = "Network error!";
Log.d(TAG,message);
} else if (volleyError instanceof ServerError) {
message = "Server error!!";
Log.d(TAG,message);
} else if (volleyError instanceof AuthFailureError) {
message = "Auth failure error!";
Log.d(TAG,message);
} else if (volleyError instanceof ParseError) {
message = "Parsing error!";
Log.d(TAG,message);
} else if (volleyError instanceof NoConnectionError) {
message = "No connection error!";
Log.d(TAG,message);
} else if (volleyError instanceof TimeoutError) {
message = "timeout error !";
Log.d(TAG,message);
}
/*Toast.makeText(context, "error", Toast.LENGTH_SHORT).show();
System.out.println(TAG + ":Error: " + volleyError.getMessage());
System.out.println(TAG + ":" + volleyError.toString());*/
System.out.println(TAG + ":" + dataObj.toString());
}
}) {
/**
* Passing some request headers
* */
#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;
}
};
jsonObjReq.setShouldCache(false);
jsonObjReq.setTag("myRequest");
// Adding request to request queue
queue.add(jsonObjReq);
}
public JSONObject getJsonObject(){
JSONObject object = new JSONObject();
try {
if (username!=null && password !=null) {
object.put("username", username.getText().toString());
object.put("password", password.getText().toString());
object.put("deviceMacAddress", "90:B6:86:0D:CE:4F");
}
else
{
Toast.makeText(this, "Email/password should not be empty", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return object;
}
you are the data which is already exist in your database so says duplicate key try different one or try to send all fields valid and different.
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)
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) {
}