RetroFit, Many to many relationships - android

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

Related

How to get some Specific data from Restapi [flutter]

I want to get only those item which contain type Lunch `` This is a function where I can fetch data from Rest Api and also ApiResponse added
I need to get specific data from a session I send instead of getting the entire array from the response from the Api() method. How do I capture just the only those item which contain type Lunch from the array?
{
"success": true,
"data": [
{
"id": 6,
"name": "Snack",
"type": "breakfast",
"detail": "18",
"image": "uploads/Screenshot_2022-12-04-13-15-13-27.jpg",
"carbs": 6,
"proteins": 4,
"fats": 8,
"cal": 4,
"day": 1,
"created_at": null,
"updated_at": null
},
{
"id": 7,
"name": "Chicken",
"type": "lunch",
"detail": "White Chicken",
"image": "uploads/1670258808164716637219.jpg",
"carbs": 15,
"proteins": 18,
"fats": 10,
"cal": 200,
"day": 1,
"created_at": null,
"updated_at": null
},
{
"id": 8,
"name": "546e57rufjvjv",
"type": "lunch",
"detail": "gdyhj",
"image": "uploads/meat.png",
"carbs": 6578,
"proteins": 2345,
"fats": 5678,
"cal": 4325,
"day": 5,
"created_at": null,
"updated_at": null
},
{
"id": 9,
"name": "Anda Tikki",
"type": "dinner",
"detail": "Egg and Daal",
"image": "uploads/1670259245043112842388.jpg",
"carbs": 10,
"proteins": 8,
"fats": 12,
"cal": 180,
"day": 1,
"created_at": null,
"updated_at": null
},
{
"id": 10,
"name": "Boiled egg and cucumber",
"type": "breakfast",
"detail": "Egg and cucumber",
"image": "uploads/1670259362662817976982.jpg",
"carbs": 10,
"proteins": 5,
"fats": 5,
"cal": 100,
"day": 2,
"created_at": null,
"updated_at": null
}
],
"message": "Food Data retrieved successfully."
}
Future<List<ProductsModel>> getProducts({String? query}) async {
List<ProductsModel> products = [];
var data=[];
try {
String url = 'https://diet.appetitor.app/Celo/api/user/food/2000.0';
var response = await Dio().get(url,
options: Options(headers: {
HttpHeaders.contentTypeHeader: "application/json",
}));
if (response.statusCode == 200) {
products.clear();
ProductsModel.fromJson(response.data);
products.add(ProductsModel.fromJson(response.data));
if (query != null) {
print(products.length);
products = products
.map((e) {
e.data!.where((element) => element.type!.toLowerCase().contains('lunch'));
})
.cast<ProductsModel>()
.toList();
}
}
} on DioError catch (e) {
print(e.response);
}
return products;
}
}
If the response status code returns 200 after making a request with the rest api, assign the data in it to a variable of the type of your model, then you can get it from the variable as you want.

Best way to use nested recyclerview(or any kind of list) in recyclerview?

I'm writing a messenger like app. I already have a recyclerview for drawing messages list. But also, i need to draw some attachments inside of each message(like images, sound, files and so). The data strucutre of message is:
"id": 2,
"text": "Test",
"sendTime": "21:31 12.10.22",
"userId": 1,
"user": {
"id": 1,
"login": "geckon01",
"email": "geckon01#example.com",
"role": "host",
"lastOnline": "2022-10-23T11:03:57.6349417",
"avatarFileId": 0,
"avatarBase64": null
},
"attachments": [{
"id": 1,
"type": "Image",
"data": null,
"user": {
"id": 1,
"login": "geckon01",
"email": "geckon01#example.com",
"role": "host",
"lastOnline": "2022-10-23T11:03:57.6349417",
"avatarFileId": 0,
"avatarBase64": null
},
"file": {
"id": 1,
"directory": "graphics",
"fileName": "1c08af89-41f2-4f85-bb5a-3336a37e51bf.jpg",
"type": "Graphics",
"fileOwner": {
"id": 1,
"login": "geckon01",
"email": "geckon01#example.com",
"role": "host",
"lastOnline": "2022-10-23T11:03:57.6349417",
"avatarFileId": 0,
"avatarBase64": null
}
},
"messageId": 2
}]
}
So, i need to draw different view for attachemnt depend on its type. I'm thought to use fragments, but in my opinion it can be slow.
Complite message, should be like this, where item1,3,4 can be image,file,text and so.
You can use ConcatAdapter. The idea is you create different adapter for each view type. Here's a pseudo code
val concatAdapter = ConcatAdapter()
val headerAdapter = HeaderAdapter()
val messagesAdapter = MessagesAdapter()
val attachmentAdapter = AttachmentAdapter()
concatAdapter.add(headerAdapter)
concatAdapter.add(messagesAdapter)
concatAdapter.add(attachmentAdapter)
recyclerView.adapter = concatAdapter

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,...)

