The response format is {"status":"201","message":"OTP is created and sent."}, I need to get the status & message values, but String name = response.getString("name"); is showing red line error.
Here is my code:
public void sendData() {
final JSONObject json = new JSONObject();
final TextView serverResp = findViewById(R.id.connectionStatus);
try {
json.put("mobile", "12312312");
} catch (JSONException e) {
e.printStackTrace();
}
String url = getResources().getString(R.string.url_login);
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, json,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(REQ_TAG, response.toString());
String name = response.getString("name");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
serverResp.setText("Error getting response\n" + error.toString());
Log.d(REQ_TAG, "Error: " + error.toString()
+ "\nStatus Code " + error.networkResponse.statusCode
+ "\nResponse Data " + error.networkResponse.data
+ "\nCause " + error.getCause()
+ "\nmessage" + error.getMessage());
}
});
jsonObjectRequest.setTag(REQ_TAG);
requestQueue.add(jsonObjectRequest);
// do i need the following line?
//RequestQueueSingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
}
Becuase there is no key name in JSON response
try this
String status= response.getString("status");
String message= response.getString("message");
Related
I am using a Web API to be integrated into my app. I a using .net server APIs for the same but the problem is that when I am passing parameters with URL then it throws an error if any parameter of API contains space. As I am passing string values but it throws me error just because of space and if I remove space then everything is perfect. Please help!!!
private void getEnterLoadDetail() {
pBar.setVisibility(View.VISIBLE);
pref = getContext().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
String userName = pref.getString(KEY_USER_NAME, "username");
Log.e("TAG", "USERNAME" + userName);
tripId = txtTripId.getText().toString();
materialCode = txtMaterialCode.getText().toString();
vendorCode = txtVendorCode.getText().toString();
String url = "http://18.216.239.216:8086/api/Mobile?username="+userName+"&tripid=" + tripId + "&VehicleNo=" + vehicleNo + "&MaterialName=" + materialname + "&MaterialCode=" + materialCode + "&VendorName=" + vendorName + "&VendorCode=" + vendorCode + "&MaterialRate=" + rate + "&Remarks="+remarks+"";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("response", response.toString());
try {
if (response.contains("success")) {
Toast.makeText(getActivity(), R.string.load_detail_submitted, Toast.LENGTH_LONG).show();
edtVehicleNo.setText("");
edtRate.setText("");
edtRemarks.setText("");
txtMaterialCode.setText("Material Code");
txtVendorCode.setText("Vendor Code");
spinnerVendorName.setSelection(0);
spinnerMaterialName.setSelection(0);
txtTripId.setText("Trip Id");
}
} catch (Exception e) {
e.printStackTrace();
Activity activity = getActivity();
if (activity != null && isAdded()) {
Toast.makeText(activity, R.string.some_error_occured, Toast.LENGTH_LONG).show();
}
}
pBar.setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: " + error.getMessage());
Activity activity = getActivity();
if (activity != null && isAdded()) {
Toast.makeText(activity, R.string.some_error_occured, Toast.LENGTH_LONG).show();
pBar.setVisibility(View.GONE);
}
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
//adding the string request to request queue
requestQueue.add(stringRequest);
}
-------- materialname and all other variables contains spaces and API throws error.
Try
String url = "http://18.216.239.216:8086/api/Mobile?username="+userName+"&tripid=" + tripId + "&VehicleNo=" + vehicleNo + "&MaterialName=" + materialname + "&MaterialCode=" + materialCode + "&VendorName=" + vendorName + "&VendorCode=" + vendorCode + "&MaterialRate=" + rate + "&Remarks="+remarks+"";
String convertedUrl = URLEncoder.encode(url, "utf-8");
I have two Android apps that communicate with a Web server using Volley calls: one app waits for the other to post a short message. Most of the time this works fine: the waiting app gets the response from the posting app. However, every 5 or so times, the response is sent by the first app but the second one never gets a response. Here is the relevant code:
Posting code:
private synchronized void setGameProgress(String user_id, int pos, String letter, String accessToken) {
String url = "";
RequestQueue queue = Volley.newRequestQueue(activity);
try {
activity.runOnUiThread(new Runnable() {
public void run() {
spinner.setVisibility(View.VISIBLE);
}
});
url = "https://www.chiaramail.com:443/GameServer/GameServer?user_ID=" + URLEncoder.encode(user_id, "UTF-8") + "&token=" + URLEncoder.encode(accessToken, "UTF-8") + "&cmd=" + URLEncoder.encode("SETGAME PROGRESS ", "UTF-8") + "&parms=" + URLEncoder.encode(user_id + " " + pos + " " + letter, "UTF-8");
} catch (UnsupportedEncodingException e) {
Toast.makeText(activity, getString(R.string.error_updating_progress) + e.getMessage(), Toast.LENGTH_LONG).show();
spinner.setVisibility(View.INVISIBLE);
}
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (!response.startsWith("42 ")) {
queue_builder.setMessage(getString(R.string.error_updating_progress) + " " + response);
queue_alert = queue_builder.create();
queue_alert.show();
}
spinner.setVisibility(View.INVISIBLE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
volleyError = error;
Toast.makeText(activity, getString(R.string.error_updating_progress) + volleyError.getMessage(), Toast.LENGTH_LONG).show();
spinner.setVisibility(View.INVISIBLE);
}
});
queue.add(stringRequest);
}
Wait code:
private synchronized void getGameProgress(final String user_id, final String accessToken) {
String url = "";
RequestQueue queue = Volley.newRequestQueue(activity);
try {
url = "https://www.chiaramail.com:443/GameServer/GameServer?user_ID=" + URLEncoder.encode(user_id, "UTF-8") + "&token=" + URLEncoder.encode(accessToken, "UTF-8") + "&cmd=" + URLEncoder.encode("GETGAME PROGRESS ", "UTF-8") + "&parms=" + URLEncoder.encode(user_id, "UTF-8");
} catch (UnsupportedEncodingException e) {
Toast.makeText(activity, getString(R.string.error_getting_progress) + e.getMessage(), Toast.LENGTH_LONG).show();
}
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.startsWith("43 ")) {
StringTokenizer st = new StringTokenizer(response.substring(3));
String position = st.nextToken();
String letter = st.nextToken();
updateTheirProgress(Integer.valueOf(position), letter);
getGameProgress(opponent_ID, AccessToken.getCurrentAccessToken().getToken());
} else {
queue_builder.setMessage(getString(R.string.error_getting_progress) + " " + response);
queue_alert = queue_builder.create();
queue_alert.show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
volleyError = error;
Toast.makeText(activity, getString(R.string.error_getting_progress) + volleyError.getMessage(), Toast.LENGTH_LONG).show();
}
});
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
60000, 5,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(stringRequest);
}
I know that the server is processing the requests from the server log:
10212211883390475 2017-11-26, 17:57:40 42
10212211883390475 2017-11-26, 17:57:40 43 4 s
I've spent several days on this and other than a Volley bug, I can't see what the problem is. Any thoughts?
The problem was due to the Apache server timing out after five minutes. The problem was resolved when I changed the timeout setting in Apache to -1 (infinite timeout).
/**
* Method to make json array request where response starts with [
* Requesting data from url
* */
private String urlJsonArry_local = "http://www.endorecord.in/endorecord/hospitaladmin/Api/device_hospitals.php?deviceid=";
private void makeJsonArrayRequest() {
showpDialog();
JsonArrayRequest req = new JsonArrayRequest(urlJsonArry_local +androidID,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
String name = person.getString("hospitalid");
String email = person.getString("hospital_name");
/*JSONObject phone = person
.getJSONObject("phone");
String home = phone.getString("home");
String mobile = phone.getString("mobile");
*/
jsonResponse += "Name: " + name + "\n\n";
jsonResponse += "Email: " + email + "\n\n";
//jsonResponse += "Home: " + home + "\n\n";
//jsonResponse += "Mobile: " + mobile + "\n\n\n";
}
Toast.makeText(getApplicationContext(), jsonResponse, Toast.LENGTH_LONG).show();
//txtResponse.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
you should be passing your url in the request "http://www.google.com"+androidID not this. And the Url urlJsonArry_local that you have mentioned above returns json object response not jsonArray, Your code and Json reponse are completely irrelavant
for the Json respone in above url
private String urlJsonArry_local = "http://www.endorecord.in/endorecord/hospitaladmin/Api/device_hospitals.php?deviceid=";
RequestQueue queue = MyVolley.getRequestQueue();
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,urlJsonArry_local,null/* paramateres passed here*/,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONObject jObject = response;
String status = jObject.getString("status");
JSONArray hospitalArray = jObject.getJSONArray("hospital");
//your for loop to parse hospital array here
hideProgressDialog();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideProgressDialog();
}
});
queue.add(jsObjRequest);
Ways to implement volley json response cache.I tried the following way to get response from volley.i get the response correctly.I dont know how to store these json values into volley cache
StringRequest strReq = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("mainresp$$$"+response);
Log.d("Volley Request Success", response.toString());
result=response;
callback.onSuccess(result);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("volley request Error",
"Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
Together with my comments, you have already read my answer at the following question:
Android Setup Volley to use from Cache
I have just tested with POST request, as the following code:
CacheRequest cacheRequest = new CacheRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
try {
final String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
// Check if it is JSONObject or JSONArray
Object json = new JSONTokener(jsonString).nextValue();
JSONObject jsonObject = new JSONObject();
if (json instanceof JSONObject) {
jsonObject = (JSONObject) json;
} else if (json instanceof JSONArray) {
jsonObject.put("success", json);
} else {
String message = "{\"error\":\"Unknown Error\",\"code\":\"failed\"}";
jsonObject = new JSONObject(message);
}
textView.setText(jsonObject.toString(5));
} catch (UnsupportedEncodingException | JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// do something...
}
});
My sample Asp.Net Web API code as the following:
// POST api/<controller>
public IHttpActionResult Post()
{
string jsonString = "[" +
"{" +
"name: \"Person 1\"," +
"age: 30," +
"type: \"POST\"," +
"}," +
"{" +
"name: \"Person 2\"," +
"age: 20," +
"type: \"POST\"," +
"}," +
"{" +
"name: \"Person 3\"," +
"age: 40," +
"type: \"POST\"," +
"}" +
"]";
JArray jsonObj = JArray.Parse(jsonString);
return Ok(jsonObj);
}
Here is the result screenshot
I have followed this tutorial.
The author directly uses the data in the callback by setting the textview within the callback. What I would like to do is populate an array with the response I'm getting from my request, and then be able to use that array elsewhere (as the response listener is an anonymous inner class, I can't figure out how to get data from it; any attempt to assign to an array inside the listener has proved fruitless.
Thanks, please bear with me as I'm still a beginner.
The listener:
JsonArrayRequest req = new JsonArrayRequest(urlJsonArry,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
String name = person.getString("name");
String email = person.getString("email");
JSONObject phone = person
.getJSONObject("phone");
String home = phone.getString("home");
String mobile = phone.getString("mobile");
jsonResponse += "Name: " + name + "\n\n";
jsonResponse += "Email: " + email + "\n\n";
jsonResponse += "Home: " + home + "\n\n";
jsonResponse += "Mobile: " + mobile + "\n\n\n";
}
txtResponse.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
});
EDIT: The code below outlines the problem I'm having. I'm aware this is probably due to misunderstanding or misapplication on my part but still.
private void makeJsonArrayRequest(String url){
//ONLY WAY TO ACCESS INSIDE LISTENER IS TO MAKE FINAL
final ArrayList<String> string = new ArrayList<>();
showpDialog();
JsonArrayRequest req = new JsonArrayRequest(
url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject field = (JSONObject) response.get(i);
string.add(i, field.getString("title"));
//THIS PRINTS OUT ALL MY TITLES CORRECTLY, SHOWING THAT
//THE STRINGS ARRAY IS POPULATED IN THIS SCOPE
Log.d(AppController.TAG, string.get(i));
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context,
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(AppController.TAG, "Error: " + error.getMessage());
Toast.makeText(context,
error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
}
);
AppController.getInstance().addToRequestQueue(req);
//THIS CAUSES AN OUT OF BOUNDS EXCEPTION, AS IT THINKS THE ARRAY HAS NOT BEEN POPULATED
Log.d(AppController.TAG, string.get(3));
}
I think the problem is using variable string as a copy of actual string inside OnResponse(..).
Try adding static to this variable :
final static ArrayList<String> string = new ArrayList<>();