I have some JSON data that I am getting from my database. I can pull it fine and load it into my table view. my issue is separating my JSON data so I can section the tableview. I have JSON array like this
"data": [
{
"ID": 1,
"wilayah_id": 1,
"name": "Jembatan Lima",
"region_name": "region1"
},
{
"ID": 2,
"wilayah_id": 1,
"name": "Kebon Jeruk",
"region_name": "region1"
},
{
"ID": 18,
"wilayah_id": 3,
"name": "Waylunik",
"region_name": "region2"
},
{
"ID": 19,
"wilayah_id": 3,
"name": "Tenggiri",
"region_name": "region2"
},
{
"ID": 25,
"wilayah_id": 3,
"name": "Mesuji",
"region_name": "region3"
},
{
"ID": 26,
"wilayah_id": 4,
"name": "KM 6",
"region_name": "region3"
}
]
What I'm trying to do is separate this data into three parts sort by "region_name" in my table view.
//region model
struct RegionList {
var ID:String
var wilayah_id:String
var name:String
var region_name:String
static var dataSource:[RegionList] {
return [
RegionList.init(ID: "1", wilayah_id: "1", name: "3", region_name: "R1"),
RegionList.init(ID: "1", wilayah_id: "1", name: "3", region_name: "R2"),
RegionList.init(ID: "1", wilayah_id: "1", name: "3", region_name: "R1"),
RegionList.init(ID: "1", wilayah_id: "1", name: "3", region_name: "R2"),
RegionList.init(ID: "1", wilayah_id: "1", name: "3", region_name: "R3")
]
}
}
//Coming Json Array
var arrRegion:[RegionList] = []
//MAKe Section Array by Using Model Class
var regionInSectionArray:[[RegionList]] = []
//Using Dic key in String and value is Model
var usingDicKeySectionArray:[String:[RegionList]] = [:]
// Dummy Data
arrRegion = RegionList.dataSource
//Using Default Dictionary Method to make a group
usingDicKeySectionArray = Dictionary.init(grouping: arrRegion, by: { (region) -> String in
/// Here we are making group dictionary by using region name, you can set by own requirment
//Specify by Region
return region.region_name
})
// You can use it in number of section usingDicKeySectionArray.count
//And number of rowInSection usingDicKeySectionArray[section].count
print(usingDicKeySectionArray.map{$0.key})
//end
///Sorting Keys
//Second option
let sortedKeys = usingDicKeySectionArray.keys.sorted()
sortedKeys.forEach { (key) in
//
let region = usingDicKeySectionArray[key]
regionInSectionArray.append(region ?? [])
}
//USe
//regionInSectionArray.count // in numberOfSection
//regionInSectionArray[section].count // in numberOfRowInSection
//result = ["R1", "R2", "R3"]
Related
I am new in Dart and I have been trying to access the value of "farm_size" key in the following piece of code but unsuccessful. I can access up to "farms" like this
print(myData1[0]["farms"]);
But not any further. Any help will be appreciated. Thanks.
void main() {
var myData1 = [
{
"id": 1,
"first_name": "Jordan",
"sur_name": "Zamunda",
"member_n0": "AA1",
"gender": "male",
"phone": "123456789",
"email": "jordan#example.com",
"farms": [
{"id": 1, "farm_name": "SOUTH_FARM", "farm_size": "160 acres"},
{"id": 2, "farm_name": "NORTH_FARM", "farm_size": "190 acres"}
]
}
];
print(myData1[0]["farms"]);
}
inside farms, there is a list of more maps, to access those maps, you need to specify the index of the map you, for example we want to get the first map, we type:
print(myData1[0]["farms"][0]);
//this will print => {"id": 1, "farm_name": "SOUTH_FARM", "farm_size": "160 acres"}
//to get the name of this farm, you use the key 'farm_name' now:
print(myData1[0]["farms"][0]['farm_name']);
//prints=> SOUTH_FARM
If you're running it in dartpad, this will work:
void main() {
var myData1 = [
{
"id": 1,
"first_name": "Jordan",
"sur_name": "Zamunda",
"member_n0": "AA1",
"gender": "male",
"phone": "123456789",
"email": "jordan#example.com",
"farms": [
{"id": 1, "farm_name": "SOUTH_FARM", "farm_size": "160 acres"},
{"id": 2, "farm_name": "NORTH_FARM", "farm_size": "190 acres"}
]
}
];
List<Map<String,dynamic>> _list = myData1[0]["farms"]as List<Map<String,dynamic>> ;
print(_list[0]['farm_name']);
}
try this
List m = myData1[0]['farms'] as List;
print(m[0]['id']);
I have this json response that contains servicetype,vehiclemodels,accessories,working status as array but i cannot access any of the class,when i print print(obj); it just shows null
Json file
{
"success": true,
"message": "",
"data": {
"service_types": [
{
"id": 1,
"name": "Car Wash"
},
{
"id": 2,
"name": "Full Body Wash"
},
{
"id": 3,
"name": "Polishing"
},
{
"id": 4,
"name": "Engine Oil Checkup"
},
],
"vehicle_models": [
{
"id": 1,
"name": "SUV"
}
],
"accessories": [
{
"id": 2,
"name": "Mat Cover"
},
{
"id": 4,
"name": "Cash"
},
{
"id": 5,
"name": "Engine Room washing"
}
],
"working_statuses": [
{
"id": 0,
"name": "Registered"
},
{
"id": 1,
"name": "Work started"
},
{
"id": 2,
"name": "Work completed"
},
{
"id": 5,
"name": "Cancelled"
}
]
}
}
Code for extracting data
var response = await http.post(Uri.parse(Urls.DasboardData),
headers: {"Content-Type": "application/json"},
body: json.encode({
"vehicle_models": "",
"service_types": "",
"station_id":Station_id,
"accessories": "",
"working_statuses": "",
}));
Map<String, dynamic> value = json.decode(response.body);
var data = value['data'];
if (data.length > 0) {
for (int i = 0; i < data.length; i++) {
var obj = data[i];
print(obj);
var service_type_obj = obj['service_types'];
var vehicle_models_obj = obj['vehicle_models'];
var accessories_obj = obj['accessories'];
var working_statuses_obj = obj['working_statuses'];
DataList.add(GetAllModel(
service_type_obj['id'],
service_type_obj['name'],
vehicle_models_obj['id'],
vehicle_models_obj['name'],
accessories_obj['id'],
accessories_obj['name'],
working_statuses_obj['id'],
working_statuses_obj['name'],
));
}
setState(() {
print("UI UPDATED");
});
}
else
{
}
Model
class GetAllModel {
String service_type_id,
service_type_name,
vehicle_models_id,
vehicle_models_name,
accessories_id,
accessories_name,
working_statuses_id,
working_statuses_name;
GetAllModel(
this.service_type_id,
this.service_type_name,
this.vehicle_models_id,
this.vehicle_models_name,
this.accessories_id,
this.accessories_name,
this.working_statuses_id,
this.working_statuses_name,
);
}
The problem is at the time of iterating your information, the data size is 4, but this It contains 4 objects, therefore you will not be able to access data[i] because data[i] does not exist, if it exists data ['service_types'] which is a list and here if you could iterate the information that this contains object.
So to be able to access the information of your objects you must iterate them like this:
for (var i = 0; i < data['service_types'].length; i++) {
print(data['service_types'][i]);
}
and the same for the other objects.
An alternative to iterate:
for (var item in data.values) {
print(item);
}
You need to change these:
var service_type_obj = obj['service_types'];
var vehicle_models_obj = obj['vehicle_models'];
var accessories_obj = obj['accessories'];
var working_statuses_obj = obj['working_statuses'];
into this:
var service_type_obj = obj['service_types'][0];
var vehicle_models_obj = obj['vehicle_models'][0];
var accessories_obj = obj['accessories'][0];
var working_statuses_obj = obj['working_statuses'][0];
You're objects are located inside a list, to access them, you have to use an index, like[0].
I have difficulties on how to group sets of flutter widgets based on data returned from server.
The sample data is as below:
{
id: 1,
group: 1,
name: A,
},
{
id: 2,
group: 1,
name: B,
},
{
id: 3,
group: 2,
name: C,
},
{
id: 3,
group: null,
name: D,
}
Lets say those group that not null will group into a set of Dropdownlist while others are checkboxed, I have been trying so many hours by still cant and I am new to Flutter.
Is that a List? You can group by filtering with where, i.e., data.where((x) => x["group"] != null).
Full Dart code, see dartpad.dev:
void main() {
var data = [
{
"id": 1,
"group": 1,
"name": "A",
},
{
"id": 2,
"group": 1,
"name": "B",
},
{
"id": 3,
"group": 2,
"name": "C",
},
{
"id": 3,
"group": null,
"name": "D",
}
];
print(data.where((x) => x["group"] != null));
}
I'm trying to get the GitHub data using Talend big data. The thing is, i have multiple URLs,because used each URL to take some values & stored into single mongoDB. The below order only i'm going to try & get the informations,
https://api.github.com/users/sample/repos
https://api.github.com/repos/sample/awesome-ciandcd/commits
https://api.github.com/repos/sample/awesome-ciandcd/contributors
Each URLs are giving the single JSONArray with multiple data format.Please give some suggestion to do this. I've already tried with sub-jobs component. But not get clear job.
My Output Should be like,
{
"gitname": "sample",
"gitType" : "User",
"password": "password",
"repoCount": 3,
"repositoryDetails": [
{
"repoName": "MergeCheckRepository",
"fileCount": 10,
"branchCount": 6,
"releaseCount": 2,
"commitsCount": 10,
"contributorsCount": 3,
"totalPulls": 1,
"mergeCount": 1,
"totalIssues": 12,
"closedIssueCount": 3,
"watchersCount": 1,
"stargazersCount": 4,
"contributorsDetails": [
{
"login": "sample",
"avatarURL": "https://avatars2.githubusercontent.com/u/30261572?v=4",
"contributions": 3
}
],
"commitDetails": [
{
"name": "sample",
"email": "sampletest#test.com",
"date": "2017-07-20T09:09:09Z"
}
]
},
{
"repoName": "Dashboard",
"filecount": 19,
"branchCount": 4,
"releasecount": 2,
"commitsCount": 5,
"contributorsCount": 3,
"totalPulls": 1,
"totalIssues": 2,
"closedIssueCount": 3,
"watchersCount": 1,
"stargazersCount": 4,
"contributorsDetails": [
{
"login": "sample",
"avatarURL": "https://avatars2.githubusercontent.com/u/30261572?v=4",
"contributions": 3
},
{
"login": "Dashboard",
"avatarURL": "https://avatars2.githubusercontent.com/u/30261572?v=4",
"contributions": 3
}
],
"commitDetails": [
{
"name": "sample",
"email": "sampletest#test.com",
"date": "2017-07-14T09:09:09Z"
},
{
"name": "Dashboard",
"email": "prakash.thangasamy#test.com",
"date": "2017-07-19T09:09:09Z"
},
{
"name": "testrepo",
"email": "test.dashboard#test.com",
"date": "2017-07-20T09:09:09Z"
}
]
}
]
}
How to achieve this one with sub-job? Is there any other way to do this?
My Data
link https://api.myjson.com/bins/rwqy
Model
var oModel = new sap.ui.model.json.JSONModel("https://api.myjson.com/bins/rwqy");
sap.ui.getCore().setModel(oModel,'data');
I want to create a SplitApp(Master-Details page). I have created the Master page as a List of User Name from the User dataset. The list should contain the firstname.
var oList = new sap.m.List({
id:"listId",
mode: sap.m.ListMode.SingleSelect,
select: function(){
oController.itemSelected();
}
});
var oItemTemplate = new sap.m.StandardListItem({
id: "sList",title:"{data>firstname}"});
oList.bindAggregation("items","data>/user",oItemTemplate );
return new sap.m.Page({
id:"master",
title: "Claims",
content: [oList]
});
Now in details page I want to show the expenses made by that user(when i select a specific user from master view) in a table.
Now my question is how to filter data and use it for the Details view. Example:
If I select User "X" from Master view list, I should get id 1 from the "user" and Expenseno 1,4 and 7 (as they are associated with uid 1) from "expense", finally i will show the expenses of uid 1 in the details view.
Code I am trying
itemSelected: function(){
var app = sap.ui.getCore().byId("appid");//when a item will b selected first we will get instance of our app
var list = sap.ui.getCore().byId("listId");//then will get instance of the list
var sitem = list.getSelectedItem();
var spath = sitem.oBindingContexts.data.sPath;
var oitem = sap.ui.getCore().getModel('data').getProperty(spath);
console.log(oitem); //oitem has Object { id="", firstname="", lastname=""} values of the selected user.
//***how to get only the id from "oitem" and filter with expense table***//
//var Model = new sap.ui.model.json.JSONModel(oitem); // will use it for details
//sap.ui.getCore().setModel(Model,'item');// view(oitem should contain the filtered data)
app.toDetail("detailsid","show");
},
Please Help, Thank you.
I would suppose you reorganize your data source to something like.
[
{
"id": "1",
"firstname": "x",
"lastname": "k",
"expense": [
{
"expenseno": "1",
"uid": "1",
"item": "c",
"amount": "1500"
},
{
"expenseno": "4",
"uid": "1",
"item": "y",
"amount": "1000"
},
{
"expenseno": "7",
"uid": "1",
"item": "q",
"amount": "900"
}
]
},
{
"id": "2",
"firstname": "y",
"lastname": "kalita",
"expense": [
{
"expenseno": "2",
"uid": "2",
"item": "t",
"amount": "1150"
},
{
"expenseno": "5",
"uid": "2",
"item": "t",
"amount": "3500"
}
]
},
{
"id": "3",
"firstname": "z",
"lastname": "kalita",
"expense": [
{
"expenseno": "6",
"uid": "3",
"item": "s",
"amount": "3500"
},
{
"expenseno": "3",
"uid": "3",
"item": "p",
"amount": "500"
}
]
}
]
You can do this from your initial Data set by something like this
myData.user.forEach(function(d,i){
var exp = myData.expense.filter(function(d1){
if(d1.uid === d.id)return true;
});
console.log(exp);
});
After this it is just relative binding from parent. /Expense will give all the expenses of parent.
Hope this helps.