Volley passing a JsonArray Request to Arraylist - android

Hi am new to android am trying to pass a json response to arraylist using jsonarray request but i am getting this error :
Error:
volley error org.json.JSONException: Value < br of type java.lang.String cannot be converted to JSONArray
Php code:
$userid=$_POST["userid"];
$semester=$_POST["semester"];
$level=$_POST["level"];
$stmt="SELECT coursecode,coursetitle,grade,credithrs,marks FROM tblresults WHERE userid = '$userid' and semester = '$semester' and level = '$level'";
$result=mysqli_query($conn,$stmt);
$responsea=array();
while($respons=mysqli_fetch_array($result)){
$response["coursecode"]=$respons['coursecode'];
$response["coursetitle"]=$respons['coursetitle'];
$response["grade"]=$respons['grade'];
$response["credithrs"]=$respons['credithrs'];
$response["marks"]=$respons['marks'];
$responsea[]=$response;
}
echo json_encode($responsea);
Php response:
[{"coursecode":"csc234","coursetitle":"Information Security","grade":"A","credithrs":"3","marks":"80.00"},{"coursecode":"csc300","coursetitle":"Cryptography","grade":"B","credithrs":"3","marks":"65.00"}]
android code:
public ArrayList<resultInstance> extractresult() {
CheckResultFragment checkResultFragment=new CheckResultFragment();
final String gsem=checkResultFragment.gsem;
final String glev=checkResultFragment.glev;
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, jsonurl, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
int i=0;
while (i<response.length()){
try {
JSONObject jsonObject=response.getJSONObject(i);
resultInstance resultinstance =new resultInstance(
jsonObject.getString("coursecode"),
jsonObject.getString("coursetitle"),
jsonObject.getInt("credit"),
jsonObject.getDouble("marks"),
jsonObject.getString("grade"));
results.add(resultinstance);
i++;
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}
){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params=new HashMap<>();
params.put("userid",guid);
params.put("level",glev);
params.put("semester",gsem);
return params;
}
};
VolleySingleton.getInstance(context).addToRequestQueue(jsonArrayRequest);
return results;
}
Any Help will be greatly appreciated!!

Do debug and set breakpoints, your API call php response is not in a format of JSONArray. Send proper JSONArray format as a response to the API call request.

Related

android jsonarray cannot be converted to jsonobject error