Dynamic fields data save to web services in android

I am getting multiple fields dynamically from JSON data. To save data of dynamic fields into web services i prefer to call by id. But i unable to get the id of that fields. So I need to know how to get ids of dynamic fields.
Here is my JSON response:
{
"sections": [
{
"head": "Section A",
"sort": 1,
"section_id": 3,
"cols": "2",
"fields": [
{
"id": 5,
"template_id": 2,
"section_id": 3,
"label": "A1",
"itype": "1",
"idefault": "",
"ioptions": "",
"required": "N",
"ivalids": "0",
"sort": 1,
"created_at": "-0001-11-30 00:00:00",
"updated_at": "2018-09-23 05:32:59",
"deleted_at": null
},
{
"id": 6,
"template_id": 2,
"section_id": 3,
"label": "A2",
"itype": "1",
"idefault": "",
"ioptions": "",
"required": "N",
"ivalids": "0",
"sort": 1,
"created_at": "-0001-11-30 00:00:00",
"updated_at": "2018-09-23 05:32:59",
"deleted_at": null
}
]
}
]
}
If "itype"=1 dynamic_field = edittext, "itype"=2 dynamic_field =
spinner and so on.
In my response, I am getting "itype"=1 so i am dynamically displaying two edit texts.
And "label" from JSON used as id for a dynamic field. If I integrate API, it's getting the error as "can't resolve the id".
I don't know how to resolve this error.
Screenshot

skipping null values when parsing json in android?

I am parsing json object from facebook.
In my facebook json object, there are string keys inside key array "data".
My Code as follows,
"data": [
{
"id": "100001211447563_300696056647440",
"from": {
"name": "Seho Lee",
"id": "100001211447563"
},
"story": "Seho Lee is now using Facebook in English (US).",
"story_tags": {
"0": [
{
"id": 100001211447563,
"name": "Seho Lee",
"offset": 0,
"length": 8
}
]
},
"type": "status",
"created_time": "2012-01-19T09:13:04+0000",
"updated_time": "2012-01-19T09:13:04+0000",
"comments": {
"count": 0
}
},
{
"id": "100001211447563_298802933503419",
"from": {
"name": "Seho Lee",
"id": "100001211447563"
},
"story": "Seho Lee started using Graph API Explorer.",
"story_tags": {
"23": [
{
"id": 145634995501895,
"name": "Graph API Explorer",
"offset": 23,
"length": 18
}
],
"0": [
{
"id": 100001211447563,
"name": "Seho Lee",
"offset": 0,
"length": 8
}
]
},
"picture": "http://photos-a.ak.fbcdn.net/photos-ak-snc1/v43/11/145634995501895/app_1_145634995501895_4870.gif",
"link": "http://developers.facebook.com/tools/explorer/",
"caption": "A tool to help you browse objects within the Facebook Graph API, manage permissions, obtain access tokens and generally learn how it all works.",
"actions": [
{
"name": "Comment",
"link": "http://www.facebook.com/100001211447563/posts/298802933503419"
},
{
"name": "Like",
"link": "http://www.facebook.com/100001211447563/posts/298802933503419"
}
],
"type": "link",
"created_time": "2012-01-16T09:47:57+0000",
"updated_time": "2012-01-16T09:47:57+0000",
"comments": {
"count": 0
}
},
{
"id": "100001211447563_298789650171414",
"from": {
"name": "Seho Lee",
"id": "100001211447563"
},
"story": "Seho Lee likes myFBCovers.com.",
"story_tags": {
"15": [
{
"id": 160901873998019,
"name": "myFBCovers.com",
"offset": 15,
"length": 14
}
],
"0": [
{
"id": 100001211447563,
"name": "Seho Lee",
"offset": 0,
"length": 8
}
]
},
"type": "status",
"created_time": "2012-01-16T08:57:33+0000",
"updated_time": "2012-01-16T08:57:33+0000",
"comments": {
"count": 0
}
}
when I parsing this json object, String key "likes" is sometimes exist and sometimes do not exist in "data" jsonArray. So when I parsing JsonString "likes", sometimes I gets JSONException since I am parsing null value. Is there any way to skipping "null" json value?
Please help me regarding this.
if try catch it, next processes will be skipped.
you can check by isNull("name") method.
Edit: this is to check key. since you mentioned key exists sometimes. did you mean the value?
use JSONObjects method has(key)
data = (JSONObject) new JSONTokener(jsonObjRecv.toString()).nextValue();
if data.has("like"){
...
}
to check whether the value is null check with isNull("name")

Categories

Resources