Issue in fetching data from nested JSON file - android

I'm new to android. I have a JSON file with multiple arrays and I'm able to fetch data from the first array and display it in listview (check the first for loop). But i tried to fetch the next array and i didn't get any results(blank screen). I need to display values from "open_days" array. Posted my JSON file and for loop portion.Please check and help me
MainActivity. java
try {
JSONObject jjsonObject =new JSONObject(result);
String getObject = jjsonObject.getString("message");
String getObject1 = jjsonObject.getString("status");
JSONArray getArray = jjsonObject.getJSONArray("favorite_facility_list");
Log.e("message",getObject);
Log.e("status",getObject1);
Log.e("favorite_facility_list",getArray.toString());
for(int i = 0; i < getArray.length(); i++)
{
JSONObject objects = getArray.getJSONObject(i);
String promotion_id = objects.getString("facility_id");
String promotion_image_name = objects.getString("facility_course_name");
String promotion_image_url = objects.getString("icon_image_name");
JSONArray array2=jjsonObject.getJSONArray("open_days");
for(int j=0;j<array2.length();j++)
{
JSONObject obj2=array2.getJSONObject(j);
String openid = obj2.getString("open_days_id");
String openname = obj2.getString("open_days_name");
//
promotionlists promotionlists = new promotionlists();
promotionlists.setFacility_id(promotion_id);
promotionlists.setFacility_course_name(promotion_image_name);
promotionlists.setIcon_image_name(promotion_image_url);
promotionlists.setOpen_days_id(openid);
promotionlists.setOpen_days_name(openname);
promotionArray.add(promotionlists);
adapter= new CustomAdapter(promotionArray,getApplicationContext());
lv.setAdapter(adapter);
}}
JSON file:
{
"status": "1",
"message": "Success",
"favorite_facility_list": [
{
"facility_id": "11",
"facility_course_name": "Facility 2",
"icon_image_name": "3.jpg",
"banner_image_name_list": [
"39.jpg"
],
"address": "test1",
"open_days": [
{
"open_days_id": "5",
"open_days_name": "Thursday"
},
{
"open_days_id": "6",
"open_days_name": "Friday"
},
{
"open_days_id": "8",
"open_days_name": "Sunday"
},
{
"open_days_id": "7",
"open_days_name": "Saturday"
}
],
"open_time_start": "6:8 pm",
"open_time_end": "12:8 pm",
"workouts": [
{
"workout_id": "1",
"workout_name": "Aerobic"
},
{
"workout_id": "2",
"workout_name": "Yoga"
},
{
"workout_id": "4",
"workout_name": "Gym"
},
{
"workout_id": "8",
"workout_name": "Pool"
}
],
"equipments": [
{
"equipment_id": "5",
"equipment_name": "Rowing"
},
{
"equipment_id": "6",
"equipment_name": "Stationary Bike"
},
{
"equipment_id": "7",
"equipment_name": "Bench Press"
},
{
"equipment_id": "8",
"equipment_name": "TRX"
}
],
"services": [
{
"service_id": "4",
"service_name": "Tranning"
},
{
"service_id": "1",
"service_name": "Personal Training"
}
],
"drop_in_rate": [
"10-test",
"20-test1",
"30-test3"
],
"parking_status": "1",
"parking_notes": "2 hrs available",
"facility_status": "1",
"facility_status_description": "Live",
"rating": "2.90",
"distance": "9412.2ml",
"already_like": 1,
"weburl": "",
"phone_no": "",
"facility_lattitude": "-3",
"facility_longitude": "151"
}
]
}

Your Logcat throws JSONException.
Don't
JSONArray array2=jjsonObject.getJSONArray("open_days");
Do
JSONArray array2=objects.getJSONArray("open_days");

You are using the wrong object to fetch open_days
Change
JSONArray array2 = jjsonObject.getJSONArray("open_days");
to
JSONArray array2 = objects.getJSONArray("open_days");

Related

How to assign nested array data on spinner?

I am calling this array and I am getting value but I am not able to assign on spinner.
This is my array data.
"data": {
"id": "105",
"prod_id": "FMSP-6815",
"prod_cat_id": "4",
"prod_name": "Aakash Fish",
"prod_price": "1",
"is_avlbl": "0",
"prod_weight": "500,1000",
"prod_quantity": "0",
"prod_desc": "Eat at your own risk",
"prod_image": "medicine.jpg",
"created_at": "2019-03-26 17:33:26",
"updated_at": "2019-03-26 17:33:26",
"bone_type": "0",
"skin_type": "0",
"cut_type": "0",
"cat_name": "ready_to_eat",
"prod_attributes": [
{
"id": "15",
"name": "Size",
"attribute_options": [
{
"id": "15",
"attribute_id": "15",
"attribute_name": "size",
"prod_id": "105",
"attr_option_id": "8",
"option_price": "10",
"option_name": "Large"
}
]
},
{
"id": "14",
"name": "Clean",
"attribute_options": [
{
"id": "16",
"attribute_id": "14",
"attribute_name": "clean",
"prod_id": "105",
"attr_option_id": "6",
"option_price": "5",
"option_name": "Skinny"
},
{
"id": "20",
"attribute_id": "14",
"attribute_name": "Clean",
"prod_id": "105",
"attr_option_id": "7",
"option_price": "30",
"option_name": "White Skin"
}
]
},
{
"id": "7",
"name": "Cut",
"attribute_options": [
{
"id": "18",
"attribute_id": "7",
"attribute_name": "Cut",
"prod_id": "105",
"attr_option_id": "4",
"option_price": "20",
"option_name": "Medium"
}
]
}
]
}
This is my array
and
this is how I am calling from API.
This is my Java code. I used for loop inside for loop.
if (response.body().getDescriptionResponseData().getSuccess().equals("200")) {
attributeData = response.body().getDescriptionResponseData().getP_data().getAttributeData();
attribute_array_size = attributeData.size();
if (attributeData.size() == 0){
p_attribute.setVisibility(View.GONE);
} else {
p_attribute.setVisibility(View.VISIBLE);
// Loading attribute options
for (int j=0;j<attributeData.size();j++){
attributeOptions = response.body().getDescriptionResponseData().getP_data().getAttributeData().get(j).getAttributeOptionsData();
//String option = attributeOptions.get(j).getOption_name();
// Log.e("options",option);
dateList.clear();
dateList.add("Select");
for (int k=0;k<attributeOptions.size();k++){
String attribute_id = attributeOptions.get(k).getAttribute_id();
String option_name = attributeOptions.get(k).getOption_name();
String option_price = attributeOptions.get(k).getOption_price();
dateList.add(option_name);
//Log.e("option_id",attribute_id);
//Log.e("option_name",option_name);
// Log.e("option_price",option_price);
}
ArrayAdapter dateArrayAdapter = new ArrayAdapter(getContext(),R.layout.date_dialog, R.id.textDate, dateList);
holder.attribute_option_spinner.setAdapter(dateArrayAdapter);
}
}
}
From the question you asked I assume that your spinner shows last values. There are two problems with your code.
1- dateList.clear(); and dateList.add("Select"); should be outside for loop
2- Set spinner adapter outside for loop after all values are assigned to arrayList
Below you can check how it will go
if (response.body().getDescriptionResponseData().getSuccess().equals("200")) {
attributeData = response.body().getDescriptionResponseData().getP_data().getAttributeData();
attribute_array_size = attributeData.size();
if (attributeData.size() == 0){
p_attribute.setVisibility(View.GONE);
} else {
p_attribute.setVisibility(View.VISIBLE);
// Loading attribute options
dateList.clear();
dateList.add("Select");
for (int j=0;j<attributeData.size();j++){
attributeOptions = response.body().getDescriptionResponseData().getP_data().getAttributeData().get(j).getAttributeOptionsData();
//String option = attributeOptions.get(j).getOption_name();
// Log.e("options",option);
for (int k=0;k<attributeOptions.size();k++){
String attribute_id = attributeOptions.get(k).getAttribute_id();
String option_name = attributeOptions.get(k).getOption_name();
String option_price = attributeOptions.get(k).getOption_price();
dateList.add(option_name);
//Log.e("option_id",attribute_id);
//Log.e("option_name",option_name);
// Log.e("option_price",option_price);
}
}
if (dateList.size() > 0) {
ArrayAdapter dateArrayAdapter = new ArrayAdapter(getContext(), R.layout.date_dialog, R.id.textDate, dateList);
holder.attribute_option_spinner.setAdapter(dateArrayAdapter);
}
}
}

How can i parse objects in arrays in arrays from json

I've been trying to parse the objects from this object that is inside an array inside another array. I made two loops because there are multiple objects that i'm trying to make a list from.
This is what the json looks like
{
"type": "FeatureCollection",
"metadata": {
"generated": 1522105396000,
"url": "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_day.geojson",
"title": "USGS Magnitude 4.5+ Earthquakes, Past Day",
"status": 200,
"api": "1.5.8",
"count": 7
},
"features": [{
"type": "Feature",
"properties": {
"mag": 4.7,
"place": "106km SW of Hihifo, Tonga",
"time": 1522100348420,
"updated": 1522102052040,
"tz": -720,
"url": "https://earthquake.usgs.gov/earthquakes/eventpage/us1000d9c6",
"detail": "https://earthquake.usgs.gov/earthquakes/feed/v1.0/detail/us1000d9c6.geojson",
"felt": null,
"cdi": null,
"mmi": null,
"alert": null,
"status": "reviewed",
"tsunami": 0,
"sig": 340,
"net": "us",
"code": "1000d9c6",
"ids": ",us1000d9c6,",
"sources": ",us,",
"types": ",geoserve,origin,phase-data,",
"nst": null,
"dmin": 3.738,
"rms": 0.85,
"gap": 66,
"magType": "mb",
"type": "earthquake",
"title": "M 4.7 - 106km SW of Hihifo, Tonga"
},
"geometry": {
"type": "Point",
"coordinates": [-174.4796, -16.604, 175.39]
},
"id": "us1000d9c6"
},
{
"type": "Feature",
"properties": {
"mag": 4.8,
"place": "West Chile Rise",
"time": 1522025174820,
"updated": 1522026587040,
"tz": -360,
"url": "https://earthquake.usgs.gov/earthquakes/eventpage/us1000d90k",
"detail": "https://earthquake.usgs.gov/earthquakes/feed/v1.0/detail/us1000d90k.geojson",
"felt": null,
"cdi": null,
"mmi": null,
"alert": null,
"status": "reviewed",
"tsunami": 0,
"sig": 354,
"net": "us",
"code": "1000d90k",
"ids": ",us1000d90k,",
"sources": ",us,",
"types": ",geoserve,origin,phase-data,",
"nst": null,
"dmin": 9.665,
"rms": 0.87,
"gap": 192,
"magType": "mb",
"type": "earthquake",
"title": "M 4.8 - West Chile Rise"
},
"geometry": {
"type": "Point",
"coordinates": [-86.6644, -41.0452, 10]
},
"id": "us1000d90k"
}
],
"bbox": [-178.6721, -56.8886, 10, 151.396, 56.3364, 541.02]
}
I just need the place, magnitude and time from both arrays but i can't seem to pick the right array to get the object from. ex:(features.properties.place)
List<String> allPlaces = new ArrayList<>();
JSONArray JA = new JSONArray(data);
JSONArray features = JA.getJSONArray(2);
// JSONArray properties = features.getJSONArray(1);
for (int i = 0; i < features.length(); i++){
JSONArray properties = (JSONArray) features.get(i);
for (int j = 0; j < properties.length(); j++){
JSONObject JO = (JSONObject) features.get(i);
String place = JO.getString("place");
singlePlace = "place: " + place;
dataPlace = "" + singlePlace;
allPlaces.add(place);
}
edit1: to be clear, i am able to get information from the first array, so the value of type, but not anything inside of features,
A problem is that you are parsing the properties as a JSONArray but in fact it's a JSONObject. So, you should try this loop to parse needed data:
JSONObject root = new JSONObject(data); //Where `data` is your raw json string
JSONArray features = root.getJSONArray("features");
for (int i = 0; i < features.length(); i++) {
JSONObject properties = features.getJSONObject(i).getJSONObject("properties");
double mag = properties.getDouble("mag");
String place = properties.getString("place");
long time = properties.getLong("time");
}

How to get a given below value from json data?

I need to get the images array data how to put into the adapter and not required adapter code? Only loop and how to add that's important for me
and then after second I can access option_value array.
First all images can be accessed then after a option_value array.
{
"success": true,
"data": {
"id": "50",
"seo_h1": "",
"name": "Shirt 10001",
"manufacturer": "",
"sku": "",
"model": "10001",
"image": "http://api.yellowskydemo.com/image/cache/data/shirts/7228-500x500.jpg",
"images": [
"http://api.yellowskydemo.com/image/cache/data/shirts/13-500x500.jpg",
"http://api.yellowskydemo.com/image/cache/data/shirts/302-500x500.jpg",
"http://api.yellowskydemo.com/image/cache/data/shirts/5-500x500.jpg",
"http://api.yellowskydemo.com/image/cache/data/shirts/205-500x500.jpg"
],
"price": "$540.00",
"rating": 0,
"description": "<p>Fasten your fashion belts, for this is the ultimate edit of swanky casual wear by Ralph Lauren! For men who are born with a strong sense of style, the American powerhouse packs a colourful punch with this high-fash collection of shirts and sporty, monogrammed polos.</p>\r\n\r\n<p>Fasten your fashion belts, for this is the ultimate edit of swanky casual wear by Ralph Lauren! For men who are born with a strong sense of style, the American powerhouse packs a colourful punch with this high-fash collection of shirts and sporty, monogrammed polos.</p>\r\n",
"attribute_groups": [],
"special": "",
"discounts": [],
"options": [
{
"name": "Size",
"type": "select",
"option_value": [
{
"image": "http://api.yellowskydemo.com/image/cache/no_image-100x100.jpg",
"price": "$50.00",
"price_prefix": "-",
"product_option_value_id": "17",
"option_value_id": "55",
"name": "L-40",
"quantity": "99"
},
{
"image": "http://api.yellowskydemo.com/image/cache/no_image-100x100.jpg",
"price": "$40.00",
"price_prefix": "+",
"product_option_value_id": "18",
"option_value_id": "57",
"name": "XXL-44",
"quantity": "100"
}
],
"required": "1",
"product_option_id": "227",
"option_id": "14"
}
],
"minimum": "1",
"meta_description": "",
"meta_keyword": "",
"tag": "",
"upc": "",
"ean": "",
"jan": "",
"isbn": "",
"mpn": "",
"location": "",
"stock_status": "Out Of Stock",
"manufacturer_id": null,
"tax_class_id": "0",
"date_available": "2014-08-12",
"weight": "0.00000000",
"weight_class_id": "1",
"length": "0.00000000",
"width": "0.00000000",
"height": "0.00000000",
"length_class_id": "1",
"subtract": "0",
"sort_order": "1",
"status": "1",
"date_added": "2014-08-13 12:05:56",
"date_modified": "2015-06-30 11:19:39",
"viewed": "8",
"weight_class": "kg",
"length_class": "cm",
"reward": "0",
"points": "0",
"category": [
{
"name": "Shirts",
"id": "59"
},
{
"name": "Casual Shirts",
"id": "60"
}
],
"quantity": "99",
"reviews": {
"review_total": "0"
}
}
}
You should really look into How to parse JsonObject / JsonArray in android.
Please put your code of also what you have tried because people are here to help solve error/problem not to do coding.
Here is code from which you can Parse your json
JSONObject jsonObject = new JSONObject();
JSONObject dataObject = jsonObject.getJSONObject("data");
JSONArray imagesArray = dataObject.getJSONArray("images");
ArrayList<String> listOfImagesUrl = new ArrayList<>();
for(int i = 0; i < imagesArray.length(); i++)
{
listOfImagesUrl.add(imagesArray.getString(i)); // listOfImages
}
// code for option value
JSONArray optionsArray = dataObject.getJSONArray("options");
for(int i = 0; i < optionsArray.length(); i++)
{
JSONObject option = optionsArray.getJSONObject(i);
JSONArray optionsValueArray = option.getJSONArray("option_value");
for(int j = 0 ; j < optionsValueArray.length(); j++)
{
JSONObject optionValueObject = optionsValueArray.getJSONObject(j);
String image = optionValueObject.getString("image");
String price = optionValueObject.getString("price");
String price_prefix = optionValueObject.getString("price_prefix");
//same like this
}
}

How insert the JSON Object in Existing JSON Array?

Here am Created the JSON Values in Static Way.
JSON Structure
{
"MatchType": {
"inningsperteam": "1",
"maxovers": "5",
"players": "11"
},
"Innings": [
{
"noballs": "0",
"BowlingDetail": [
{
"noballs": "0",
"balls": "0",
"maidens": "0",
"player": "Bowler 12",
"runs": "0",
"wickets": "0",
"bowlingposition": "1",
"wides": "0"
}
],
"byes": "0",
"battingteam": "Team 26",
"overs": "0",
"addpenaltyruns": "0",
"legbyes": "0",
"inplay": "true",
"balls": "0",
"InningsOvers": [],
"declared": "false",
"penaltyruns": "0",
"bowlingteam": "Team 46",
"runs": "0",
"wickets": "0",
"wides": "0",
"completed": "false"
}
],
"Umpire 1": "Umpire 12",
"Umpire 2": "Umpire 53",
"location": "England",
"Ground": "Oval",
"date": "20/6/2014",
"Club": [
{
"Team": {
"Player": [
{
"keeper": "false",
"captain": "false",
"firstname": "Batsman 1"
},
{
"keeper": "false",
"captain": "false",
"firstname": "Batsman 2"
}
],
"local": "1",
"name": "Team 26",
"toss": "false"
},
"local": "1",
"name": "Club1"
},
{
"Team": {
"Player": [
{
"keeper": "false",
"captain": "true",
"firstname": "Bowler 12"
}
],
"local": "2",
"name": "Team 46",
"toss": "true"
},
"local": "2",
"name": "Club2"
}
],
"CurrentPlayers": {
"bowler": "Bowler 12",
"playerA": "Batsman 1",
"playerB": "Batsman 2"
}
}
BattingDetails JSON
[
{
"BattingDetail": [
{
"balls": "0",
"sixes": "0",
"runs": "10",
"player": "Batsman 1",
"battingposition": "1",
"fours": "0"
},
{
"balls": "0",
"sixes": "0",
"runs": "0",
"player": "Batsman 2",
"battingposition": "1",
"fours": "0"
}
]
}
]
Coding
try {
json_scores = new JSONObject(test_str);
jsonArray = new JSONArray("["+test_str+"]");
json_scores = jsonArray.getJSONObject(0);
JSONArray nxt_test = new JSONArray(json_scores.getString("Innings"));
String str = new JSONArray(json_scores.getString("Innings")).getJSONObject(0).getString("BattingDetail");
JSONArray jArray = new JSONArray(str);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json = new JSONObject();
json = jArray.getJSONObject(i);
if (json.getString("player").equalsIgnoreCase(player_name)) {
jArray.getJSONObject(i).put("runs", "10");
}
}
Log.v("Test Array", ""+nxt_test.put(0,new JSONObject().put("BattingDetail", jArray)));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
I want to put the BattingDetail JSON array in Innings json array in JSON Structure.am not able solve this issue.can any one know help me to solve this issue.
Take your main json data into JSONObject.
JSONObject jsobj=new JSONObject(data);
JSONArray jsarBatting=new JSONArray(battingdetail);
JSONArray jsAr=jsobj.getJSONArray("innings");
JSONObject jsobj= jsAr.getJSONObject(0);
jsobj.put("BattingDetail",jsarBatting);

Facebook Profile Information JSON Parsing in Android

For example : if the given below is json of the person's profile on facebook got thorugh facebook sdk login through android app , How we will get the School Name fron the education Field in th json data in android . Please Help
Data :
{
"id": "1464730016",
"name": "Ravi Tamada",
"first_name": "Ravi",
"last_name": "Tamada",
"link": "https://www.facebook.com/ravi8x",
"username": "ravi8x",
"birthday": "12/22/1988",
"hometown": {
"id": "112158005464147",
"name": "Baruva"
},
"location": {
"id": "102186159822587",
"name": "Chennai, Tamil Nadu"
},
"bio": "Author: www.androidhive.info\r\nCo-author: www.9lessons.info",
"work": [
{
"employer": {
"id": "179366562092719",
"name": "ByteAlly"
},
"location": {
"id": "102186159822587",
"name": "Chennai, Tamil Nadu"
},
"position": {
"id": "124917314217511",
"name": "Product Head"
}
]
}
],
"favorite_athletes": [
{
"id": "18620649907",
"name": "Virat Kohli"
}
],
"education": [
{
"school": {
"id": "131587206873093",
"name": "Raghu Engineering College (REC)"
},
"degree": {
"id": "140065339390579",
"name": "B.Tech"
},
"year": {
"id": "142963519060927",
"name": "2010"
},
"type": "Graduate School",
"classes": [
{
"id": "192259410803415",
"name": "2010",
"with": [
{
"id": "584960408",
"name": "Santosh Patnaik"
}
],
"from": {
"id": "584960408",
"name": "Santosh Patnaik"
}
}
]
}
],
"gender": "male",
"relationship_status": "Single",
"website": "www.androidhive.info\nwww.9lessons.info\nwww.twitter.com/ravitamada\nwww.about.me/rv",
"timezone": 5.5,
"locale": "en_US",
"languages": [
{
"id": "106059522759137",
"name": "English"
},
{
"id": "107617475934611",
"name": "Telugu"
},
{
"id": "112969428713061",
"name": "Hindi"
},
{
"id": "343306413260",
"name": "Tamil"
}
],
"verified": true,
"updated_time": "2012-03-02T17:04:18+0000"
}
JSONObject jsonResult = new JSONObject(jsonUser);
JSONArray data = jsonResult.getJSONArray("education");
if(data != null)
{
for(int i = 0 ; i < data.length() ; i++)
{
JSONObject c = data.getJSONObject(i);
String type = c.getString("type");
if(type.equalsIgnoreCase("college"))
{
JSONObject school = c.getJSONObject("school");
String id2 = school.getString("id");
String name2 = school.getString("name");
JSONObject year = c.getJSONObject("year");
String id_y = school.getString("id");
String name_y = school.getString("name");
}
}
}
Supposing that you've this json into a jsonObject that you retrieve as response, this is the way:
// Get jsonArray 'education' from main jsonObject
JSONArray jsonArrayEducation = jsonObject.getJSONArray("education");
JSONObject jsonSchool = jsonArrayEducation.getJSONObject("school");
Note that if you are interested only at the name, you can group the two lines above into
JSONObject jsonSchool = jsonObject.getJSONArray("education").getJSONObject("school");
// get school name
String schoolName = jsonSchool.getString("name");

Categories

Resources