So heres my stuff basic getParams post method in volley but I don't know how to send array to backend can someone help?
#Override
protected Map<String, String> getParams() {
JSONObject jsonObject = new JSONObject();
//looping throught recyclerview
for (int i = 0; i < CustomCreateGroupAdapter.dataModelArrayList.size(); i++){
//getting selected items
if(CustomCreateGroupAdapter.dataModelArrayList.get(i).getSelected()) {
try {
//putting all user ids who you selected into jsonObject
jsonObject.put("params", CustomCreateGroupAdapter.dataModelArrayList.get(i).getOthersid());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Map<String, String> params = new HashMap<String, String>();
params.put("params",jsonObject.toString());
return params;
}
You should add all those values to a JSONArray and then add this JSONArray to your JSONObject. You could also add all objects to a simple array and then get the corresponding JSONArray by calling new JSONArray(your_array);
Add the objects of your payload to a JSONArray, then use JSONArray.toString() to pass the payload to a JsonRequest as the requestBody.
Related
How to pass the object value in hashmap? I was referring to the details.getString("jobcategory") to send the value inside the hashmap key jobscategory> I'm using Android Volley. Thank you
JSONObject json = new JSONObject(response1);
final JSONArray array = json.getJSONArray("Jobs");
for (int i = 0; i < array.length(); i++) {
JSONObject jobs = array.getJSONObject(i);
String companyDetails = jobs.getString("jobdetails");
JSONObject details = new JSONObject(companyDetails);
jobcat = details.getString("jobcategory");
I need to pass the value of jobcat = details.getString("jobcategory") which I know is 16 to Hashmap;
Map<String, String> data = new HashMap<>();
data.put("barangayid", preferences.getString("sessionBrgyID", null));
data.put("jobcategory", jobcat);
data.put("function", "get_user_jobs_by_category");
System.out.println(data);
return data;
but I get an error a null value.
You need to override getParams in the volley's request.
#Override
protected Map<String, String> getParams() {
Map<String, String> data = new HashMap<>();
data.put("barangayid", preferences.getString("sessionBrgyID", null));
data.put("jobcategory", jobcat);
data.put("function", "get_user_jobs_by_category");
System.out.println(data);
return data;
}
I am using Volley to send data to the server, Here I am unable to find the way to send both String and Array at a time in a single request.
I can send the array like:
Map<String, List<String>> jsonParams = new HashMap<>();
jsonParams.put("names", my_names_list);
And also I can send String like:
Map<String, String> jsonParams = new HashMap<>();
jsonParams.put("user_id", userId);
but how to send both at a time?
like:
Map<String, String> jsonParams = new HashMap<>();
jsonParams.put("user_id", userId);
jsonParams.put("names", my_names_list); // here it is expecting String but I want to send array of strings to server
the expected JSON request should be like:
{
"user_id": "1",
"names" : ["abc, "cdf", "efg"]
}
I think you can merge the string and array into a single json and then send the json to the server.Example
public class Member
{
private String name;
private List<String> skills;
//getter and setter at lower
}
Use the GSON library for make this model class to json.
Member mem = createjsonobject();
Gson gson=new Gson();
String json=gson.toJson(mem);
//Pass this json to the server and at server side you can seperate the string and array
private static Member createjsonObject()
{
Member member= new Member();
member.setName("Rishabh");
List<String> skill=new ArrayList<>();
skill.add("Java");
skill.add("C#");
skill.add("Android");
member.setSkills(skill);
return member;
}
I solved my problem like this-
protected Map<String, String> getParams() throws AuthFailureError {
JSONArray words_ar = new JSONArray();
for(int i=0;i<exercise.getWord_list().size();i++){
JSONObject word_ob = new JSONObject();
try {
word_ob.put("id",(i+1)+"");
word_ob.put("learn",exercise.getWord_list().get(i).getLearn_str());
word_ob.put("native",exercise.getWord_list().get(i).getNative_str());
words_ar.put(word_ob);
} catch (JSONException e) {
e.printStackTrace();
}
}
Map<String, String> params = new HashMap<>();
params.put("user", prefs.getUserId()+"");
params.put("title", exercise.getTitle());
params.put("words", words_ar+"");
return params;
}
Try using custom JSONObject. For your above example request, you can create a JSON object as below
try {
String[] names = {"abc", "cdf", "efg"};
String userId = "user_id";
JSONArray jsonArray = new JSONArray();
for(String n : names) {
jsonArray.put(n);
}
JSONObject jsonParams = new JSONObject();
jsonParams.put("names", jsonArray);
jsonParams.put("userId", userId);
} catch (JSONException e) {
e.printStackTrace();
}
try this one ; put the names in array than:
for(int i = 0;i<yourArrayLength;i++){
params.put("names"+i, my_names_list[i]);
}
hope it will help
I have to a JSONObject, especially the "data" content, in Android from a WebService, then I have to print it into a ListView or a Table.
This is my JSON:
{
"status":200,
"status_message":"Direct ways found",
"data":[{"codice_linea":"5","partenza":"Longa","ora_partenza":"17:34:00","arrivo":"Schiavon","ora_arrivo":"17:38:00"}]
}
Let
response = {
"status":200,
"status_message":"Direct ways found",
"data":[{"codice_linea":"5","partenza":"Longa","ora_partenza":"17:34:00","arrivo":"Schiavon","ora_arrivo":"17:38:00"}]
}
String status = response.get("status"); // status = 200
String status_message = response.get("status_message"); // status_message = "Direct ways found"
JSONArray message = response.getJSONArray("data");
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for (int i = 0; i < message.length(); i++) {
HashMap<String, String> hm = new HashMap<String, String>();
JSONObject temp = message.getJSONObject(i);
hm.put("codice_linea",temp.getString("codice_linea"));
hm.put("partenza",temp.getString("partenza"));
hm.put("ora_partenza",temp.getString("ora_partenza"));
hm.put("arrivo",temp.getString("arrivo"));
....................................
.............................
aList.add(hm);
}
Finally all your JSON data is prased to List aList.
Then use custom Listview to show this data in Listview
Here is the full tutorial http://www.androidhive.info/2014/07/android-custom-listview-with-image-and-text-using-volley/
Hope this solved your problem.
Try this
JSONObject jsonObject = new org.json.JSONObject(YourJsonResponse);
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
jsonArray.getJSONObject(i).getString("codice_linea");
jsonArray.getJSONObject(i).getString("partenza");
jsonArray.getJSONObject(i).getString("ora_partenza");
......
}
I assume you effort to get this Json in android , if i right try this:
Paste your example Json in Json Schema 2 Pojo , and site will generate Pojo classes
Convert your Json response to Pojo class with Gson
Add this line to your dependencies : compile 'com.google.code.gson:gson:2.4'
Convert Json result to Pojo :
Gson gson = new Gson();
YourPojo yourpojo= gson.fromJson(jsonresponse, YourPojo.class);
And handle result whatever you want .
If you didnt effort anything
Go to google and search how to handle Json in android or how to connect web service , for example you can search : HttpUrlConnection , OkHttp, Retrofit ...
What you seem wanting to do is to re-create an existing JSONObject that is contained in an array.
If you use the JSONObject from the Android tools, you can use getJSONObject and getJSONArray.
According to the Documentation:
Returns the value mapped by name if it exists and is a JSONArray, or throws otherwise.
Returns the value mapped by name if it exists and is a JSONObject, or throws otherwise.
See here for more details.
You have to do something like that:
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
Your-url-JsonObj, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
// Parsing json object response
// response will be a json object
String status = response.getString("status");
String status_message = response.getString("status_message");
JSONArray jsonArray =jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
jsonArray.getJSONObject(i).getString("codice_linea");
jsonArray.getJSONObject(i).getString("partenza");
jsonArray.getJSONObject(i).getString("ora_partenza");
jsonArray.getJSONObject(i).getString("arrivo");
jsonArray.getJSONObject(i).getString("ora_arrivo");}
} 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();
// hide the progress dialog
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
This is the Nested Json Array that we are getting as a respone from server side.
Response:
"[[{\"userID\":\"1\",\"roleID\":\"1\",\"userName\":\"GHG Admin\",\"email\":\"vikas.rana#redalkemi.in\",\"password\":\"b2314cd68cdfb7545dacd0b4ecf6a190\",\"userImage\":\"image12.jpg\",\"dtAdded\":\"2013-05-28\",\"dtUpdated\":\"2013-05-28\",\"enumStatus\":\"A\"}],[{\"settingID\":\"1\",\"moduleName\":\"event\",\"displayName\":\"Ev\\\"ent's1\",\"enumStatus\":\"E\"},{\"settingID\":\"2\",\"moduleName\":\"notice\",\"displayName\":\"Not\\\"ic'es\",\"enumStatus\":\"E\"},{\"settingID\":\"3\",\"moduleName\":\"quote\",\"displayName\":\"Qu\\\"ot'es\",\"enumStatus\":\"E\"},{\"settingID\":\"6\",\"moduleName\":\"crawlingtext\",\"displayName\":\"Crawling Text\",\"enumStatus\":\"D\"}]]"
Here is the code for getting this, but while executing complier goes in catch JSON exeception.
JSONArray arr;
try {
if (response != null) {
System.out.println(response);
arr= new JSONArray(response);
JSONArray a1= arr.getJSONArray(0);
JSONObject obj1= a1.getJSONObject(0);
map = new HashMap<String, String>();
// Retrive JSON Objects
map.put("userID", obj1.getString("userID"));
map.put("userName", obj1.getString("userName"));
data = new ArrayList<HashMap<String, String>>();
// Set the JSON Objects into the array
data.add(map);
id = (String) map.get("userID");
ID=Integer.parseInt(id);
name = (String) map.get("userName");
System.out.println(id+name);
JSONArray a2=arr.getJSONArray(1);
for (int i = 0; i < a2.length(); i++) {
JSONObject obj2= a2.getJSONObject(i);
map = new HashMap<String, String>();
map.put("settingID", obj2.getString("settingID"));
map.put("moduleName", obj2.getString("moduleName"));
data = new ArrayList<HashMap<String, String>>();
// Set the JSON Objects into the array
data.add(map);
String Module=(String)map.get("moduleName");
System.out.println("MODULE="+Module);
}}
}
catch ( JSONException e ) {
System.out.println("JSON Error parsing JSON");
}
It looks like you haven't removed the escape sequences from the JSON response before parsing it. Do this before you parse the response
response.toString().replaceAll("\\\\","");
arr= new JSONArray(response);
....
Here is the way i was going to do it but I get an error in the line JSONObject c = orders.getJSONObject(i);:
Error:(95, 57) error: incompatible types: int cannot be converted to String
Maybe there is a better way of doing this process , please help
#Override
protected String doInBackground(String... params) {
try {
List<NameValuePair> param = new ArrayList<NameValuePair>();
JSONObject json = jsonParser.makeHttpRequest(URL_ORDERS, "GET",
param, token);
JSONObject data = json.getJSONObject("data");
JSONObject orders = data.getJSONObject("orders");
Log.d("JSON DATA", data.toString());
Log.d("JSON ORDERS", orders.toString());
for (int i = 0; i < orders.length(); i++) {
JSONObject c = orders.getJSONObject(i);
imageurl = c.getString(TAG_IMAGE);
Log.d("IDK", imageurl);
title = c.getString(TAG_TITLE).substring(0, 20);
price = c.getString(TAG_PRICE);
status = c.getString(TAG_PSTATUS);
symbol = c.getString(TAG_PRICESYMBOL);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_PRICE, price);
map.put(TAG_PSTATUS, status);
map.put(TAG_PRICESYMBOL, symbol);
map.put(TAG_IMAGE, imageurl);
orderList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Your orders object is a JSONObject (with the order IDs being used as keys and the complete order objects as values), but in your code you're treating it as a JSONArray.
You probably want to change your loop as follows:
Iterator<String> orderIterator = orders.keys();
while (orderIterator.hasNext()) {
JSONObject c = orders.getJSONObject(orderIterator.next());
// ...
}
The call to keys() will return an iterator over the object's keys (in this case order IDs). Then it's just a matter of using the iterator to loop over all the keys, and retrieve each order object using getJSONObject.