I have a problem in using volley Rest API Post Request
I am not sure is it required to use Map but here I didn't use it.
I'm trying to update my jSONArray from this :
[
{
"id": 1,
"num1": "1",
"num2": "0",
"num3": "1",
"num4": "0"
}
]
into this :
[
{
"id": 1,
"num1": "1",
"num2": "1",
"num3": "1",
"num4": "0"
}
]
Following is my code( I used volley Post request for this ) :
RequestQueue queue = Volley.newRequestQueue(Rele.this);
String url = "https://mysite.dev/fdfh2g/data";
JsonArrayRequest request = new JsonArrayRequest
(Request.Method.POST, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Integer num2val = 1 ;
try {
JSONObject Info = response.getJSONObject(0);
Info.put("num2",num2val);
}catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "error", Toast.LENGTH_SHORT).show();
}
});
queue.add(request);
but instead I'm getting this :
[
{
"id": 1,
"num1": "1",
"num2": "1",
"num3": "1",
"num4": "0"
},
{
"id": 2
}
]
I am getting response from API as a JSONarray and I can get the data into my arraymodel but the problem is I need some specific data from one array and I don't have any idea how to do that.
the array is:
"history": [
{
"id": "20",
"code": "mcw_5b97de588ce0c",
"date": "2018-09-11 17:25:12",
"status": "1",
"name": "a:1:{s:7:\"english\";s:9:\"rent bill\";}",
"img": "shop.png"
}
I want the English, S:9 and the rent bill data from name.
I am posting my code here so you can understand what I have done and what mistake i'm committing.
public void shopListing()
{
showSimpleProgressDialog(this, "Loading...","Fetching Shops History",false);
StringRequest stringRequest = new StringRequest(Request.Method.POST, shopurl,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("strrrrr", ">>" + response);
try {
JSONObject obj = new JSONObject(response);
//if(obj.optString("status").equals("true")){
dataModelArrayList = new ArrayList<>();
JSONArray dataArray = obj.getJSONArray("history");
for (int i = 0; i < dataArray.length(); i++) {
shopModel playerModel = new shopModel();
JSONObject dataobj = dataArray.getJSONObject(i);
playerModel.setId(dataobj.getString("id"));
playerModel.setName(dataobj.getString("name"));
playerModel.setDetails(dataobj.getString("date"));
dataModelArrayList.add(playerModel);
}
setupListview();
// }
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
String api = getApi_key();
String user = getUser_key();
Map<String, String> param = new HashMap<> ();
param.put("api_key", api);
param.put("user_key", user);
return param;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Your server response is not good. instead of sending name as a string to you, it should return you "name" as an object like this:
"history": [
{
"id": "20",
"code": "mcw_5b97de588ce0c",
"date": "2018-09-11 17:25:12",
"status": "1",
"name":
{
"s":7,
"subject":"english",
"s":9,
"any_key":"rent bill"
},
"img": "shop.png"
}
I feel like server is returning you code string which you have written to process request from client. Please double check.
This is the example of ArrayList that i need to fetch, how to fetch this Arrays? Im using GET method of volley to fetch this Array and show in Recycler View.
[
{
"_id": "a2a1",
"name": "Flower",
"image": {
"_id": "a2a2",
"name": "flower.jpg",
"url": "/uploads/c8c8c.jpg",
"related": [
"a2a1"
],
"id": "0a2a2"
},
},
{
"_id": "433d",
"name": "Bouquet",
"id": "433d",
"image": {
"_id": "433e",
"name": "baloon.jpg",
"url": "/uploads/247db.jpg",
"related": [
"433d"
],
"id": "433e"
},
}]
This is my code by using Get method of Volley to fetch the array, i already put the correct api but i didnt get the list of the array.
private void FlowerList(){
StringRequest request = new StringRequest(
Request.Method.GET,
ServerApi.URL_FLOWER,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Gson gson = new GsonBuilder().create();
if(response != null) {
JSONObject json = null;
try {
json = new JSONObject(response);
FlowerModel[] models = gson.fromJson(String.valueOf(json.getJSONArray(null)), FlowerModel[].class);
flowerAdapter.addBatch(Arrays.asList(models));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
Volley.newRequestQueue(getContext()).add(request);
}
if you are using Gson verson 2.8' then
try {
json = new JSONObject(response);
ArrayList<FlowerModel> models = gson.fromJson(response, TypeToken.getParameterized(ArrayList.class, FlowerModel.class).getType());
//flowerAdapter.addBatch(Arrays.asList(models));
} catch (JSONException e) {
e.printStackTrace();
}
for older version
try {
json = new JSONObject(response);
ArrayList<FlowerModel> models = gson.fromJson(response, new TypeToken<ArrayList<FlowerModel>>(){}.getType(););
//flowerAdapter.addBatch(Arrays.asList(models));
} catch (JSONException e) {
e.printStackTrace();
}
try this....i have modified your code
ArrayList<String> stringArrayList;
String id1,name,id2;
StringRequest request = new StringRequest(
Request.Method.GET,
ServerApi.URL_FLOWER,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Gson gson = new GsonBuilder().create();
if(response != null) {
JSONObject json = null;
try {
json = new JSONObject(response);
JSONArray jsonArray=json.getJSONArray("Your_response_arrayName");
stringArrayList=new ArrayList<>();
for(i=0;i<jsonArray.length;i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
stringArrayList.add(jsonObject);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
Volley.newRequestQueue(getContext()).add(request);
}
hope this will help you
when receiving my json from my loop it comes as one big object
how do I prevent this can someone point me in the right direction or documents.
Log....
W/System.err: org.json.JSONException: Value {"1":{"id":1,"name":"Bitcoin","symbol":"BTC","website_slug":"bitcoin","rank":1,"circulating_supply":17153487,"total_supply":17153487,"max_supply":21000000,"quotes":{"USD":{"price":6720.93,"volume_24h":4367200000,"market_cap":115287385383,"percent_change_1h":-0.09,"percent_change_24h":2.07,"percent_change_7d":3.26}},"last_updated":1531828586},"1027":{"id":1027,"name":"Ethereum","symbol":"ETH","website_slug":"ethereum","rank":2,"circulating_supply":100744923,"total_supply":100744923,"max_supply":null,"quotes":{"USD":{"price":472.777,"volume_24h":1774520000,"market_cap":47629882298,"percent_change_1h":-0.45,"percent_change_24h":0.3,"percent_change_7d":5.32}},"last_updated":1531828591},"52":{"id":52,"name":"XRP","symbol":"XRP","website_slug":"ripple","rank":3,"circulating_supply":39262444717,"total_supply":99991916481,"max_supply":100000000000,"quotes":{"USD":{"price":0.473278,"volume_24h":269811000,"market_cap":18582051311,"percent_change_1h":-0.18,"percent_change_24h":2.43,"percent_change_7d":4.17}},"last_updated":1531828571},"1831":{"id":1831,"name":"Bitcoin Cash","symbol":"BCH","website_slug":"bitcoin-cash","rank":4,"circulating_supply":17242013,"total_supply":17242013,"max_supply":21000000,"quotes":{"USD":{"price":793.963,"volume_24h":471637000,"market_cap":13689519971,"percent_change_1h":-0.47,"percent_change_24h":3.58,"percent_change_7d":12.07}},"last_updated":1531828592},"1765":{"id":1765,"name":"EOS","symbol":"EOS","website_slug":"eos","rank":5,"circulating_supply":896149492,"total_supply":900000000,"max_supply":1000000000,"quotes":{"USD":{"price":7.94815,"volume_24h":666448000,"market_cap":7122730586,"percent_change_1h":-0.29,"percent_change_24h":2.5,"percent_change_7d":6.31}},"last_updated":1531828590},"2":{"id":2,"name":"Litecoin","symbol":"LTC","website_slug":"litecoin","rank":6,"circulating_supply":57444758,"total_supply":57444758,"max_supply":84000000,"quotes":{"USD":{"price":83.7447,"volume_24h":283495000,"market_cap":4810693998,"percent_change_1h":-0.17,"percent_change_24h":1.63,"percent_change_7d":8.91}},"last_updated":1531828567},"512":{"id":512,"name":"Stellar","symbol":"XLM","website_slug":"stellar","rank":7,"circulating_supply":18766530971,"total_supply":104125061584,"max_supply":null,"quotes":{"USD":{"price":0.231804,"volume_24h":49352700,"market_cap":4350156945,"percent_change_1h":-0.94,"percent_change_24h":0.8,"percent_change_7d":17.92}},"last_updated":1531828584},"2010":{"id":2010,"name":"Cardano","symbol":"ADA","website_slug":"cardano","rank":8,"circulating_supply":25927070538,"total_supply":31112483745,"max_supply":45000000000,"quotes":{"USD":{"price":0.152682,"volume_24h":86195700,"market_cap":3958596984,"percent_change_1h":0.16,"percent_change_24h":1.2,"percent_change_7d":15.48}},"last_updated":1531828594},"1720":{"id":1720,"name":"IOTA","symbol":"MIOTA","website_slug":"iota","rank":9,"circulating_supply":2779530283,"total_supply":2779530283,"max_supply":2779530283,"quotes":{"USD":{"price":1.06608,"volume_24h":45845200,"market_cap":2963201644,"percent_change_1h":-0.49,"percent_change_24h":0.44,"percent_change_7d":8.21}},"last_updated":1531828590},"825":{"id":825,"name":"Tether","symbol":"USDT","website_slug":"tether","rank":10,"circulating_supply":2707140346,"total_supply":3080109502,"max_supply":null,"quotes":{"USD":{"price":1.00215,"volume_24h":2728850000,"market_cap":2712960697,"percent_change_1h":0.11,"percent_change_24h":0.45,"percent_change_7d":-0.16}},"last_updated":1531828588},"1958":{"id":1958,"name":"TRON","symbol":"TRX","website_slug":"tron","rank":11,"circulating_supply":65748111645,"total_supply":99000000000,"max_supply":null,"quotes":{"USD":{"price":0.0367706,"volume_24h":191259000,"market_cap":2417597514,"percent_change_1h":0.03,"percent_change_24h":1.55,"percent_change_7d":8.49}},"last_updated":1531828593},"1376":{"id":1376,"name":"NEO","symbol":"NEO","website_slug":"neo","rank":12,"circulating_supply":65000000,"total_supply":100000000,"max_supply":100000000,"quotes":{"USD":{"price":36.2949,"volume_24h":128189
here is my code for the request
public ArrayList getCoin () {
firstlist.clear();
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
Constants.URL_JSON, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray coinArray = response.getJSONArray("data");
for (int i = 0; i < coinArray.length(); i++) {
JSONObject coinOBJ = coinArray.getJSONObject(i);
CoinMarketAPI coin = new CoinMarketAPI();
// coin.setId(coinOBJ.getString("id"));
//coin.setName(coinOBJ.getString("name"));
//coin.setSymbol(coinOBJ.getString("symbol"));
//coin.setWebsite_slug(coinOBJ.getString("website_slug"));
// coin.setRank(coinOBJ.getString("rank"));
// coin.setCirculating_supply(coinOBJ.getString("circulating_supply"));
// coin.setTotal_supply(coinOBJ.getString("total_supply"));
// coin.setQuotes(coinOBJ.getString("quotes"));
// coin.setUSD(coinOBJ.getString("USD"));
// coin.setPrice(coinOBJ.getString("price"));
Log.d(TAG, coin.getName());
firstlist.add(coin);
}
JSON
{
"data": {
"1": {
"id": 1,
"name": "Bitcoin",
"symbol": "BTC",
"website_slug": "bitcoin",
"rank": 1,
"circulating_supply": 17008162.0,
"total_supply": 17008162.0,
"max_supply": 21000000.0,
"quotes": {
"USD": {
"price": 9024.09,
"volume_24h": 8765400000.0,
"market_cap": 153483184623.0,
"percent_change_1h": -2.31,
"percent_change_24h": -4.18,
"percent_change_7d": -0.47
}
},
"last_updated": 1525137271
},
"1027": {
"id": 1027,
"name": "Ethereum",
"symbol": "ETH",
"website_slug": "ethereum",
"rank": 2,
"circulating_supply": 99151888.0,
"total_supply": 99151888.0,
"max_supply": null,
"quotes": {
"USD": {
"price": 642.399,
"volume_24h": 2871290000.0,
"market_cap": 63695073558.0,
"percent_change_1h": -3.75,
"percent_change_24h": -7.01,
"percent_change_7d": -2.32
}
},
NOTE some lines are commented out to prevent further errors.
Im think the error is to do the jsonarray response line but not to sure how to fix it. any help will be greatly appreciated.
data is object, not an array, so you can loop by iterator like this
JSONObject coinArray = response.getJSONObject("data");
Iterator<String> iter = coinArray.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object coinOBJ = coinArray.get(key);
CoinMarketAPI coin = new CoinMarketAPI();
coin.setId(coinOBJ.getString("id"));
coin.setName(coinOBJ.getString("name"));
coin.setSymbol(coinOBJ.getString("symbol"));
coin.setWebsite_slug(coinOBJ.getString("website_slug"));
coin.setRank(Integer.parseInt(coinOBJ.getString("rank")));
coin.setCirculating_supply(coinOBJ.getString("circulating_supply"));
coin.setTotal_supply(coinOBJ.getString("total_supply"));
coin.setQuotes(coinOBJ.getString("quotes"));
coin.setUSD(coinOBJ.getString("USD"));
coin.setPrice(coinOBJ.getString("price"));
Log.d(TAG, coin.getName());
firstlist.add(coin);
} catch (JSONException e) {
// Something went wrong!
}
}
Let me explain it for you. What I did is that "data" was a JsonObject and has multiple objects Inside itself. so I converted data Into Json array by jsonObject.names(); Now I will get each object inside data through for loop.
JSONObject jsonObject = response.getJSONObject("data");
JSONArray jsonArray = jsonObject.names();
Log.e(tag,jsonArray.toString());
for(int i=0;i<jsonArray.length();i++){
JSONObject getObjectFromJsonArray=jsonObject.getJSONObject(jsonArray.getString(i));
CoinMarketAPI coin=new CoinMarketAPI();
coin.setId(getObjectFromJsonArray.getString("id"));
coin.setName(getObjectFromJsonArray.getString("name"));
coin.setSymbol(getObjectFromJsonArray.getString("symbol"));
coin.setWebsite_slug(getObjectFromJsonArray.getString("website_slug"));
coin.setRank(getObjectFromJsonArray.getString("rank"));
coin.setCirculating_supply(getObjectFromJsonArray.getString("circulating_supply"));
coin.setTotal_supply(getObjectFromJsonArray.getString("total_supply"));
JSONObject qoutes = getObjectFromJsonArray.getJSONObject("quotes");
JSONObject USD = qoutes.getJSONObject("USD");
coin.setPrice(USD.getString("price"));
firstlist.add(coin);
}
I have a Jax-Rs created REST endpoint as defined below:
//It will create the order for the customer who is occupying
//the table identified by the PathParam tableId
#Path("/order/{tableId}")
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON )
public List<ItemOrder> giveOrder(#PathParam("tableId") int tableId, List<ItemOrder> itemOrderList){
Customer currentCustomer = Restaurant.getRestaurant().getCustomerArray().get(tableId);
for (int i = 0; i<itemOrderList.size(); i++){
currentCustomer.giveOrder(itemOrderList.get(i));
}
return itemOrderList;
}
Class ItemOrder has been defined as follows:
#XmlRootElement
public class ItemOrder {
private Item mItem;
private int mNumberOfPlates;
.....
......
.....
}
Class Item has been defined as follows:
#XmlRootElement
public class Item {
private int mItemId;
private String mName;
private float mPrice;
......
......
......
}
Now i am trying to send the JSON Post data from an Android client App as follows:
//Ordering Menu
JSONObject itemOrder1Item = new JSONObject();
JSONObject itemOrder1 = new JSONObject();
try {
itemOrder1Item.put("itemId", 11);
itemOrder1Item.put("itemName","Tea");
itemOrder1Item.put("itemPrice", 10);
itemOrder1.put("Item", itemOrder1Item);
itemOrder1.put("numberOfPlates", 10);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject itemOrder2Item = new JSONObject();
JSONObject itemOrder2 = new JSONObject();
try {
itemOrder2Item.put("itemId", 22);
itemOrder2Item.put("itemName","Coffee");
itemOrder2Item.put("itemPrice", 20);
itemOrder2.put("Item", itemOrder2Item);
itemOrder2.put("numberOfPlates", 10);
} catch (JSONException e) {
Log.d("Message",e.getMessage());
}
JSONArray jsonArray = new JSONArray();
jsonArray.put(itemOrder1);
jsonArray.put(itemOrder2);
JSONObject itemsOrderListObj = new JSONObject();
try {
itemsOrderListObj.put("itemOrderList", jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
HTTPAsyncTask asyncTask = new HTTPAsyncTask(getActivity().getApplicationContext(),c, null, itemsOrderListObj, "POST");
asyncTask.execute("http://10.0.2.2:8080/restaurant1/webapi/restaurant/waiters/menus/order/2");
}
But it is throwing some error saying the POST data is not correct. While developing the REST Api i have seen that the server is able to accept data as follows:
[
{
"item": {
"itemId": 11,
"itemName": "Tea",
"itemPrice": 10
},
"numberOfPlates": 5
},
{
"item": {
"itemId": 22,
"itemName": "Coffee",
"itemPrice": 20
},
"numberOfPlates": 5
},
{
"item": {
"itemId": 33,
"itemName": "Bread",
"itemPrice": 30
},
"numberOfPlates": 5
}
]
Now how will i be able to create this JSON Data in my Android app.
Need the help badly.
Used GSON. Its pretty simple as follows;
List<ItemOrder> itemsOrderListObj = new ArrayList<>();
itemsOrderListObj.add(new ItemOrder(new Item(11, "Tea", 10), 10));
itemsOrderListObj.add(new ItemOrder(new Item(22, "Coffee", 20), 10));
itemsOrderListObj.add(new ItemOrder(new Item(33, "Bread", 30), 10));
String itemsOrderListStringJSON = new Gson().toJson(itemsOrderListObj);
Log.i("JSONPOSTDATA", itemsOrderListStringJSON );
HTTPAsyncTask asyncTask = new HTTPAsyncTask(getActivity().getApplicationContext(),c, null, itemsOrderListStringJSON, "POST");
asyncTask.execute("http://10.0.2.2:8080/restaurant1/webapi/restaurant/waiters/menus/order/2");