I am working on android project and my web service successfully giving response in postman as I mention response below. I am getting below error after getting response from my API. I am not doing this types of web service call first time but don't know why this happening. How can I achieve this ?
web service response in postman -
[
{
"emp_id": 43065,
"emp_name": "Rahul Bhandari",
"username": "43065",
"password": null
}
]
Error -
org.json.JSONException: Value [{"emp_id":43065,"emp_name":"Rahul Bhandari","username":"43065","password":null}] of type org.json.JSONArray cannot be converted to JSONObject
Volley Code -
public void apiCall(final String email, final String password) {
processArray = new ArrayList<String>();
HashMap<String, String> params = new HashMap<String, String>();
params.put("username", email);
params.put("password", password);
JsonObjectRequest request_json = new JsonObjectRequest(AppConfig.login, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if (mStatusCode == 200) {
try {
loginResult = new JSONArray(response.toString());
try {
if (loginResult != null) {
for (int i = 0; i < loginResult.length(); i++) {
JSONObject obj = loginResult.getJSONObject(i);
// SQLite database handler
db = new SQLiteHandler(LoginActivity.this);
// Session manager
session = new SessionManager(LoginActivity.this);
session.setLogin(true);
// Inserting row in users table
db.addUser(obj.getString("username"), obj.getString("emp_name"), obj.getString("emp_id"), obj.getString("emp_designation"), obj.getString("emp_location"));
Intent intent = new Intent(LoginActivity.this, SelectAuditActivity.class);
startActivity(intent);
finish();
Toast.makeText(LoginActivity.this, "Successfull login...", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(LoginActivity.this, "Invalid login credential...", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
//Process os success response
} else {
Toast.makeText(LoginActivity.this, "Oops sorry something went wrong...", Toast.LENGTH_SHORT).show();
}
//Process os success response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
}) {
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
mStatusCode = response.statusCode;
return super.parseNetworkResponse(response);
}
};
;
// add the request object to the queue to be executed
AppController.getInstance().addToRequestQueue(request_json);
}
JsonArrayRequest request_json = new JsonArrayRequest(AppConfig.login, new JSONArray(params),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
I think you have to replace JsonObjectRequest with JsonArrayRequest once try replacing them like above i did not tried this but hope it helps you.
Your response is a json array
[
{
"emp_id": 43065,
"emp_name": "Rahul Bhandari",
"username": "43065",
"password": null
}
]
but you are making JsonObjectRequest , do a JsonArrayRequest instead
EDIT:
I see you post body is a Json object and you cannot directly send a Json object in JsonArrayRequest , so you have to send the body using getBody() method
example request
JsonArrayRequest jsObjRequest = new JsonArrayRequest
(requestMethod, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//do some thing with response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// handelErrorResponse
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return setHeaders();
}
#Override
public byte[] getBody() {
String body;
// convert your json object to string and send it
body= yourJsonobject.toString();
return body.getBytes();
}
#Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
getHeader(response);
return super.parseNetworkResponse(response);
}
};
addToRequestQueue(jsObjRequest);
These square brackets [ {...}, {...},.. ] represent for a JSONArray. So if your array have only one items, Change JsonObjectRequest to JsonArrayRequest which will return an JSONArray then get the first item from this array.
JsonArrayRequest req = new JsonArrayRequest(urlJsonArry,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject result = response.get(0);
}
}
You're making a request using the object JsonObjectRequest, this mean that your request are expecting a json in the object format like:
{ a: "a", b: "b" }
but your service is responding with a json array that look like:
[{a:"a", b:"b"} , {a:"a1", b:"b1"}]
so, in order to get rid of your error change the way you make your request using JsonArrayRequest
Use this code
if (loginResult != null) {
//for (int i = 0; i < loginResult.length(); i++) {
JSONObject obj = loginResult.getJSONObject(0);
//JSONObject obj = loginResult.getJSONObject(i);
// SQLite database handler
db = new SQLiteHandler(LoginActivity.this);
// Session manager
session = new SessionManager(LoginActivity.this);
session.setLogin(true);
// Inserting row in users table
/*db.addUser(obj.getString("username"), obj.getString("emp_name"), obj.getString("emp_id"), obj.getString("emp_designation"), obj.getString("emp_location"));*/
db.addUser(obj.getString("username"), obj.getString("emp_name"), obj.getString("emp_id"),"","");
Intent intent = new Intent(LoginActivity.this, SelectAuditActivity.class);
startActivity(intent);
finish();
Toast.makeText(LoginActivity.this, "Successfull login...",
Toast.LENGTH_SHORT).show();
//}
} else {
Toast.makeText(LoginActivity.this, "Invalid login credential...", Toast.LENGTH_SHORT).show();
}
return this only from web services
{
"emp_id": 43065,
"emp_name": "Rahul Bhandari",
"username": "43065",
"password": null
}

Using Volley to send JsonObject with Children

I wanna send a notification using Volley to FCM.
The method expects to get the message information under "data".
The problem is that when i use "put" in volley - like here:
JSONObject notificationTitleObject = new JSONObject().put("message_title",notificationTitle);
The line above is deleted from "data".
I have tried to use JsonArray and then putting it as the value of "data".
It didn't work.
If I was writing the desirable result in Json, it will look like that:
{ "data": {
"message_title": "XXXX",
"message": "XXXXX"
"message_image_url": "XXX"
},
"to" : "/topics/Notifications_For_Event_Items"
}
The full code is here:
private void sendNotifToServer() throws JSONException {
rootObject = new JSONObject();
JSONObject notificationTitleObject = new JSONObject().put("message_title",notificationTitle);
JSONObject notificationMessageObject = new JSONObject().put("message",itemName.getText().toString());
JSONObject notificationImageObject = new JSONObject().put("message_image_url",imageUrl);
try {
rootObject.put("to","/topics/Notifications_For_Event_Items");
rootObject.put("data",notificationTitleObject);
rootObject.put("data",notificationMessageObject);
rootObject.put("data",notificationImageObject);
// rootObject.put("data",new JSONObject().put("fragmentType","1"));
}catch (JSONException e){
e.printStackTrace();
}
RequestQueue queue = Volley.newRequestQueue(AddEventItemsActivity.this);
StringRequest request = new StringRequest(Request.Method.POST, notificationUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public byte[] getBody() throws AuthFailureError {
return rootObject.toString().getBytes();
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers = new HashMap<String,String>();
headers.put("Content-Type","application/json");
headers.put("Authorization","key="+notifApiKey);
return headers;
}
};
I think the correct JSONObject is the following:
rootObject = new JSONObject();
JSONObject dataObject = new JSONObject();
dataObject.put("message_title", notificationTitle);
dataObject.put("message", itemName.getText().toString());
dataObject.put("message_image_url", imageUrl);
rootObject.put("data", dataObject);
rootObject.put("to","/topics/Notifications_For_Event_Items");

Android Json Arraylist to Server with Restful Web service

This is my Arraylist which I get from the previous fragment,
listoftags = getArguments().getParcelableArrayList("data");
It works well. Now I have to send this with some parameters like below:
public void volleyJsonObjectRequest(final String SessionID , final String CustomerID, final String ServiceState , final String ServiceID, final String Address, final String PaymentMode, final String CustomerComments , final ArrayList Items){
String REQUEST_TAG = "volleyJsonObjectRequest";
// POST parameters
CustomRequest request = new CustomRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Toast.makeText(SignActivity.this, response.toString(), Toast.LENGTH_SHORT).show();
Log.d("response",""+response.toString());
/* String status = response.optString("StatusMessage");
String actionstatus = response.optString("ActionStatus");
Toast.makeText(getActivity(), ""+status, Toast.LENGTH_SHORT).show();
if(actionstatus.equals("Success"))
{
// Intent i = new Intent(SignActivity.this, LoginActivity.class);
// startActivity(i);
// finish();
}*/
dismissProgress();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Error."+error.toString(), Toast.LENGTH_SHORT).show();
Log.d("response",""+error.toString());
dismissProgress();
}
}) {
/* #Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}*/
public String getBodyContentType()
{
return "application/json; charset=utf-8";
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
JSONArray jsArray = new JSONArray(listoftags);
params.put("SessionID", SessionID);
params.put("CustomerID", CustomerID);
params.put("ServiceState", ServiceState);
params.put("ServiceID", ServiceID);
params.put("Address", Address);
params.put("PaymentMode",PaymentMode);
params.put("CustomerComments",CustomerComments);
params.put("Items",jsArray.toString());
return params;
}
};
AppSingleton.getInstance(getActivity().getApplicationContext())
.addToRequestQueue(request, REQUEST_TAG);
}
but it getting error to me I want to send it like
// server side //
{
"SessionID":"9lm5255sg0ti9",
"CustomerID":"9",
"ServiceState":"Karnataka",
"ServiceID":"3",
"Address":"sfaff",
"PaymentMode":"cash",
"CustomerComments":"this is fine",
"Items":[
{
"ItemId":1,
"Cost":6777,
"Quantity":33333
}
]
}
How can send arraylist, with other strings, as raw data using volley on server.
JsonObjectRequest can be used to execute rest api using json as input.
JsonObject jobj = new JsonObject();
jobj.put("key","value");
jobj.put("key","value");
jobj.put("key","value");
jobj.put("key","value");
JsonObjectRequest request = new JsonObjectRequest(requestURL, jobj, new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
}
});
*Now add this request in request queue of volley.*
Here jobj is containing input parameters. It can contain even json array inside a JsonObject. Let me know in case of any query.
Rather then volley try retrofit. Make pojo model of your object you want to send, you can make that from pojo classes from https://www.jsonschema2pojo.org the send the whole object on restapi
// try the request //
try {
REQUEST QUEUE
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
String URL = url;
JSONObject jsonBody = new JSONObject();
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
Iterator itr = listoftags.iterator();
while(itr.hasNext()){
AddRowItem ad=(AddRowItem)itr.next();
jsonObject.put("ItemId:",1);
jsonObject.put("Cost:",ad.getPrices());
jsonObject.put("Quantity:",ad.getQty());
// Log.d("ItemId:",""+1+" "+"Cost:"+ad.getPrices()+" "+"Quantity:"+ad.getQty());
}
jsonArray.put(jsonObject);
JSON VALUES PUT
jsonBody.put("SessionID", "9kp0851kh6mk3");
jsonBody.put("CustomerID", "9");
jsonBody.put("ServiceState", "Karnataka");
jsonBody.put("ServiceID", "3");
jsonBody.put("Address", "Address Demo");
jsonBody.put("PaymentMode", "cost");
jsonBody.put("CustomerComments", "Android Volley Demo");
jsonBody.put("Items", jsonArray);
final String requestBody = jsonBody.toString();
Log.d("string ---- >",""+requestBody);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
showToast("get value"+response.toString());
try {
JSONObject jObj = new JSONObject(response);
String action = jObj.get("ActionStatus").toString();
String status = jObj.getString("StatusMessage");
{"ActionStatus":"Success","StatusMessage":"Order Created","RefIDName":"OrderID","RefIDValue":19}
showToast("get value"+action);
}
catch (JSONException e)
{
showToast("get error"+e.toString());
Log.d("errorissue",""+e.toString());
}
dismissProgress();
}
}, new Response.ErrorListener() {
// error response //
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
showToast("get error"+error.toString());
dismissProgress();
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
dismissProgress();
}
}
}
// THIS IS THE WAY ISSUE RESLOVED //
THANKS EVERYONE ...

