Here I am trying to send my json array to mysql database.When I run this code I get this error:
com.android.volley.ParseError: org.json.JSONException: Value {"msg":false,"status":false} of type org.json.JSONObject cannot be converted to JSONArray
And here's my code:
private void insertToDb() {
billType = (invEstSwitch.isChecked() ? textViewEstimate : textViewInvoice)
.getText().toString();
try {
jsonObject.put("custInfo", custSelected.toString());
jsonObject.put("invoiceNo", textViewInvNo.getText().toString());
jsonObject.put("barcode", barCode.getText().toString());
jsonObject.put("desc", itemDesc.getText().toString());
jsonObject.put("weight", weightLine.getText().toString());
jsonObject.put("rate", rateAmount.getText().toString());
jsonObject.put("makingAmt", makingAmount.getText().toString());
jsonObject.put("net_rate", netRate.getText().toString());
jsonObject.put("itemTotal", itemtotal.getText().toString());
jsonObject.put("vat", textViewVat.getText().toString());
jsonObject.put("sum_total", textViewSum.getText().toString());
jsonObject.put("bill_type", billType);
jsonObject.put("date", textViewCurrentDate.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
try {
itemSelectedJson.put(index, jsonObject);
index++;
} catch (JSONException e) {
e.printStackTrace();
}
final JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.POST, INVEST_URL, itemSelectedJson, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("RESPONSE", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("JSON ERROR", error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json; charset=utf-8");
headers.put("Accept", "application/json");
return headers;
}
};
final RequestQueue queue = Volley.newRequestQueue(this);
queue.add(arrayRequest);
}
I also tried displaying the json array inside a text view.It displays the following json array.
[
{
"custInfo": "Ujwal 9975022560",
"rate": "24000",
"weight": "21.00000",
"desc": "GENTS ANGTHI 22k NO STONE",
"makingAmt": "200",
"sum_total": "RS.104188.92",
"vat": "RS.2042.92",
"itemTotal": "51073",
"barcode": "BQSP78BB",
"net_rate": "24200",
"date": "2015-12-01",
"invoiceNo": "1",
"bill_type": "Estimate"
},
{
"custInfo": "Ujwal 9975022560",
"rate": "24000",
"weight": "21.00000",
"desc": "GENTS ANGTHI 22k NO STONE",
"makingAmt": "200",
"sum_total": "RS.104188.92",
"vat": "RS.2042.92",
"itemTotal": "51073",
"barcode": "BQSP78BB",
"net_rate": "24200",
"date": "2015-12-01",
"invoiceNo": "1",
"bill_type": "Estimate"
}
]
I tested this json array on json lint.It is a valid JSON.
As suggested I changed to json object request.Now I am getting a Response it say RESPONSE: {"msg":false,"status":false} I get it at
public void onResponse(JSONObject response) { Log.d("RESPONSE", response.toString()); } what does that mean?
private void insertToDb() {
billType = (invEstSwitch.isChecked() ? textViewEstimate : textViewInvoice)
.getText().toString();
try {
jsonObject.put("custInfo", custSelected.toString());
jsonObject.put("invoiceNo", textViewInvNo.getText().toString());
jsonObject.put("barcode", barCode.getText().toString());
jsonObject.put("desc", itemDesc.getText().toString());
jsonObject.put("weight", weightLine.getText().toString());
jsonObject.put("rate", rateAmount.getText().toString());
jsonObject.put("makingAmt", makingAmount.getText().toString());
jsonObject.put("net_rate", netRate.getText().toString());
jsonObject.put("itemTotal", itemtotal.getText().toString());
jsonObject.put("vat", textViewVat.getText().toString());
jsonObject.put("sum_total", textViewSum.getText().toString());
jsonObject.put("bill_type", billType);
jsonObject.put("date", textViewCurrentDate.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
try {
itemSelectedJson.put(index, jsonObject);
index++;
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject jsonobj = new JSONObject();
try {
jsonobj.put("itemarray",itemSelectedJson);
} catch (JSONException e) {
e.printStackTrace();
}
final JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.POST, INVEST_URL, jsonobj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("RESPONSE", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("JSONERROR",error.toString());
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json; charset=utf-8");
headers.put("Accept", "application/json");
return headers;
}
};
final RequestQueue queue = Volley.newRequestQueue(this);
queue.add(objectRequest);
}
As in log:
com.android.volley.ParseError: org.json.JSONException: Value
{"msg":false,"status":false}
Means Server is returning JSONObject instead of JSONArray as response String.
So, use JsonObjectRequest instead of JsonArrayRequest to make Volley request.
POST a JSONArray doesn't mean you need to call a JsonArrayRequest request.
Request depends on the type of the response you are expecting. You have to check the object type returned by your webservice and then adapt your request according to that.
In your specific case, the error log says you need to use a JsonObjectRequest instead of JsonArrayRequest.
And I final got it to work this is my current code
private void insertToDb() throws JSONException{
//createJsonArray();
final String jsonArray = itemSelectedJson.toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, INVEST_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
display.setText("This is the "+response);
Toast.makeText(AddInvEst.this, "This is the response"+response, Toast.LENGTH_LONG).show();
Log.d("RESPONSE", response.toString().trim());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put(KEY_JSONARRAY,jsonArray);
return params;
}
};
RequestQueue requestQ =Volley.newRequestQueue(this);
requestQ.add(stringRequest);
}
Related
I want to send a DELETE request to an API to delete a city with the given id. In the API request documentation it says that the DELETE request requires as parameters the authentication token and the city id. When I run the code below I always get a com.android.volley.AuthFailureError.
Here's my code:
void deleteCity(String cityId, final VolleyResponseListener volleyResponseListener){
String url = baseUrl + "city";
try {
JSONObject params = new JSONObject();
params.put("token", token);
params.put("city_id", cityId);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.DELETE, url, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try{
String success = response.get("success").toString();
if(success.equals("true")){
volleyResponseListener.onResponse();
}else{
String errorMessage = response.get("errorMessage").toString();
throw new Exception(errorMessage);
}
} catch (Exception e) {
volleyResponseListener.onError(e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error);
volleyResponseListener.onError("Volley Error");
}
});
requestQueue.add(jsonObjectRequest);
}catch (JSONException e){
volleyResponseListener.onError("Param error");
}
}
UPDATE:
I solved the problem by adding the city id as a query in the HTTP request and sent the authentication token in the header. Here is the final code:
void deleteCity(String cityId, final VolleyResponseListener volleyResponseListener){
String url = baseUrl + "city?city_id="+cityId;
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.DELETE, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try{
String success = response.get("success").toString();
if(success.equals("true")){
volleyResponseListener.onResponse();
}else{
String errorMessage = response.get("errorMessage").toString();
throw new Exception(errorMessage);
}
} catch (Exception e) {
volleyResponseListener.onError(e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error);
volleyResponseListener.onError("Volley Error");
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null || headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
headers.put("token", token);
return headers;
}
};
requestQueue.add(jsonObjectRequest);
}
I want to update the "Pass" field using WebAPI, I have created an HTTP PUT Request using Asp.Net WEB API and Android Java with Volley.
through Postman it's updating field value but when I test through my App it's updating the blank value in DB.
Thanks in advance.
private void callPUTDataMethod(String name, String job) {
loadingPB.setVisibility(View.VISIBLE);
String url = URL;
RequestQueue queue = Volley.newRequestQueue(PassUpdt.this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.PUT, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
loadingPB.setVisibility(View.GONE);
jobEdt.setText("");
userNameEdt.setText("");
// on below line we are displaying a toast message as data updated.
Toast.makeText(PassUpdt.this, "Data Updated..", Toast.LENGTH_SHORT).show();
try {
JSONObject jsonObject = new JSONObject("Pass");
String output = "Password Updated";
responseTV.setText(output);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(PassUpdt.this, "Fail to update data..", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("EmpCd", "P010");
params.put("Pass", "12345");
params.put("Content-Type", "application/json; charset=utf-8");
return params;
}
};
queue.add(jsonObjectRequest);
}
}
I created the functions like the json file in the picture. When I send a post request, the response is "Unexpected response code 500" for. I think the problem is caused by json arrays, I don't understand exactly why this error is coming. Server url works fine, successfully post on swift. Thanks
json_array_requested_from_me
private void CreditCardParams(Map<String, String> requestParameters) {
JSONArray creditCardItems = new JSONArray();
JSONObject item_creditCardItems = new JSONObject();
try {
item_creditCardItems.put("CC_NUMBER", "1111");
item_creditCardItems.put("EXP_MONTH", “11”);
item_creditCardItems.put("EXP_YEAR", “1111");
item_creditCardItems.put("CC_CVV", “111”);
item_creditCardItems.put("CC_OWNER", “TEST USER”);
item_creditCardItems.put("INSTALLMENT_NUMBER", "1");
} catch (JSONException e) {
e.printStackTrace();
}
creditCardItems.put(item_creditCardItems);
requestParameters.put("CreditCard", (creditCardItems.toString()));
}
private void CustomerParams(Map<String, String> requestParameters) {
JSONArray CustomerItems = new JSONArray();
JSONObject item_Customer = new JSONObject();
try {
item_Customer.put("FIRST_NAME", "Firstname");
item_Customer.put("LAST_NAME", "Lastname");
item_Customer.put("MAIL", "test#test.com");
item_Customer.put("PHONE", "+11111111");
item_Customer.put("CITY", "Test");
item_Customer.put("STATE", "Test");
item_Customer.put("ADDRESS", "Test");
item_Customer.put("CLIENT_IP", "111.11.11.11”);
} catch (JSONException e) {
e.printStackTrace();
}
CustomerItems.put(item_Customer);
requestParameters.put("Customer", (CustomerItems.toString()));
}
private void ProductParams(Map<String, String> requestParameters) {
JSONArray ProductItems = new JSONArray();
JSONObject item_Product = new JSONObject();
try {
item_Product.put("PRODUCT_ID", "1");
item_Product.put("PRODUCT_NAME", “1”);
item_Product.put("PRODUCT_CATEGORY", “Elec.”);
item_Product.put("PRODUCT_DESCRIPTION", “Info”);
item_Product.put("PRODUCT_AMOUNT", 15.00);
} catch (JSONException e) {
e.printStackTrace();
}
ProductItems.put(item_Product);
requestParameters.put("Product", (ProductItems.toString()));
}
private void ConfigParams(Map<String, String> requestParameters) {
JSONArray configItems = new JSONArray();
JSONObject item = new JSONObject();
try {
item.put("MERCHANT", "TEST1234");
item.put("MERCHANT_KEY", “123”);
item.put("BACK_URL", "localhost");
item.put("PRICES_CURRENCY", "USD");
item.put("ORDER_REF_NUMBER", "RFN0001");
item.put("ORDER_AMOUNT", 15.00);
} catch (JSONException e) {
e.printStackTrace();
}
configItems.put(item);
requestParameters.put("Config", (configItems.toString()));
}
private void post_func(){
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error);
}
}
){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String,String>();
CreditCardParams(params);
CustomerParams(params);
ProductParams(params);
ConfigParams(params);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
As you know, 500 server error is an error caused by an exception in the server. If you don't get an error when you send the JSON file you showed from an http request sender program like postman, the problem is in the JSON object you sent to the server.
I sent request with postman its working, but volley doesn't work. I always get error! I searched stackoverflow volley returns error when response is empty but i added CustomJsonObjectRequest still the issue remains.
Error message
Volley org.json.JSONException: End of input at character 0 of
CustomJsonObjectRequest
public class CustomJsonObjectRequest extends JsonObjectRequest {
public CustomJsonObjectRequest(int method, String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(method, url, jsonRequest, listener, errorListener);
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
if (response.data.length == 0) {
byte[] responseData = "{}".getBytes("UTF8");
response = new NetworkResponse(response.statusCode, responseData, response.headers, response.notModified);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return super.parseNetworkResponse(response);
}
}
Volley request
EcoElement ecoElement = ecoElementArrayList.get(position);
Map<String, String> params = new HashMap<String, String>();
params.put("Id", ecoElement.getId().toString());
params.put("Checked", ecoElement.getChecked().toString());
JSONObject ObjParams = new JSONObject(params);
try {
CustomJsonObjectRequest getRequest = new CustomJsonObjectRequest(Request.Method.PUT, "https://ourwebsite.sslbeta.de/api/gardenapi/updateecoelements", ObjParams,
response -> {
Toast.makeText(getContext(), ""+response, Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
},
error -> {
Toast.makeText(getContext(), ""+error.toString(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
);
RequestQueueSingleton.getInstance(getContext()).addToRequestQueue(getRequest);
} catch (Exception e) {
Toast.makeText(getContext(), e.toString(), Toast.LENGTH_LONG).show();
}
Finally i was able to fix the issues after hours of searching. There were two reasons to this, first is that api was returning null/empty so CustomJsonObjectRequest fixed that, and then another issue is that i forgot to add authentication headers. that was a silly mistake i know!
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("Authorization", "Bearer "+access_token);
return headers;
}
};
Here is the solution, just create this method and pass your value.
private void CustomJsonObjectRequest() {
String tag_string_req = "req__details";
StringRequest strReq = new StringRequest(Request.Method.POST, <API URL>, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
getPerspective().showErrorLogs(TAG, "Response Invest : " + response);
try {
// Parse your response here
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("Id", <ID VALUE HERE>);
params.put("Checked", <TRUE or FALSE>);
return params;
}
};
strReq.setRetryPolicy(new RetryPolicy() {
#Override
public void retry(VolleyError arg0) throws VolleyError {
}
#Override
public int getCurrentTimeout() {
return 0;
}
#Override
public int getCurrentRetryCount() {
return 0;
}
});
strReq.setShouldCache(false);
addToRequestQueue(strReq, tag_string_req);
}
Both ID and Checked must have String type.And create below methods in MainActivity:
private RequestQueue mRequestQueue;
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
I feel like this is a very basic concept missunderstanding. In my Android app I make HTTP requests using Volley lib. At first I made the requests through a JsonObjectRequest in the Activity code and worked right, but now I separated the request code in a class apart so I can call it from any Activity. The new class has a method that returns the requested JSONObject but any "json action" I do over the returned object ends in an error.
Here is the new class code, JSONRequests:
public class JSONRequests {
private JSONObject mResponse;
private String mURL = "https://myurl.com/";
public JSONObject getJSONObject(final String credentials, final String path) {
final JsonObjectRequest mRequest = new JsonObjectRequest(mURL.concat(path), null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
mResponse = response;
try {
Log.d("RESPONSE", mResponse.getString("id")); // It works here
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", "Basic " + credentials);
return headers;
}
};
MyApplication.getInstance().getRequestQueue().add(mRequest);
return mResponse;
}
}
And here is how I call getJSONObject from MyActivity:
JSONRequests mRequest = new JSONRequests();
JSONObject mInfo = mRequest.getJSONObject(mEncodedCredentials, mPath);
try {
Log.d("RESPONSE", mInfo.getString("id")); // This doesn't work
} catch (JSONException e) {
e.printStackTrace();
}
When in the Activity file, I used "response" as a JSONObject and it worked, but now separated it won't. I don't know if is a error with JSONObject or just that I'm not getting the returned object in the correct way. Thanks in advance.