GeoJSON properties - Kotlin - android

i have some response form HTTP API - GeoJSON data, but how i can get only some values from features --> properties in Kotlin - Android Studio? Or is there some statement where I can determine for example all object where "year==2014" to array/list? So i want only some properties to array/list or variable. Thank you for your help :)
This working, but how to loop for each properties?
val test = jsonObject.getJSONArray("features").getJSONObject(0).getJSONObject("properties").getString("year")
{
"type": "FeatureCollection",
"name": "cycl_accidents_cycl_neh_xytabletopoint_spa1",
"crs": { "crs".
"type": "name",
"properties": { "properties".
"name": "urn:ogc:def:crs:OGC:1.3:CRS84"
}
},
"features": [
{
"type": "feature",
"properties": {
"objectid": 1,
"join_count": 1,
"target_fid": 1,
"id": 60040140073.0,
"d": -604774.832,
"e": -1162719.75,
"datum": "2014-08-03T00:00:00Z",
"day": 7,
"year": 2014,
"month": 8,
"collision": "other type of accident",
"cause": "driving on the wrong side of the road, driving into oncoming traffic",
"alcohol": "Yes, blood alcohol content between 0,8‰ and 1,0‰",
"at fault": "driver of a non-motor vehicle",
'consequences': 'accident resulting in death or injury',
'road condition': 'surface dry, not contaminated',
'weather conditions': 'not obstructed',
'visibility': 'at night - no public lighting, visibility not impaired by weather conditions',
'visibility': 'good',
'mishap': 'none or none of the above',
"type_of_community": "road monitored (in selected cities)",
'type of vehicle': 'bicycle',
'rider_status': 'under the influence of alcohol, blood alcohol content up to 0,99 ‰',
"affected_ride": 1,
"person": "driver",
"mark_person": "without helmet (only for motorcyclists or cyclists)",
"gender": "male",
"consequence": "slight injury",
"killed_os": 0,
"severely_injured_os": 0,
"slightly_injured_os": 1,
"material damage": 0,
"time": 430,
"hour": 4,
"month_t": "august",
"day of the week": "Sunday",
"age_group": "19-24",
"name": "Brno-Bosonohy",
"point_x": 16.52074206,
"point_y": 49.17113043000001,
"globalid": "{CD1B3254-7DD0-478E-8B3A-C6221ADC3DAB}"
},
"geometry": {
"type": "point",
"coordinates": [
16.520742066000025,
49.171130437000045
]
}
},
{
"type": "Feature",
"properties": {
"objectid": 2,
"join_count": 1,
"target_fid": 2,
"id": 60206100089.0,
"d": -596241.506,
"e": -1157759.125,
"datum": "2010-01-21T00:00:00Z",
"day": 4,
"year": 2010,
"month": 1,
"collision": "collision with a moving non-rail vehicle",
"cause": "driver not fully engaged in driving the vehicle",
"alcohol": "No",
"at fault": "by the driver of the motor vehicle",
'consequences': 'accident resulting in death or injury',
'road condition': 'surface dry, dirty (sand, dust, leaves, gravel, etc.)',
'weather conditions': 'not obstructed',
'visibility': 'at night - with public lighting, visibility not impaired by weather conditions',
'visibility': 'good',
'accident location': 'near a pedestrian crossing (within 20 m)',
'road type': 'local road',
'type of vehicle': 'bicycle',
'condition_ridic': 'good - no adverse circumstances detected',
"affected_ridice": 1,
"person": "driver",
"person_mark": "with helmet (only for motorcyclists or cyclists)",
"gender": "male",
"consequence": "slight injury",
"killed_os": 0,
"severely_injured_os": 0,
"slightly_injured_os": 1,
"material damage": 20,
"time": 1829,
"hour": 18,
"month_t": "January",
"day of the week": "Thursday",
"age_group": "33-44",
"name": "Brno-sever",
"point_x": 16.62980964,
"point_y": 49.22375737,
"globalid": "{83269995-7595-4174-B258-92B2231CF8F2}"
},
"geometry": {
"type": "point",
"coordinates": [
16.629809646000069,
49.223757371000033
]
}
},
]
}