Volley POST REQUEST error 500

JSON:
{
"isRegistrationSuccess":"true"
}
This what my backend should provide while user successfully register in system. I am sending Name, Email and Password as parameters. I am getting 500 error.
/Volley: [188] BasicNetwork.performRequest: Unexpected response code 500 for http://100.100.202.200/mobile/register?name=admin&email=admin#nomail.com&password=admin123
Although, I can see the user information in my backend. Here is my code:
RequestQueue queue = Volley.newRequestQueue(this);
String url_to_parse = getLink(name,email,password).trim();
StringRequest stringReq = new StringRequest(Request.Method.POST, url_to_parse, new Response.Listener<String>() {
#Override
public void onResponse(String response){
try{
Log.d("Response",response);
JSONArray obj = new JSONArray();
boolean isLoginSuccess = Boolean.parseBoolean(obj.getString(0));
if(isLoginSuccess){
onSignupSuccess();
}else{
onSignupFailed();
}
}catch (JSONException e){
e.printStackTrace();
onSignupFailed();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
onSignupFailed();
Log.e("Error",String.valueOf(error.getMessage()));
}
});
queue.add(stringReq);
I am not sure what is wrong I am doing here? How can I solve it?
POST data is given in a protected Map getParams () and not the URL:
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("parametr1","value1");
params.put("parametr2","value2");
params.put("parametr3","value3");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
Fix your url and use JsonObjectRequest
You want to parse a array into a boolean, you have to loop through the array like this:
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray= jsonObject.getJSONArray("example");
if (jsonArray.length() != 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jo = jsonArray.getJSONObject(i);
boolean isLoginSuccess = Boolean.parseBoolean(jo.getString("exampleString"));
}
}

