Executing a for loop after one is finished in flutter - android

Server response returning three JSON arrays and all the objects are stored in database one by one and optionsGroupList, attributes, assignedattributes.
In the Project I have three tables are named as a group, attribute, and assignedattribute. firstly I have to insert all the elements of optionsGroupList in group table and I'm able to do so, In the second array I'm getting groupid, attributeid, attributename but in the second table I have 4 columns which have
groupid, attributeid,attributename,groupname, but for the groupname I have to get the record of a particular group by group id from group table but my second loop executes first so I'm not able to get the group record because of the loop still inserting records that time my second loop has started before completing first, my second table depends on the first and my third table depends on the second so I need to insert record after one is finished. Sometimes it works correctly
{
"result": 1,
"data": "optionsList",
"merchantid": "MER-07156",
"optionsGroupList": [{
"grouprowid": "3012",
"groupname": "Color",
"isrequired": "0"
}],
"attributes": [{
"attributerowid": "20794",
"grouprowid": "3012",
"attributename": "Red",
"weight": "0"
}],
"assignedattributes": [{
"attributegrouprowid": "154577",
"productrowid": "342702",
"attributerowid": "20794",
"subsku": "",
"quantity": "0",
"pricechange": "4"
},
{
"attributegrouprowid": "154590",
"productrowid": "354723467",
"attributerowid": "20794",
"subsku": "0",
"quantity": "0",
"pricechange": "0"
}
]
}
My Second loop debug statement printing before first.
optionListService().then((onValue) async {
if (onValue.result == 1) {
//Loop 1
for(int i=0;i<onValue.optionsGroupList.length;i++){
_insertOption(onValue.optionsGroupList[i]);
}
//Loop 2
for(int j=0;j<onValue.attributes.length;j++){
debugPrint('Attribute Name:--${ onValue.attributes[j].attributename}');// this is printed first before first loop excuted
List groupIdList=new List<Map<String,dynamic>>();
groupIdList= await dbHelper.queryReadOption(onValue.attributes[j].grouprowid); // here i'm finding group name from group table but i think is executing first.
if(groupIdList.length>0){
_insertOptionAttribute(onValue.attributes[j],groupIdList[0][DatabaseHelper.columnGroupName],groupIdList[0][DatabaseHelper.columnIsRequired]);
}
}
//Loop 3
for(int i=0;i<onValue.assignedattributes.length;i++){
String attr=onValue.assignedattributes[i].attributerowid;
arrtIdList=new List<Map<String,dynamic>>();
arrtIdList= await dbHelper.queryReadAttribute(attr);
if(arrtIdList.length>0){
_insertProductWithAttribute(
onValue.assignedattributes[i],
arrtIdList[0][DatabaseHelper.columnGroupId],
arrtIdList[0][DatabaseHelper.columnGroupName],
arrtIdList[0][DatabaseHelper.columnAttributeName],
arrtIdList[0][DatabaseHelper.columnIsRequired],
arrtIdList[0][DatabaseHelper.columnWeight]
);
}
}}});}

just add second loop in chained "then" block and in first block return "onValue" varibale. like so:
optionListService().then((onValue) async {
if (onValue.result == 1) {
//Loop 1
for(int i=0;i<onValue.optionsGroupList.length;i++){
_insertOption(onValue.optionsGroupList[i]);
}
}
return onValue;
}).then((onValue) {
if (onValue.result == 1) {
//Loop 2
for(int j=0;j<onValue.attributes.length;j++){
// some code
}
}
});

Related

How to create JSON object in flutter?

