Can't compile the code with getting the value from JsonObject - java

I use Volley library to make API request to Google Places.
The response is an object like this:
{
"html_attributions": [],
"results": [
{
"address": "Wood Quay, Dublin, Ireland",
"name": "Christ Church Cathedral",
"place_id": "ChIJGw9ASiYMZ0gRy9yiaCZxNZI",
},
{ ... },
{ ... },
],
"status": "OK"
}
Inside the Response.Listener I need to access the "results" array.
I try to get the JSONArray with name "results" as follows:
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, API_URL, null,
new Response.Listener <JSONObject> () {
#Override
public void onResponse(JSONObject response) {
// THE PROBLEM IS HERE - WON'T COMPILE !!!
JSONArray array = response.getJSONArray("results");
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//
}
});
But I see an error:

Seems like response.getJSONArray("results"); throws the JSONException. You need to handle that exception by wrapping response.getJSONArray("results"); with a try-catch block.
Something like this:
try {
JSONArray array = response.getJSONArray("results");
} catch (org.json.JSONException exception) {
// handle the exception
}

Related

android volley POST jsonArray update

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

How can i get the data from array inside an array android studio JSONArray

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.

How to get ArrayList using GET method of volley

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

JSON request android error

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

JSON file processing with a different structure

I have an android app (Java) that processes an API from te web.
Currently the app is processing a JSON file that looks like this:
{
"contacts": [
{
"id": 1,
"name": "name1",
"email": "email1",
"phone": "1234567890"
},
{
"id": 2,
ETC...
I need to process another JSON file but it has a different structure:
{
"contacts": {
"1": {
"id": 1,
"name": "name1",
"email": "email1",
"phone": "1234567890",
"level1": {
"level2": {
"level3": 3,
}
},
"last_updated": 20180712
},
"2": {
ETC...
How do I process this second JSON file by adjusting the below code?
if (jsonSource != null) {
try {
JSONObject jsonObject = new JSONObject(jsonSource);
JSONArray jsonArrayData = jsonObject.getJSONArray("contacts");
for (int i = 0; i < jsonArrayData.length(); i++) {
JSONObject contacts = jsonArrayData.getJSONObject(i);
String id = contacts.getString("id");
String name = contacts.getString("name");
String email = contacts.getString("email");
String phone = contacts.getString("phone");
HashMap<String, String> values = new HashMap<>();
values.put("id", id);
values.put("name", name);
values.put("email, email);
values.put("phone, phone);
contactList.add(values);
}
} catch (final JSONException e) {
Log.e(TAG, "JSON parsing error: " + e.getMessage());
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(), "ERROR", Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Unable to retrieve JSON file from URL");
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(), "ERROR", Toast.LENGTH_LONG).show();
}
});
}
return null;
Any help is much appreciated!
It looks, that inside first json you have "contacts" as array of objects, and inside second one you have "contacts" as object. Inside it you have other objects, simplified version looks like this:
"contacts": [
{...},
{...},
{...}
]
"contacts": {
"1": {...},
"2": {...},
"3": {...}
}
So, the only option you have is to check manually is "contacts" array or object, and based on it change your code.
It would look like this:
JSONObject jsonObject = new JSONObject(jsonSource);
if (jsonObject.get("contacts") instanceof JSONObject) {
JSONObject contactsJson = jsonObject.getJSONObject("contacts");
for (Iterator<String> it = contactsJson.keys(); it.hasNext(); ) {
String key = it.next();
JSONObject contactJson = contactsJson.getJSONObject(key);
// your code to process contact item
}
} else {
// Your code to process every contact item
}

Categories

Resources