Android Volley POST Parameters

I need to call an api that expects a string array as a POST parameter. So for an example of an API definition:
POST api/names
POST parameter expected is an array of names and some other attributes like below:
{ names: [ "John", "Bill" ], department: "Engineering" }
I am currently using a custom Volley framework as described in the Android documentation but it seems like the parameters from Volley can only be passed as a Map of (String, String as key and value). I already have the array from my Android app, ready to be passed as a post parameter but this Volley expects a String.
I tried to convert my array using Arrays.toString(myStringArray) and passed it like below but it does not work.
String[] namesArray = new String[1];
namesArray[0] = "Bill";
Map<String, String> mapParams = new HashMap<String, String>();
mapParams.put("department", "Computer Science");
mapParams.put("names", Arrays.toString(namesArray));
// Then call the Volley here passing the mapParams.
How can I call the api that expects a String of array when I can only use a String from Volley?
I will give you full code to post JsonObject on volley, through POST method.
JSONObject js = new JSONObject();
try {
js.put("genderType", "MALE");
}
} catch (JSONException e) {
e.printStackTrace();
}
String url = "LINK TO POST/";
// Make request for JSONObject
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
Request.Method.POST, url, js,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Response_Code from Volley" + "\n" + response.toString() + " i am king");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e(TAG, "Error: " + error.getMessage());
NetworkResponse response = error.networkResponse;
if (error instanceof ServerError && response != null) {
try {
String res = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, "utf-8"));
// Now you can use any deserializer to make sense of data
Log.e(TAG, "onErrorResponse: of uploadUser" + res);
// JSONObject obj = new JSONObject(res);
} catch (UnsupportedEncodingException e1) {
// Couldn't properly decode data to string
e1.printStackTrace();
}
}
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}
};
Log.e(TAG, "uploadUser: near volley new request ");
// Adding request to request queue
Volley.newRequestQueue(this).add(jsonObjReq);
}
Put anything you need in the js object with key and its values
Use JsonObjectRequest and simply pass a JSONObject. There's a full example here
public void makePostRequest(final Map<String,String> myMap,String MEDIA_URL,final VolleyResponse callback)
{
VolleySingleton VS;
Log.e("URL",MEDIA_URL);
VS=VS.getInstance();
RequestQueue rq=VS.getRequestQueue();
StringRequest stringRequest = new StringRequest(Request.Method.POST,MEDIA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
callback.onSuccess(s);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
callback.onError();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new Hashtable<String, String>();
Iterator<Map.Entry<String, String>> iterator = myMap.entrySet().iterator();
while(iterator.hasNext()) {
Map.Entry<String,String> pairs = (Map.Entry<String,String>)iterator.next();
String value = pairs.getValue();
String key = pairs.getKey();
params.put(key,value);
Log.e("Key","Value"+value);
}
return params;
}
};
//Creating a Request Queue
// RequestQueue requestQueue = Volley.newRequestQueue(this);
DefaultRetryPolicy retryPolicy = new DefaultRetryPolicy(0, -1, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(retryPolicy);
//Adding request to the queue
rq.add(stringRequest);
}
Where the VolleyResponse is a simple custom interface like this
public interface VolleyResponse {
void onSuccess(String resp);
void onError();
}

Categories

Resources