I'm working on one application in which I want to fill the registration form and pass this data to API.I tried almost all solutions but not solved this issue.
I'm getting this type of data after filling the form
[
{Date of Birth of the Baby: 08/01/1997},
{Gender of the baby: male},
{Time of Birth of the Baby: 12.00 pm},
{Father's Name: Nnn},
{Mother's Name: Hbhh},
{Any Extra Details?: Bnn}
]
and I want this type of data
{
"Date of Birth of the Baby": "08/01/1997",
"Gender of the baby": "male",
"Time of Birth of the Baby": "12.00 pm",
"Father's Name": "Nnn",
"Mother's Name": "Hbhh",
"Any Extra Details?": "Bnn"
}
var fieldsData = [];
final myControllers = [];
mydynamicData() {
for (var i = 0; i <= widget.fieldData.length; i++) {
fieldsData.add({
widget.fieldData[i]['question'],
myControllers[i].text != null || myControllers[i].text != ""
? myControllers[i].text
: ""
});
}
print("fieldsData:${fieldsData}");
}
This is my method i know this issue occurred due to for loop but without for loop I'm not getting all fields data. so please help.
Import:
import 'dart:convert';
then you can use:
json.encode(fieldsData);
As you have a list of objects, it may be necessary to make a for in the list calling json.encode for each item, then encoding the result.

Parsing JSON from nested result android

Here is my code:
try{
JSONObject jsonObjitem = new JSONObject(jsonString);
JSONArray phrasemaster = jsonObjitem.getJSONArray("phrases");
for(int i = 0; i<phrasemaster.length();i++){
JSONObject scan = phrasemaster.getJSONObject(i);
int id = scan.getInt("id");
if (id == current){
String question = scan.getString("question");
idoutcome1 = scan.getString("idoutcome1");
idoutcome2 = scan.getString("idoutcome2");
idoutcome3 = scan.getString("idoutcome3");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
The user on launch gets random number, when he press the button he is being moved to another fragment where this number is used to pull item from JSON, this number serves as id.
Each item have another three id's. So when I pull my item with this code I also pull 3 id's from that json item. Now what I want is to output the question string from these id's.
{
"phrases": [
{
"id": 1,
"question": "first item",
"idoutcome1": 2,
"idoutcome2": 3,
"idoutcome3": 4
},
{
"id": 2,
"nameofoption": "item 2",
"question": "some question 2",
"idoutcome1": 5,
"idoutcome2": 6,
"idoutcome3": 7
},
{
"id": 3,
"nameofoption": "item 3",
"question": "some question 3",
"idoutcome1": 8,
"idoutcome2": 9,
"idoutcome3": 10
}
]
}
The thing is that I don't understand how I can reach out to these values.
Edit: illustration of what I'm trying to do.
While parsing I take the idoutcome1,2,3 values and output them on my buttons.
However, I want to output the value written in the nameofoption field instead of these numbers. Just like the example, instead of 2 it should show "left".
The problem is that I have this try that searches for id that it got on the previous page and outputs item with corresponding id. How can I implement it within the course of this try that it would go deeper and depending on the idoutcome's of this JSON item display values from the nameofoption field?
I've solved it in a following way, all of the idoutcome's were put in arraylist, then I've reused the same json parsing code to loop through the items with the respective id's and then output them ti the buttons with settext.
That was my first json experience, thanks for the downvotes.

Android Cloudant sync query

as docs say( https://github.com/cloudant/sync-android/blob/master/doc/query.md) im trying to do a query inside a list
look:
query.put("codigo", 4);
result = q.find(query);
for (DocumentRevision revision : result) {
Log.d("QueryTest", "Test1 :" + revision.getBody().toString());
}
return:
{ "codigo":4, "companies":[
{
"id":"b9f19d88-13c0-40e3-89de-63dc787afb4c",
"name":"Filial 0 1488949817178"
},
{
"id":"f17fb098-316e-4d33-a0f7-f5719bf9d62e",
"name":"Filial 1 1488949817178"
} ], "employees":[
{
"codigo":2891,
"id":"cc54fa37-0b64-4108-869a-1303c6176ce5",
"name":"Employee 0 79ed4"
},
{
"codigo":4642,
"id":"19b76bbc-82c7-4295-a385-82ac2d892458",
"name":"Employee 1 e1102"
} ], "id":"ef2d0ebf-50b9-4cd0-9aaf-5389bccaaa56", "nome":"Random 4" }
so its ok
but this query doesnt work:
query.put("employees.codigo", 2891);
first return:
QuerySqlTranslator: No single index contains all of
[{employees.codigo={$eq=2891}}]; add index for these fields to query
efficiently
after created the index:
Index i = q.createJsonIndex(Arrays.<FieldSort>asList(new FieldSort("employees.codigo")), null);
return
QueryExecutor: Projection fields array is empty, disabling project for
this query
so i created the arraylist of fields to filter
List<String> fields = Arrays.asList("codigo");
result = q.find(query, 0 , 0 , fields, null);
nothing returned
adding more one field to filter:
query.put("codigo",4)
query.put("employees.codigo", 2891);
returned: Complain about index
Created another index:
i = q.createJsonIndex(Arrays.<FieldSort>asList(new FieldSort("employees.codigo"), new FieldSort("codigo")), null);
returned: Nothing
whats is wrong?
How can i get document by child and how can i get ONLY the children?
thanks
I think this is unsupported, see the doc on unsupported features, specifically the highlighted entry:
Arrays
Dotted notation to index or query sub-documents in arrays.
Querying for exact array match, { field: [ 1, 3, 7 ] }.
Querying to match a specific array element using dotted notation, { field.0: 1 }.
Querying using $all.
Querying using $elemMatch.

How to change sequence of list View items in android

I have a calendar like this:
materialise calendar
every tic icon shows their corresponding event.
and I have a json response like this:
{
"Table": [
{
"userid": 4,
"eventname": "adi",
"eventdate": "/Date(1484121600000-0800)/",
"eventcolor": "2413AD",
"autoid": 2005
},
{
"userid": 4,
"eventname": "Aditya",
"eventdate": "/Date(1479974400000-0800)/",
"eventcolor": "5986FF",
"autoid": 1011
},
{
"userid": 4,
"eventname": "aditya",
"eventdate": "/Date(1484812800000-0800)/",
"eventcolor": "13AD1A",
"autoid": 2006
},
{
"userid": 4,
"eventname": "dfgdgdgs",
"eventdate": "/Date(1478678400000-0800)/",
"eventcolor": "AD3D1F",
"autoid": 1005
},
{
"userid": 4,
"eventname": "dfgdgdgs",
"eventdate": "/Date(1478678400000-0800)/",
"eventcolor": "AD3D1F",
"autoid": 1006
}
]
}
Here comes the real problem.When I click any date on the calendar, above json response comes in a listView according to sequence of json. But, I want to change the sequence according to which date i clicked(i.e. Date i am clicked in the calendar, that date comes first in the list and remaining item comes after that).
I'm not posting any code, If any one wants to see my code, please ask.
When you parse the list from JSON at that time you check the date of each object and compare to the clicked date and store that particular index.
Then you simply parse the list from JSON response
at parsing time you remove that particular object at that stored index and move to the first position of that list.
Use code like:
list.removeAt(stored_index);
list.add(0, objectOfList);
and then simply add that list to adapter

Filter array field in couchbase

I m working on couchbase lite android.
I have series of documents, every document contains a field which it's value is array of string.
now I want to filter value of this field.
{
type : "customer",
name: "customerX",
states: [ "IL" , "IO" , "NY" , "CA" ]
},
{
type : "customer",
name: "customerY",
states: [ "WY" , "CA", "WA" ]
},
{
type : "customer",
name: "customerZ",
states: [ "NY" ]
}
I want to get customer documents which have "CA" in their states field.
I m using CBL Android.
emit(states , null);
then how could I make my Start and End Key option.
startkey("CA")
Or
startKey(["CA"])
customerX customerY
how can i get only customerX and customerY by "CA" in their states field ?!
If you are just wanting to filter on one state then your best solution would be to make a view like this:
function (doc, meta) {
if(doc.type && doc.type == "customer") {
if(doc.states) {
for (index = 0, len = doc.states.length; index < len; ++index) {
emit(doc.states[index],null);
}
}
}
}
This view will emit a view row for each state in the arrays of each of your documents of type 'customer'. This means that you can then select an individual state with a startkey of "CA" and an endkey of "CA", remember to set the inclusive_true flag to true so that endkeys that match are included:
startkey="CA"&endkey="CA"&inclusive_end=true
Hope that helps!

Categories

Resources