I am assuming features is the list which you get after parsing your response.
first parse your response to your model class. please check this link
for that.
https://stackoverflow.com/a/68501606/7248394.
for example
val apiData = Gson().fromJson(readJson, YourModelClass::class.java)
val features = apiData.features
val featureList = features.filter{
it.properties.year =="2014"
}
so this will give featureList of 2014 year.

Related

Retrofit Android API Get without nested array

This is my first android project (I'm a php developer) but i'm struggling to see how to take this example which uses a nested structure under data for the json array whereas my data is not double nested like this example.
The excample code I am trying to modify is from here https://github.com/datanapps/RetrofitKotlin and the key differences in the json are todo with the nesting.
Original
{
"page": 1,
"per_page": 6,
"total": 12,
"total_pages": 2,
"data": [
{
"id": 1,
"email": "george.bluth#reqres.in",
"first_name": "George",
"last_name": "Bluth",
"avatar": "https://reqres.in/img/faces/1-image.jpg"
},
{
"id": 2,
"email": "james.smith#reqres.in",
"first_name": "James",
"last_name": "Smith",
"avatar": "https://reqres.in/img/faces/1-image.jpg"
}
]
}
whereas mine is simply
[
{
"_id": "62f4cb4e131d9d00046a1b9c",
"device": "AndroidAPS-DexcomG6",
"date": 1660209967000,
"dateString": "2022-08-11T09:26:07.000Z",
"isValid": true,
"sgv": 133,
"direction": "Flat",
"type": "sgv",
"created_at": "2022-08-11T09:26:38.326Z",
"mills": 1660209998326
},
{
"_id": "62f4cb4e131d9d00046a1b9c",
"device": "AndroidAPS-DexcomG6",
"date": 1660209967000,
"dateString": "2022-08-11T09:26:07.000Z",
"isValid": true,
"sgv": 133,
"direction": "Flat",
"type": "sgv",
"created_at": "2022-08-11T09:26:38.326Z",
"mills": 1660209998326
}
]
Specifically I want to query the SGV values, direction and date
Thanks
You "return type" of "method" in Retrofit "interface" will be:
List<MyModel>
And MyModel:
data class MyModel(val _id:String, val device:String,...)

Adaptive Card text overflow in Microsoft Teams Android app

I have the following JSON code for my adaptive card:
{
"type": "AdaptiveCard",
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"version": "1.3",
"body": [
{
"type": "Container",
"items": [
{
"type": "TextBlock",
"text": "Awesome! 👍",
"wrap": true,
"size": "large",
"weight": "bolder"
}
]
},
{
"type": "TextBlock",
"text": "Let's add some tags and notes to make it more memorable",
"wrap": true
},
{
"type": "Input.ChoiceSet",
"choices": [
{
"title": "Work",
"value": "1"
},
{
"title": "Kids",
"value": "2"
}
],
"id": "tags",
"label": "What influences your current mood?",
"style": "expanded",
"isMultiSelect": true
},
{
"type": "TextBlock",
"text": "Any notes that you would like to add",
"wrap": true
},
{
"type": "Input.Text",
"placeholder": "Write something...",
"id": "notes",
"isMultiline": true
},
{
"type": "Input.Text",
"value": "1",
"id": "moodId",
"isVisible": false
}
],
"actions": [
{
"type": "Action.Submit",
"title": "Submit"
}
]
}
But for some reason it doesn't care for the wrap attribute in Android (iOS is working ok). The MS Teams is refusing my submission because of the horizontal scrollbar, how can I solve this?
iOS
Android
Update:
Tested on:
Xiaomi Redmi Note 8
Android version 11 rkq1.201004.002
Teams version 1416/1.0.0.2021163901/1022
The issue is fixed now. Please update your Teams version and check

Android Room Write Custom Nested Objects

Okay so I've successfully sent GET request to a server using Retrofit library, and parsed that data in my app. Now I want to store that data(custom model classes which I have created) in ROOM database, however I have a lot of model classes. So what's the best way to write that custom objects in database, how should I write type converters for this? Check my network response to understand how complex the data is:
{
"recipes": [
{
"vegetarian": false,
"vegan": false,
"glutenFree": true,
"dairyFree": false,
"veryHealthy": false,
"cheap": false,
"veryPopular": false,
"sustainable": false,
"weightWatcherSmartPoints": 9,
"gaps": "no",
"lowFodmap": false,
"aggregateLikes": 27,
"spoonacularScore": 27,
"healthScore": 2,
"creditsText": "Foodista.com – The Cooking Encyclopedia Everyone Can Edit",
"license": "CC BY 3.0",
"sourceName": "Foodista",
"pricePerServing": 168.58,
"extendedIngredients": [
{
"id": 1001,
"aisle": "Milk, Eggs, Other Dairy",
"image": "butter-sliced.jpg",
"consistency": "solid",
"name": "butter",
"original": "1 tablespoon butter",
"originalString": "1 tablespoon butter",
"originalName": "butter",
"amount": 1,
"unit": "tablespoon",
"meta": [],
"metaInformation": [],
"measures": {
"us": {
"amount": 1,
"unitShort": "Tbsp",
"unitLong": "Tbsp"
},
"metric": {
"amount": 1,
"unitShort": "Tbsp",
"unitLong": "Tbsp"
}
}
},
{
"id": 10011268,
"aisle": "Produce;Ethnic Foods",
"image": "dried-porcini-mushrooms.png",
"consistency": "solid",
"name": "dried porcini mushrooms",
"original": "1 cup porcini mushrooms (dried or fresh)",
"originalString": "1 cup porcini mushrooms (dried or fresh)",
"originalName": "porcini mushrooms (dried or fresh)",
"amount": 1,
"unit": "cup",
"meta": [
"fresh",
"()"
],
"metaInformation": [
"fresh",
"()"
],
"measures": {
"us": {
"amount": 1,
"unitShort": "cup",
"unitLong": "cup"
},
"metric": {
"amount": 236.588,
"unitShort": "ml",
"unitLong": "milliliters"
}
}
},
{
"id": 1053,
"aisle": "Milk, Eggs, Other Dairy",
"image": "fluid-cream.jpg",
"consistency": "liquid",
"name": "heavy cream",
"original": "1/2 cup heavy cream (or until desired consistency)",
"originalString": "1/2 cup heavy cream (or until desired consistency)",
"originalName": "heavy cream (or until desired consistency)",
"amount": 0.5,
"unit": "cup",
"meta": [
"(or until desired consistency)"
],
"metaInformation": [
"(or until desired consistency)"
],
"measures": {
"us": {
"amount": 0.5,
"unitShort": "cups",
"unitLong": "cups"
},
"metric": {
"amount": 118.294,
"unitShort": "ml",
"unitLong": "milliliters"
}
}
},
{
"id": 1033,
"aisle": "Cheese",
"image": "parmesan.jpg",
"consistency": "solid",
"name": "parmesan cheese",
"original": "1 cup grated Parmesan cheese (or more to taste)",
"originalString": "1 cup grated Parmesan cheese (or more to taste)",
"originalName": "grated Parmesan cheese (or more to taste)",
"amount": 1,
"unit": "cup",
"meta": [
"grated",
"to taste",
"( )"
],
"metaInformation": [
"grated",
"to taste",
"( )"
],
"measures": {
"us": {
"amount": 1,
"unitShort": "cup",
"unitLong": "cup"
},
"metric": {
"amount": 236.588,
"unitShort": "ml",
"unitLong": "milliliters"
}
}
},
{
"id": 10035137,
"aisle": "Pasta and Rice;Ethnic Foods;Baking",
"image": "cornmeal.png",
"consistency": "solid",
"name": "polenta",
"original": "1 cup polenta",
"originalString": "1 cup polenta",
"originalName": "polenta",
"amount": 1,
"unit": "cup",
"meta": [],
"metaInformation": [],
"measures": {
"us": {
"amount": 1,
"unitShort": "cup",
"unitLong": "cup"
},
"metric": {
"amount": 236.588,
"unitShort": "ml",
"unitLong": "milliliters"
}
}
},
{
"id": 2047,
"aisle": "Spices and Seasonings",
"image": "salt.jpg",
"consistency": "solid",
"name": "salt",
"original": "Salt to taste",
"originalString": "Salt to taste",
"originalName": "Salt to taste",
"amount": 6,
"unit": "servings",
"meta": [
"to taste"
],
"metaInformation": [
"to taste"
],
"measures": {
"us": {
"amount": 6,
"unitShort": "servings",
"unitLong": "servings"
},
"metric": {
"amount": 6,
"unitShort": "servings",
"unitLong": "servings"
}
}
},
{
"id": 14412,
"aisle": "Beverages",
"image": "water.png",
"consistency": "liquid",
"name": "water",
"original": "4 cups water",
"originalString": "4 cups water",
"originalName": "water",
"amount": 4,
"unit": "cups",
"meta": [],
"metaInformation": [],
"measures": {
"us": {
"amount": 4,
"unitShort": "cups",
"unitLong": "cups"
},
"metric": {
"amount": 946.352,
"unitShort": "ml",
"unitLong": "milliliters"
}
}
}
],
"id": 640677,
"title": "Creamy Porcini Mushroom Polenta",
"readyInMinutes": 45,
"servings": 6,
"sourceUrl": "http://www.foodista.com/recipe/F38KZJ88/creamy-porcini-mushroom-polenta",
"image": "https://spoonacular.com/recipeImages/640677-556x370.jpg",
"imageType": "jpg",
"summary": "Creamy Porcini Mushroom Polentan is a <b>gluten free</b> side dish. This recipe makes 6 servings with <b>263 calories</b>, <b>9g of protein</b>, and <b>14g of fat</b> each. For <b>$1.69 per serving</b>, this recipe <b>covers 7%</b> of your daily requirements of vitamins and minerals. Head to the store and pick up water, porcini mushrooms, heavy cream, and a few other things to make it today. 27 people have made this recipe and would make it again. From preparation to the plate, this recipe takes approximately <b>45 minutes</b>. All things considered, we decided this recipe <b>deserves a spoonacular score of 30%</b>. This score is not so super. Try Wild Mushroom Polenta with Porcini Sauce, Creamy polenta & mushroom ragout, and Polenta with Creamy Mushroom Sauce for similar recipes.",
"cuisines": [],
"dishTypes": [
"side dish"
],
"diets": [
"gluten free"
],
"occasions": [],
"winePairing": {},
"instructions": "<ol><li>In a large heavy bottomed saucepan, season water with salt and bring to a boil. Quickly whisk in the polenta until fully incorporated.</li><li>Lower the heat to a simmer, add the butter and porcini and allow the polenta to cook, stirring occasionally for about 30 minutes.</li><li>Finish by stirring in the cream and Parmesan cheese. If necessary, add salt to taste.</li></ol>",
"analyzedInstructions": [
{
"name": "",
"steps": [
{
"number": 1,
"step": "In a large heavy bottomed saucepan, season water with salt and bring to a boil. Quickly whisk in the polenta until fully incorporated.Lower the heat to a simmer, add the butter and porcini and allow the polenta to cook, stirring occasionally for about 30 minutes.Finish by stirring in the cream and Parmesan cheese. If necessary, add salt to taste.",
"ingredients": [
{
"id": 1033,
"name": "parmesan",
"localizedName": "parmesan",
"image": "parmesan.jpg"
},
{
"id": 10035137,
"name": "polenta",
"localizedName": "polenta",
"image": "cornmeal.png"
},
{
"id": 1001,
"name": "butter",
"localizedName": "butter",
"image": "butter-sliced.jpg"
},
{
"id": 1053,
"name": "cream",
"localizedName": "cream",
"image": "fluid-cream.jpg"
},
{
"id": 14412,
"name": "water",
"localizedName": "water",
"image": "water.png"
},
{
"id": 2047,
"name": "salt",
"localizedName": "salt",
"image": "salt.jpg"
}
],
"equipment": [
{
"id": 404669,
"name": "sauce pan",
"localizedName": "sauce pan",
"image": "sauce-pan.jpg"
},
{
"id": 404661,
"name": "whisk",
"localizedName": "whisk",
"image": "whisk.png"
}
],
"length": {
"number": 30,
"unit": "minutes"
}
}
]
}
],
"originalId": null,
"spoonacularSourceUrl": "https://spoonacular.com/creamy-porcini-mushroom-polenta-640677"
}
]
}
Although there's no best way of handling this, besides having to create converters models for each of these fields, it would be wise to limit the amount of data you're saving to only the relevant information that you're going to need and then to use custom converters to convert your data automatically.
As requested by OP in the comments, here's a basic example of how you can add a type converter for a list/array (making use of Gson):
extension methods:
fun <T> String.fromGson(classOfT: Class<T>) = Gson().fromJson(this, classOfT)
fun Any.toGson() = Gson().toJson(this)
converter:
class MyConverter {
#TypeConverter
fun toListOfObjects(value: String?): List<Foo> {
if (value.isNullOrEmpty()) {
return emptyList()
}
val jsonArray = value.fromGson(JsonArray::class.java)
return jsonArray.map { jsonArray -> jsonArray.fromGson(Foo::class.java) }
}
#TypeConverter
fun toString(value: List<Foo>?) = value?.toGson()
}
similar question/answer

REST api 'The gurdian' get image URL

Am working on a news app which fetch data from 'The guardian' using the RESTapi http://open-platform.theguardian.com/explore/
http://content.guardianapis.com/search?page=20&q=business%20OR%20sport&api-key={myKey}
I will get a response similar to this
{
"response": {
"status": "ok",
"userTier": "developer",
"total": 80009,
"startIndex": 191,
"pageSize": 10,
"currentPage": 20,
"pages": 8001,
"orderBy": "relevance",
"results": [{
"id": "sport/2016/aug/03/lizzie-armitstead-responds-statement-twitter-missed-tests-olympics-rio",
"type": "article",
"sectionId": "sport",
"sectionName": "Sport",
"webPublicationDate": "2016-08-03T11:14:46Z",
"webTitle": "Lizzie Armitstead hits back: I love my sport but I would never cheat for it",
"webUrl": "https://www.theguardian.com/sport/2016/aug/03/lizzie-armitstead-responds-statement-twitter-missed-tests-olympics-rio",
"apiUrl": "https://content.guardianapis.com/sport/2016/aug/03/lizzie-armitstead-responds-statement-twitter-missed-tests-olympics-rio",
"isHosted": false
}, {
"id": "sport/2016/apr/03/mark-bonar-doctor-at-centre-of-doping-allegations-in-sport",
"type": "article",
"sectionId": "sport",
"sectionName": "Sport",
"webPublicationDate": "2016-04-03T14:10:50Z",
"webTitle": "Mark Bonar: doctor at centre of doping allegations in sport",
"webUrl": "https://www.theguardian.com/sport/2016/apr/03/mark-bonar-doctor-at-centre-of-doping-allegations-in-sport",
"apiUrl": "https://content.guardianapis.com/sport/2016/apr/03/mark-bonar-doctor-at-centre-of-doping-allegations-in-sport",
"isHosted": false
}, {
"id": "sport/blog/2016/apr/22/the-joy-of-six-sporting-tics",
"type": "article",
"sectionId": "sport",
"sectionName": "Sport",
"webPublicationDate": "2016-04-22T09:15:02Z",
"webTitle": "The Joy of Six: sporting tics",
"webUrl": "https://www.theguardian.com/sport/blog/2016/apr/22/the-joy-of-six-sporting-tics",
"apiUrl": "https://content.guardianapis.com/sport/blog/2016/apr/22/the-joy-of-six-sporting-tics",
"isHosted": false
}, {
"id": "business/2016/sep/20/sports-direct-bows-to-pressure-and-agrees-to-independent-review",
"type": "article",
"sectionId": "business",
"sectionName": "Business",
"webPublicationDate": "2016-09-20T09:58:23Z",
"webTitle": "Sports Direct bows to pressure and agrees to independent review",
"webUrl": "https://www.theguardian.com/business/2016/sep/20/sports-direct-bows-to-pressure-and-agrees-to-independent-review",
"apiUrl": "https://content.guardianapis.com/business/2016/sep/20/sports-direct-bows-to-pressure-and-agrees-to-independent-review",
"isHosted": false
}]
}
}
I need to include one main picture for each headline; but the response data doesn't contains any image URL. Is it possible to get image URL using any methods; please help me on this...
You must include &show-fields=thumbnail in your request URL like this:
http://content.guardianapis.com/search?page=20&q={query}&api-key={myKey}&show-fields=thumbnail

RetroFit, Many to many relationships

I have a json response that looks somewhat like this.
{
"id": 1,
"username": "user",
"email": "generic user#gmail.com",
"name": "harshvardhan",
"phone_no": 2147483647,
"created_at": "2016-06-27 12:23:25",
"updated_at": "2016-06-27 12:23:25",
"hash": "",
"groups": [
{
"id": 37,
"title": "aspernatur-et-rem-quos-eius-voluptatem-eveniet-aut",
"descr": "33",
"identifier": "5771545383a2d",
"no_of_members": 0,
"created_at": "2016-06-27 21:59:07",
"pivot": {
"user_id": 1,
"grp_id": 37,
"roles": "admin"
}
},
{
"id": 67,
"title": "quibusdam-voluptas-non-facere-nihil",
"descr": "194",
"identifier": "57715453b8d80",
"no_of_members": 0,
"created_at": "2016-06-27 21:59:07",
"pivot": {
"user_id": 1,
"grp_id": 67,
"roles": "admin"
}
},
{
"id": 161,
"title": "libero-id-ipsa-beatae-aut",
"descr": "59",
"identifier": "5771545469db4",
"no_of_members": 0,
"created_at": "2016-06-27 21:59:08",
"pivot": {
"user_id": 1,
"grp_id": 161,
"roles": "admin"
}
},
{
"id": 198,
"title": "iure-ad-sunt-id-delectus-laboriosam-quo",
"descr": "150",
"identifier": "57715454a9d15",
"no_of_members": 0,
"created_at": "2016-06-27 21:59:08",
"pivot": {
"user_id": 1,
"grp_id": 198,
"roles": "admin"
}
}
]
}
There is a many to many relationship between users and groups.
I am using retrofit with the GsonConverterFactory. On response, how can I parse this information into objects?
I tried making a User class , and a group class, then I put an array of groups as a member of the user class.
But when I access User.getGroups().get(1).getID , it returns 0.
However, User.getGroups().size() does return 4 (the correct number in this case)
How can I achieve this in retrofit?
A practical tool to parse JSON correctly with retrofit can be to generate the classes with http://www.jsonschema2pojo.org
You just have to put the example JSON, the resource type in JSON and put the desired annotation style (GSON, Jackson, ..).
Finally click on the preview button and you can see the results

Categories

Resources