Android Volley send Array as a param along with String - android

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

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

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;
}

android volley how to send array?

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.

Array as parameter in retrofit

I have an issue with my parameters passing in retrofit, My problem is need to send int array ([3,1,2]) as one of the parameters in a POST method with retrofit 2, other parameters are as string. (ex: tips - "10", amount-"100", service-ids -[3,1,2]). How can send parameters like above in example.
You can use ArrayList such as:
#FormUrlEncoded
#POST("service_name")
void functionName(
#Field("yourarray[]") ArrayList<String> learning_objective_uuids, #Field("user_uuids[]") ArrayList<String> user_uuids, #Field("note") String note,
Callback<CallBackClass> callback
);
You can follow this link.
Or you could use JSONObject like so:
#POST("demo/rest/V1/customer")
Call<RegisterEntity> customerRegis(#Body JsonObject registrationData);
registrationData:
private static JsonObject generateRegistrationRequest() {
JSONObject jsonObject = new JSONObject();
try {
JSONObject subJsonObject = new JSONObject();
subJsonObject.put("email", "abc#xyz.com");
subJsonObject.put("firstname", "abc");
subJsonObject.put("lastname", "xyz");
jsonObject.put("customer", subJsonObject);
jsonObject.put("password", "password");
} catch (JSONException e) {
e.printStackTrace();
}
JsonParser jsonParser = new JsonParser();
JsonObject gsonObject = (JsonObject) jsonParser.parse(jsonObject.toString());
return gsonObject;
}
You can define an object reflecting the structure of the POST body:
#POST("/pathtopostendpoint")
Call<ResponseObject> postFunction(#Body final RequestBody body);
with your RequestBody being defined as following (if you use the GSON converter, tweak the naming of the field with #SerializedName):
class RequestBody {
String tips;
String amount;
int[] serviceIds;
RequestBody(final String tips, final amount String, final int[] serviceIds) {
this.tips = tips;
this.amount = amount;
this.serviceIds = serviceIds;
}
}
and build the request call like that:
final Call<ResponseObject> call = retrofitService.postFunction(
new RequestBody("10", "100", new int[]{ 3, 1, 2 })
);

convert a json object response into array and get both key and value android

I have a json response which is dynamic such that even the key name and index no.can change
{
"Assigned": {
"DC": 7,
"EmpCode": "E0104",
"FS": 8
}
}
I want to convert it into JsonArray and fetch all the key names and values dynamically under the object 'Assigned'.But I am only getting the value name by trying this.
try {
//converting dynamic jsonobject to json array and fetching value as well as key name
JSONObject jsonObject = response.getJSONObject("Assigned");
Iterator x = jsonObject.keys();
JSONArray jsonArray = new JSONArray();
while (x.hasNext()) {
String key = (String) x.next();
jsonArray.put(jsonObject.get(key));
}
Toast.makeText(RolesActivity.this,jsonArray.toString(), Toast.LENGTH_LONG).show();
Log.d("jsonarray",jsonArray.toString());
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(RolesActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
}
You can get the JSONObject's keys list by calling JSONObject.keys() (as Iterator), or JSONObject.names() (as JSONArray)
After that you can iterate through the keys, and get each key's value by using JSONObject.getString(key)
First create a pojo class
private HashMap<String, String> parseResponse(){
String json = ""; // your json string
Gson gson = new Gson();
Response response = gson.fromJson(json, Response.class)
return response.getAssigned();
}
public class Response {
#SerializedName("Assigned")
private HashMap<String, String> assigned;
public HashMap<String, String> getAssigned() {
return assigned;
}
}
than parse with Gson library. You can read key and values from assigned Hashmap.

JSONObject parsing

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.

Categories

Resources