Using Volley to send JsonObject with Children - android

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");

Related

How to send JSON Array of objects using Volley in android

I want to send some bulk data to my php server so I constructed JSON Array. But how to send it using volley in Android. Could you anybody help. I already tried many ways but didnt work.
Below is my code for the dataset
JSONArray jsData = new JSONArray();
JSONObject others = new JSONObject();
while(crsrallansr.isAfterLast() == false) {
JSONObject Inner = new JSONObject();
try {
Inner.put("qid",crsrallansr.getString(crsrallansr.getColumnIndex("qid")));
Inner.put("qstn",crsrallansr.getString(crsrallansr.getColumnIndex("qid")));
Inner.put("result",crsrallansr.getString(crsrallansr.getColumnIndex("qid")));
} catch (JSONException e) {
e.printStackTrace();
}
jsData.put(Inner);
crsrallansr.moveToNext();
xx++;
}
Fixed the problem using StringRequest like :
reqPostanswers = new StringRequest(Request.Method.POST, url,new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("posting info :",response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Log.i("posting error :",error.toString());
}
}){
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("user", thisuser);
params.put("answers",jsData.toString());
params.put("lickey","1761");
return params;
}
};
answerpostQueue = Volley.newRequestQueue(getApplicationContext());
answerpostQueue.add(reqPostanswers);
At the server side ( php ); the code is as follows :
$answers=json_decode($_POST['answers']);
foreach ($answers as $answer) {
$answer=json_encode($answer);
echo $answer;
$answer=json_decode($answer);
$uname=$_POST['user'];
$qid=$answer->qid;
$result=$answer->result;
$qstn=$answer->qstn;

How to solve Error in json parsing using volley POST?

Hi I am using volley as JSON Parsing. I am using POST method and sending parameters in post request. I am getting following error when parsing the data, I am getting following error. I want to use volley. I have tried with JsonArrayRequest but it does not allow to send parameters as JSONObject,which I am using in my code.
org.json.JSONArray cannot be converted to JSONObject
Request is like
{
"city":"acd",
"user_id":"82",
"phone_number1":"1232131231",
"my_type":"asf"
}
Response is like
[{
"name":"dfdfd",
}]
Following is my code
private void Search_Refer() {
//initialize the progress dialog and show it
progressDialog = new ProgressDialog(SearchReferNameActivity.this);
progressDialog.setMessage("Please wait....");
progressDialog.show();
try {
JSONObject jsonBody = new JSONObject();
jsonBody.put("city", "acb");
jsonBody.put("user_id", "82");
jsonBody.put("phone_number1", "12332123231");
jsonBody.put("my_type", "asf");
JsonObjectRequest jsonOblect = new JsonObjectRequest(Request.Method.POST, Constants.BASE_URL1+"api/lab/search", jsonBody, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
Log.e("Search EROOR", response.toString());
try {
JSONArray itemArray=new JSONArray(response);
dataModelArrayList = new ArrayList<>();
for (int i = 0; i < itemArray.length(); i++) {
SearchModel playerModel = new SearchModel();
JSONObject dataobj = itemArray.getJSONObject(i);
//playerModel.setProduct_name(dataobj.getString("name"));
playerModel.setRadiology_store_first_name(dataobj.getString("radiology_store_first_name"));
dataModelArrayList.add(playerModel);
}
} catch (JSONException e) {
e.printStackTrace();
}
progressDialog.dismiss();
/* Intent intent = new Intent(SearchReferNameActivity.this, SearchResult.class);
intent.putExtra("Search_result", dataModelArrayList);
startActivity(intent);*/
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Response: " + error.toString(), Toast.LENGTH_SHORT).show();
System.out.println("Search Eroor"+error.toString());
progressDialog.dismiss();
}
}){
#Override
public String getBodyContentType() {
return "application/json";
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", "Bearer "+deviceToken);
return headers;
}
};
jsonOblect.setRetryPolicy(new DefaultRetryPolicy(
10000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MyApplication.getInstance().addToRequestQueue(jsonOblect,"postrequest");
} catch (JSONException e) {
e.printStackTrace();
}
// Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_LONG).show();
}
Use JsonArrayRequest or StringRequest in place of JsonObjectRequest
JsonArrayRequest
change the following response parameter to JSONArray
Instead of new Response.Listener<JSONObject> Use new Response.Listener<JSONArray>
// JSONArray insated of JSONObject
public void onResponse(JSONArray response) {
}
Use Below code
StringRequest stringRequest = new StringRequest(Request.Method.POST, "api/lab/search", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, 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("city", "abcd");
params.put("user_id", "82");
params.put("phone_number1", "01235467895");
params.put("my_type", "asf");
return params;
}
};

How to parse JSON using Volley?

