Android get elements from json array - android

I'm trying to get elements from my json array.
this is my json response:
{"IDs":["635426812801493839","635429094450867472","635433640807558204"]}
This is what I've tried so far:
itemList = new ArrayList<HashMap<String, String>>();
JSONArray a = jsonObj.getJSONArray(Constants.IDS);
int arrSize = a.length();
ArrayList<String> stringArray = new ArrayList<String>();
for (int i = 0; i < arrSize; ++i) {
JSONObject obj = a.getJSONObject(i);
stringArray.add(obj.toString());
item = new HashMap<String, String>();
item.put(Constants.ID, obj.toString());
itemList.add(item);
}
Log.e("ARR COUNT", "" + stringArray.size());
But I'm getting empty list. What is wrong with my code? Any help will be truly appreciated. Thanks.

The for loop should be
for (int i = 0; i < arrSize; ++i) {
stringArray.add(a.getString(i));
your the JSONArray contains already string

JSONObject obj = a.getJSONObject(i);
replace with
String str = a.getString(i);

Use this
itemList = new ArrayList<HashMap<String, String>>();
JSONArray a = jsonObj.getJSONArray(Constants.IDS);
int arrSize = a.length();
ArrayList<String> stringArray = new ArrayList<String>();
for (int i = 0; i < arrSize; ++i) {
stringArray.add(a.getString(i));
item = new HashMap<String, String>();
item.put(Constants.ID, obj.toString());
itemList.add(item);
}
Log.e("ARR COUNT", "" + stringArray.size());

Related

Store json array keys data in separate arrayLists

I have this kind of json data returning from url as shown in Image1 Image2 Image3
Basically there are dates inside data and then within these dates there are further 5 different things i.e. session_from, session_to, rate, bookingFound and promotion. What i want is that i want to store all these dates data in separate arraylist.
For example:
sessionfrom0 contains data for 09-09-2018 and all its objects
sessionfrom1 contains data for 10-09-2018 and all its objects
sessionfrom2 contains data for 11-09-2018 and all its objects
I have tried with following piece of code but its not working correctly
JSONObject jsonObject = new JSONObject(response);
JSONObject dataObj = jsonObject.getJSONObject("data");
Iterator<String> iter = dataObj.keys();
sessionsfrom0 = new ArrayList<String>();
sessionsfrom1 = new ArrayList<String>();
sessionsfrom2 = new ArrayList<String>();
while (iter.hasNext()) {
key = iter.next();
JSONArray datesArray = dataObj.getJSONArray(key);
for (int i = 0; i < datesArray.length(); i++) {
JSONObject datesObject0 = datesArray.getJSONObject(i);
JSONObject datesObject1 = datesArray.getJSONObject(i);
JSONObject datesObject2 = datesArray.getJSONObject(i);
sessionsfrom0.add(datesObject0.getString("session_from") + " - " +datesObject0.getString("session_to");
sessionsfrom1.add(datesObject1.getString("session_from") + " - " +datesObject1.getString("session_to");
sessionsfrom2.add(datesObject2.getString("session_from") + " - " +datesObject2.getString("session_to");
} }
This code not working correctly, as you can see that date 09-09-2018 contains further array of size 4 and and in those array there are further 5 items inside each jjson object so i want to store all this in first arraylist i.e. sessionfrom0 and then go to next date and pick all its arrays and json objects and store data in sessionfrom1 arraylist and so on.
Try this:
JSONObject jsonObject = new JSONObject(response);
JSONObject dataObj = jsonObject.getJSONObject("data");
Iterator<String> iter = dataObj.keys();
sessionsfrom0 = new ArrayList<String>();
sessionsfrom1 = new ArrayList<String>();
sessionsfrom2 = new ArrayList<String>();
while (iter.hasNext()) {
String key = iter.next();
JSONArray datesArray = dataObj.getJSONArray(key);
switch (key) {
case "2018-09-09":
fillSessions(datesArray, sessionsfrom0);
break;
case "2018-10-09":
fillSessions(datesArray, sessionsfrom1);
break;
....so on....
}
}
You can create a function instead of rewriting the for loop logic on each case:
void fillSessions(JSONArray jsonArray, List<String> sessionList) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject datesObject = jsonArray.getJSONObject(i);
sessionList.add(datesObject.getString("session_from") + " - " +datesObject0.getString("session_to");
}
}
You can do this by using HashMap
JSONObject jsonObject = new JSONObject(response);
JSONObject dataObj = jsonObject.getJSONObject("data");
Iterator<String> iter = dataObj.keys();
HashMap<String, ArrayList<String>> map = new HashMap<>();
while (iter.hasNext()) {
key = iter.next();
JSONArray datesArray = dataObj.getJSONArray(key);
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < datesArray.length(); i++) {
JSONObject datesObject0 = datesArray.getJSONObject(i);
list.add(datesObject0.getString("session_from") + " - " + datesObject0.getString("session_to");
}
map.put(key, list);
}
Try this:
JSONObject jsonObject = new JSONObject(response);
JSONObject dataObj = jsonObject.getJSONObject("data");
Iterator<String> iter = dataObj.keys();
Map<String, ArrayList<String>> map = new TreeMap<>();
while (iter.hasNext()) {
String key = iter.next();
JSONArray datesArray = dataObj.getJSONArray(key);
ArrayList<String> tmp = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject datesObject = jsonArray.getJSONObject(i);
tmp.add(datesObject.getString("session_from") + " - "+datesObject.getString("session_to"));
}
map.put(key, tmp);
}
Probably you don't have all keys inside data so using switch case is not sensitive.

parse JsonArray in android

How to parse this jsonarray "Images" ??
I parse this json ,, but i can't get "Images"
the Jsonarray "data" inside it elements , inside every element array of images >>>>
this is the response
this is my code
JSONObject responseObject = new JSONObject(response);
JSONArray newsJsonArray = responseObject.getJSONArray("data");
final List <AndroidVersion> newsList = new ArrayList <AndroidVersion>();
newsImages = new ArrayList<String>();
newsids = new ArrayList<String>();
newsnames = new ArrayList<String>();
newshotelsid = new ArrayList<String>();
newscontents = new ArrayList<String>();
newstimesto = new ArrayList<String>();
newscost = new ArrayList<String>();
newstimesfrom = new ArrayList<String>();
newscountry = new ArrayList<String>();
newscity = new ArrayList<String>();
newstype = new ArrayList<String>();
newsImages = new ArrayList<String>();
for (int j = 0; j < newsJsonArray.length(); j++) {
AndroidVersion news = new AndroidVersion();
if (newsJsonArray.getJSONObject(j).has("id")) {
newsids.add(newsJsonArray.getJSONObject(j).getString("id"));
}
if (newsJsonArray.getJSONObject(j).has("name")) {
news.setName(newsJsonArray.getJSONObject(j).getString("name"));
newsnames.add(newsJsonArray.getJSONObject(j).getString("name"));
}
if (newsJsonArray.getJSONObject(j).has("desc")) {
news.setdesc(newsJsonArray.getJSONObject(j).getString("desc")
.replaceAll("<p>", "").replaceAll("<\\/p>\\r\\n", "").replaceAll(" ", ""));
newscontents.add(newsJsonArray.getJSONObject(j).getString("describtion"));
}
if (newsJsonArray.getJSONObject(j).has("country")) {
news.setcountry(newsJsonArray.getJSONObject(j).getString("country"));
newscountry.add(newsJsonArray.getJSONObject(j).getString("country"));
}
if (newsJsonArray.getJSONObject(j).has("city")) {
news.setcity(newsJsonArray.getJSONObject(j).getString("city"));
newscity.add(newsJsonArray.getJSONObject(j).getString("city"));
}
if (newsJsonArray.getJSONObject(j).has("date_from")) {
news.setdate_from(newsJsonArray.getJSONObject(j).getString("date_from"));
newstimesfrom.add(newsJsonArray.getJSONObject(j).getString("date_from"));
}
if (newsJsonArray.getJSONObject(j).has("date_to")) {
news.setdate_to(newsJsonArray.getJSONObject(j).getString("date_to"));
newstimesto.add(newsJsonArray.getJSONObject(j).getString("date_to"));
}
if (newsJsonArray.getJSONObject(j).has("num persons")) {
news.sethotel_id(newsJsonArray.getJSONObject(j).getString("num persons"));
newshotelsid.add(newsJsonArray.getJSONObject(j).getString("num persons"));
}
if (newsJsonArray.getJSONObject(j).has("price")) {
news.setprice(newsJsonArray.getJSONObject(j).getString("price"));
newscost.add(newsJsonArray.getJSONObject(j).getString("price"));
}
if (newsJsonArray.getJSONObject(j).has("images")) {
news.setImage(newsJsonArray.getJSONObject(j).getString("images"));
newsImages.add(newsJsonArray.getJSONObject(j).getString("images"));
}
newsList.add(news);
}
I would highly recommend using Gson to parse it.
Create a response object with structure matching the json response. Then you can use the single object without having to create it down into parts.
Change this part:
if (newsJsonArray.getJSONObject(j).has("images")) {
news.setImage(newsJsonArray.getJSONObject(j).getString("images"));
newsImages.add(newsJsonArray.getJSONObject(j).getString("images"));
}
to:
if(newsJsonArray.getJSONObject(j).getJSONArray("images") != null) {
JSONArray jArray = newsJsonArray.getJSONObject(j).getJSONArray("images");
for (int k=0; k<jArray.length(); k++) {
news.setImage(jArray.getString(k));
newsImages.add(jArray.getString(k));
}
}
You can use direct string object from JSONArray like below:
JSONArray array = object.getJSONArray("images");
for (int i = 0; i < array.length(); i++) {
String image = array.getString(i);
}

sum for loop quantity values?

i have this code..
JSONObject jsonObjcart = new JSONObject(myJSONCartProducts);
jsonarrayCartProducts = jsonObjcart.getJSONArray("cartproducts");
cartarraylist = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jsonarrayCartProducts.length(); i++) {
HashMap<String, String> lmap = new HashMap<String, String>();
JSONObject p = jsonarrayCartProducts.getJSONObject(i);
// Retrive JSON Objects
lmap.put("products_id", p.getString("products_id"));
lmap.put("products_name", p.getString("products_name"));
lmap.put("products_price", p.getString("products_price"));
lmap.put("products_image", p.getString("products_image"));
lmap.put("customers_basket_quantity", p.getString("customers_basket_quantity"));
lmap.put("products_price_total", p.getString("products_price_total"));
lmap.put("pcustomersid", customersid);
lmap.put("pcountryid", countryid);
lmap.put("customers_basket_id", p.getString("customers_basket_id"));
// Set the JSON Objects into the array
cartarraylist.add(lmap);
}
i want to sum the quantity p.getString("customers_basket_quantity") and set to my textview..
i tried to do create an
int qtySum=0;
int qtyNum;
and do this inside for loop..
qtyNum = Integer.parseInt(p.getString("customers_basket_quantity"));
qtySum += qtyNum;
and set qtySum to my textview
textTotalitems.setText(qtySum);
but i got error, the app crashed..
this is updated code with sum i tried..
JSONObject jsonObjcart = new JSONObject(myJSONCartProducts);
jsonarrayCartProducts = jsonObjcart.getJSONArray("cartproducts");
cartarraylist = new ArrayList<HashMap<String, String>>();
int qtySum=0;
int qtyNum;
for (int i = 0; i < jsonarrayCartProducts.length(); i++) {
HashMap<String, String> lmap = new HashMap<String, String>();
JSONObject p = jsonarrayCartProducts.getJSONObject(i);
// Retrive JSON Objects
lmap.put("products_id", p.getString("products_id"));
lmap.put("products_name", p.getString("products_name"));
lmap.put("products_price", p.getString("products_price"));
lmap.put("products_image", p.getString("products_image"));
lmap.put("customers_basket_quantity", p.getString("customers_basket_quantity"));
lmap.put("products_price_total", p.getString("products_price_total"));
lmap.put("pcustomersid", customersid);
lmap.put("pcountryid", countryid);
lmap.put("customers_basket_id", p.getString("customers_basket_id"));
// Set the JSON Objects into the array
qtyNum = Integer.parseInt(p.getString("customers_basket_quantity"));
qtySum += qtyNum;
cartarraylist.add(lmap);
}
textTotalitems.setText(qtySum);
Use
textTotalitems.setText(String.valueOf(qtySum));
instead of
textTotalitems.setText(qtySum);
With your current implementation your trying to set a resource-Id to your TextView, because TextView has an overloaded setText(int resId)-method.

Insert JSON Array on String Array on android

I have JSON array like below format
{
"get": [],
"post": {
"_event": "get_buyers_guide_detail",
"_deviceID": "490154203237518",
"type": "cars",
"model_id": "1007"
},
"cars": [
{
"ID": 6119,
"post_title": "COROLLA",
"interior_images": [
"http://.....e8664969d20654bf2a58f1b26de70d2.jpg",
"http://........02/3bdfae250e3ce14514fe8f2f9dc3e58f.jpg",
"http://........1d14a554a2ed78d1659463ec.jpg"
],
}
]
}
I have create JSONArray for this:
JSONArray Array = entries.getJSONArray("cars");
for (int i = 0; i < Array.length(); i++) {
JSONObject detailObject = Array.getJSONObject(i);
String ID = detailObject.getString("ID");
String title = detailObject.getString("post_title");
JSONArray galleryArray = detailObject.getJSONArray("interior_images");
for(int j=0; j<galleryArray.length(); j++){
// What to do here ????
}
}
now i am confused with this format of JSON data. There is no JSONObject to get the values. How to insert these string on Array please help me find out the solution
Try this,
galleryArray.getString(j);
this should get the string at position j.
galleryArray.getString(index);
This function will return String object of corresponding index
try this
ArrayList<String> stringArray = new ArrayList<String>();
JSONArray galleryArray = detailObject.getJSONArray("interior_images");
for(int j=0; j<galleryArray.length(); j++){
try {
JSONObject jsonObject = galleryArray.getJSONObject(j);
stringArray.add(jsonObject.toString());
}
catch (JSONException e) {
e.printStackTrace();
}
}
Try this way,hope this will help you to solve your problem.
try{
String jsonRespone="{\"get\":[],\"post\":{\"_event\":\"get_buyers_guide_detail\",\"_deviceID\":\"490154203237518\",\"type\":\"cars\",\"model_id\":\"1007\"},\"cars\":[{\"ID\":6119,\"post_title\":\"COROLLA\",\"interior_images\":[\"http://.....e8664969d20654bf2a58f1b26de70d2.jpg\",\"http://........02/3bdfae250e3ce14514fe8f2f9dc3e58f.jpg\",\"http://........1d14a554a2ed78d1659463ec.jpg\"],}]}";
JSONObject responeJson = new JSONObject(jsonRespone);
ArrayList<HashMap<String,Object>> data = new ArrayList<HashMap<String, Object>>();
JSONArray carsJsonArray = responeJson.getJSONArray("cars");
for (int i=0;i<carsJsonArray.length();i++){
HashMap<String,Object> row = new HashMap<String, Object>();
row.put("ID",carsJsonArray.getJSONObject(i).getString("ID"));
row.put("TITLE",carsJsonArray.getJSONObject(i).getString("post_title"));
JSONArray galleryArray = carsJsonArray.getJSONObject(i).getJSONArray("interior_images");
ArrayList<String> interiorImages = new ArrayList<String>();
for(int j=0; j<galleryArray.length(); j++){
interiorImages.add(galleryArray.getString(j));
}
row.put("INTERIORIMAGES",carsJsonArray.getJSONObject(i).getString("interiorImages"));
data.add(row);
}
for (HashMap<String,Object> row :data){
System.out.print("ID : "+row.get("ID"));
System.out.print("TITLE : "+row.get("TITLE"));
ArrayList<String> interiorImages = (ArrayList<String>) row.get("INTERIORIMAGES");
for (int j=0;j<interiorImages.size();j++){
System.out.print("INTERIORIMAGES +"+j+" : "+interiorImages.get(j));
}
}
}catch (Throwable e){
e.printStackTrace();
}
I think you need to use List of Map
Example:
List<Map> list = new ArrayList<Map>();
Map map = new HashMap();
map.put("userIcon", R.drawable.scott);
map.put("username", "Shen");
map.put("usertext", "This is a simple sample for SimpleAdapter");
list.add(map);
map = new HashMap();
map.put("userIcon", R.drawable.ricardo);
map.put("username", "Ricardo");
map.put("usertext", "This is a simple sample for SimpleAdapter");
list.add(map);
add this in loop

Recover multiple data from json

I'm trying to parse a json inside an HashMap to use the data inside my app.
Here is a simplified version of the code:
JSONArray array1 = new JSONArray(json);
for (int i = 0; i < array1.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject object1 = array1.getJSONObject(i);
JSONObject object2 = object1.getJSONObject("job");
JSONArray array2 = object2.getJSONArray("formations");
if (array2.length() != 0) {
for (int i1 = 0; i1 < array2.length() - 1; i1++) {
JSONObject object3 = array2.getJSONObject(i1);
map.put("formation-created_at",
}
}
map.put("testimony", object2.getString("testimony"));
JSONArray array3 = object2.getJSONArray("themes");
if (array3.length() != 0) {
for (int i2 = 0; i2 < array3.length() - 1; i2++) {
JSONObject object4 = array3.getJSONObject(i2);
map.put("themes-intro", object4.getString("intro"));
}
}
JSONObject object5 = object2.getJSONObject("sector");
map.put("sector-description", object5.getString("description"));
list.add(map);
}
Log.d("testimony", list.get(1).get("testimony"));
Log.d("themes-intro", list.get(1).get("themes-intro"));
I can recover the first object in the map with :
Log.d("testimony", list.get(1).get("testimony"));
But i cannot recover the one who is inside the loop :
Log.d("themes-intro", list.get(1).get("themes-intro"));
The logcat return the error :
FATAL EXCEPTION: main
java.lang.NullPointerException: println needs a message
at android.util.Log.println_native(Native Method)
at android.util.Log.d(Log.java:138)
I know that I should specify which "themes-intro" I want to call from the loop, but I cannot add a .get(x) to the expression.
Edit :
Here is the full json : http://komfushee.com/documents/ctai/jobs.json
And I've edited my code to give the full version of the code
please use below code i think i hope it will be haplfull....
HashMap<String, String> map1 = new HashMap<String, String>();
HashMap<String, String> map2 = new HashMap<String, String>();
if (array1.length() != 0) {
for (int i = 0; i < array1.length(); i++) {
JSONObject object1 = array1.getJSONObject(i);
JSONObject object2 = object1.getJSONObject("job");
map1.put("testimony", object2.getString("testimony"));
}
}
if (array2.length() != 0) {
for (int i1 = 0; i1 < array2.length() - 1; i1++) {
JSONObject object3 = array2.getJSONObject(i1);
map2.put("formation-created_at", object3.getString("created_at"));
}
}

Categories

Resources