i have some json output like this
{
"message": "success",
"battery": "AHAJAJ1DH13T0021",
"data": {
"id": 6,
"userId": 3,
"shopId": 1,
"transactionStatus": "PENDING",
"expiredAt": "2019-01-04T03:01:18.878Z",
"updatedAt": "2019-01-04T02:01:18.916Z",
"createdAt": "2019-01-04T02:01:18.916Z",
"paymentId": null,
"batteryNo": null
},
"shopData": {
"id": 1,
"name": "test1",
"tel": "555",
"address": "cikarang",
"description": "showroom",
"latitude": "-6.307923199999999",
"longitude": "107.17208499999992",
"open_time": "10.00",
"battery_available": 16,
"battery_booked": 1,
"status": 1,
"createdAt": "2018-12-28T03:59:55.156Z",
"updatedAt": "2019-01-04T02:01:18.940Z"
}
}
and i implement using volley like this
StringRequest request = new StringRequest(Request.Method.POST, ApiService.ORDER_BATTERY, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
BookBattery bookBattery = new BookBattery();
JSONObject jsonObject = new JSONObject(response);
if (!jsonObject.has("success")) {
JSONObject object = jsonObject.getJSONObject("battery");
String data = object.getString("");
JSONArray jsonArray = jsonObject.getJSONArray("data");
} else {
Log.e("Your Array Response", "Data Null");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error is ", "" + error);
}
}) {
//This is for Headers If You Needed
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json; charset=UTF-8");
params.put("token", TokenUser);
return params;
}
//Pass Your Parameters here
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("shopId", String.valueOf(shopId));
//params.put("Pass", PassWord);
return params;
}
};
AppController.getInstance().addToRequestQueue(request, tag_json_obj);
but not working, please help thanks a lot
Use http://jsonviewer.stack.hu/ [To see json data structure]
braces {} its an JSONObject
brackets [] its an JSONArray
public void parseJson() {
try {
JSONObject jsonObject = new JSONObject(jsonParsing);
boolean isSuccess = jsonObject.getString("message").contains("success");
if (isSuccess) {
JSONObject jsonObjectData = jsonObject.getJSONObject("data");
String userId = jsonObject.getString("userId");
JSONObject jsonObjectShopData = jsonObject.getJSONObject("shopData");
String name = jsonObject.getString("tel");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
You are not getting JSONArray anywhere, your response object has multiple JSONObject
JSONObject jsonObject = new JSONObject(response);
if (!jsonObject.has("success")) {
JSONObject object = jsonObject.getJSONObject("battery");
JSONOnject jsonObject2= jsonObject .getJSONObject("data");// here you need to change.
String batteryNo=jsonObject2.getJSONObject("batteryNo");
JSONOnject jsonObject3= jsonObject1.getJSONObject("shopData");
String address=jsonObject2.getJSONObject("address");
} else {
Log.e("Your Array Response", "Data Null");
}
You can use some lib for Volley (e.g. VolleyEx), together with Gson, to parse the JSON Object to a Map in Java.
i.e. using GsonObjectRequest instead of StringRequest
developer.android.com has the code, but there are also libs doing that for you.
example HERE
Try this
StringRequest request = new StringRequest(Request.Method.POST, ApiService.ORDER_BATTERY, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
BookBattery bookBattery = new BookBattery();
JSONObject jsonObject = new JSONObject(response);
String message = jsonObject.getString("message");
if (message.equalsIgnoreCase("success")) {
String battery = jsonObject.getString("battery");
JSONObject dataObject = jsonObject.getJSONObject("data");
JSONObject shopDataObject = jsonObject.getJSONObject("shopData");
int dataId = dataObject.getInt("id");
int dataUserId = dataObject.getInt("userId");
int dataShopId = dataObject.getInt("shopId");
} else {
Log.e("Your Array Response", "Data Null");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error is ", "" + error);
}
}) {
//This is for Headers If You Needed
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json; charset=UTF-8");
params.put("token", TokenUser);
return params;
}
//Pass Your Parameters here
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("shopId", String.valueOf(shopId));
//params.put("Pass", PassWord);
return params;
}
};
AppController.getInstance().addToRequestQueue(request, tag_json_obj);
here i only parse "id", "userId" & "shopId" from dataObject. Rest can be parse in similar way.
Before do it I will suggest you please read about the json Array and Json Object.
Here the solution.
HashMap<String, String> params = new HashMap<String, String>();
params.put("your json parameter name", json parameter value);
// params.put("device_id", deviceID);
Log.d("response11", String.valueOf(params));
String Url ="your server url";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Url,
new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG + "JO", String.valueOf(response));
try {
String msgObject = response.getString("message");
Log.d("response","msgObject");
}catch (JSONException e){
String jsonExp = e.getMessage();
Log.d(TAG + "JE", jsonExp);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
String volleyErr = error.getMessage();
Log.d(TAG + "VE", volleyErr);
}
});
requestQueue.add(jsonObjectRequest);
this sufficient for print you server response. check response in logcat.

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