How do I get the JSON result from Amadeus API (Kotlin Android) - android

I am trying to use the Amadeus Offers Search API with the following code:
when (val flightOffers = amadeus.shopping.flightOffersSearch.get(
originLocationCode = "MDZ",
destinationLocationCode = "MAD",
departureDate = LocalDate.parse("2020-11-11").toString(),
adults = 2,
max = 1
)) {
is ApiResult.Success -> {
if (flightOffers.succeeded) {
println("RESULT SUCCEEDED")
println(flightOffers.data)
}
else
{
println("RESULT DIDN'T SUCCEEDED")
}
}
is ApiResult.Error -> {
println("RESULT ERROR")
}
}
And if I compile that the logcat output is as follows:
I/System.out: RESULT SUCCEEDED
Which makes me think that flightOffers.data is empty.
However if I try this code:
val flightOffers = amadeus.shopping.flightOffersSearch.get(
originLocationCode = "MDZ",
destinationLocationCode = "MAD",
departureDate = LocalDate.parse("2020-11-11").toString(),
adults = 2,
max = 1
)
println("AMADEUS: $flightOffers")
I get the following output:
I/System.out: AMADEUS: Success(meta=Meta(count=1, links={self=https://test.api.amadeus.com/v2/shopping/flight-offers?originLocationCode=MDZ&destinationLocationCode=MAD&departureDate=2020-11-11&adults=2&max=1}), data=[FlightOfferSearch(type=flight-offer, id=1, source=GDS, instantTicketingRequired=false, nonHomogeneous=false, oneWay=false, lastTicketingDate=2020-05-03, numberOfBookableSeats=7, itineraries=[Itinerary(duration=PT18H, segments=[SearchSegment(departure=AirportInfo(iataCode=MDZ, terminal=null, at=2020-11-11T07:10:00), arrival=AirportInfo(iataCode=AEP, terminal=null, at=2020-11-11T08:45:00), carrierCode=AR, number=1403, aircraft=Aircraft(code=738), duration=PT1H35M, id=1, numberOfStops=0, blacklistedInEU=false, co2Emissions=null), SearchSegment(departure=AirportInfo(iataCode=EZE, terminal=A, at=2020-11-11T13:25:00), arrival=AirportInfo(iataCode=MAD, terminal=1, at=2020-11-12T05:10:00), carrierCode=UX, number=42, aircraft=Aircraft(code=789), duration=PT11H45M, id=2, numberOfStops=0, blacklistedInEU=false, co2Emissions=null)])], price=SearchPrice(currency=EUR, total=1151.26, base=510.0, fees=[Fee(amount=0.0, type=SUPPLIER), Fee(amount=0.0, type=TICKETING)], grandTotal=1151.26), pricingOptions=PricingOptions(includedCheckedBagsOnly=true, fareType=[PUBLISHED], corporateCodes=null, refundableFare=false, noRestrictionFare=false, noPenaltyFare=false), validatingAirlineCodes=[UX], travelerPricings=[TravelerPricing(travelerId=1, fareOption=STANDARD, travelerType=ADULT, price=SearchPrice(currency=EUR, total=575.63, base=255.0, fees=null, grandTotal=0.0), fareDetailsBySegment=[FareDetailsBySegment(segmentId=1, cabin=ECONOMY, fareBasis=ZYYOPO, segmentClass=Q, includedCheckedBags=IncludedCheckedBags(weight=0, weightUnit=null)), FareDetailsBySegment(segmentId=2, cabin=ECONOMY, fareBasis=ZYYOPO, segmentClass=Z, includedCheckedBags=IncludedCheckedBags(weight=0, weightUnit=null))]), TravelerPricing(travelerId=2, fareOption=STANDARD, travelerType=ADULT, price=SearchPrice(currency=EUR, total=575.63, base=255.0, fees=null, grandTotal=0.0), fareDetailsBySegment=[FareDetailsBySegment(segmentId=1, cabin=ECONOMY, fareBasis=ZYYOPO, segmentClass=Q, includedCheckedBags=IncludedCheckedBags(weight=0, weightUnit=null)), FareDetailsBySegment(segmentId=2, cabin=ECONOMY, fareBasis=ZYYOPO, segmentClass=Z, includedCheckedBags=IncludedCheckedBags(weight=0, weightUnit=null))])])], dictionaries={locations={MAD={cityCode=MAD, countryCode=ES}, EZE={cityCode=BUE, countryCode=AR}, MDZ={cityCode=MDZ, countryCode=AR}, AEP={cityCode=BUE, countryCode=AR}}, aircraft={789=BOEING 787-9, 738=BOEING 737-800}, currencies={EUR=EURO}, carriers={AR=AEROLINEAS ARGENTINAS, UX=AIR EUROPA}})
Which means that the API is returning a JSON but then I can't use flightOffers with gson to pass this data to a DataClass because flightOffers is a ApiResult> and I don't know how to use that. According to their library docs it should be done like I did it in the first try.
I appreciate all the help and advice I can get. This is my first Android App.

Nice to see that we have a new Android developer in the community !
So first, in Android you should avoid using println, instead you should use Log.d/e/w/i, this method will print your result in android logcat.
For what I see you successfully setup your project and where able to make query from the sdk.
In the android sdk, every get() will give you a correct data object and not just JSON. You don't have to take care of parsing the answer. The thing you have in your flightOffers.data is in fact a List<FlightOfferSearch> that you can use right away !

Related

NODE JS Api working from Postman results in timeout from App

I have a Node js API written in express framework.
I am sending some data over all my api does is calculate number of Packages to make For example :- 100/10 = 10 packages to make.
Loops and creates packages in sales force and firebase one by one.
Works fine from postman.
Problem:
When i try to hit the api from my app it works fine when the package count is <= 10. when > 10 ,Lets say 25 it calculates packages and run a loop of 25 and creates packages,crashes after 11th iteration and restarts the route, calculate again 25 packages to create and resulting in "Over weight error".
1- thought it was from android error may be i was hitting two request one after an other ( this was not the case ).
2- Tried sending header "Connection" "Keep-Alive" ( as Postman does ) not working.
3- tried to put up the timeout in the below code it did not work either ( tried variations of time out like 0, 50,000 ms )
else {
console.log('=====By Item=============');
const supplierFinishedGood = {
Name: parentBatchDoc['itemName'],
Supplier_Product__c: parentBatchDoc['id'],
Package_Size__c: 'a090S000001ZQ5kQAG', // Hard coded PackageSize in 'Gram' as per SALESFORCE
On_Hand_Amount__c: childBatch['batchWeight']
}
console.log('=====By Item============= 2');
const SupplierFinishedProductID = await createSupplierFinishedProduct(supplierFinishedGood, bearerToken);
const Quantity_Packaged__c = Math.floor((childBatch['batchWeight'] - childBatch['batchTestAmount']) / noOfPackage);
console.log('=====By Item============= 3');
//console.log('Quantity_Packaged__c ==== Remaining_Grams_Available_for_Packaging__c', Quantity_Packaged__c, parentBatchSalesforce['Remaining_Grams_Available_for_Packaging__c']);
for (let index = 0; index < noOfPackage; index++) {
if (parentBatchSalesforce['Remaining_Grams_Available_for_Packaging__c'] > Quantity_Packaged__c) {
let package = {
Batch__c: childId,
Product__c: SupplierFinishedProductID,
Inventory_Location__c: 'a030S000003x7M7QAI', //Hard coded InventoryLocation 'StorageFinished' as per SALESFORCE
Number_Of_Items__c: noOfItemInPackage,
Quantity_Packaged__c: Quantity_Packaged__c,
Date_Packaged__c: datePackaged,
Expiration_Date__c: expirationDate
};
console.log('Before creating apcaktge ', index);
const packageID = await createPackage(package, bearerToken);
console.log('After creating package ', index, parentBatchSalesforce['Remaining_Grams_Available_for_Packaging__c']);
package['parentBatchId'] = parentId;
package['status'] = 'Ready to checkout';
package['uid'] = packageID;
const packageFBResponse = await db.collection('packages').doc(packageID).set(package, { merge: true });
reponseBody.push(packageID);
} else {
console.log('======Over
Weight====');
}
Above code is what produces the error.
There is a If condition before this it works fine i have tested it
as it has some other scenario.
End result should not be a timeout error.
API should create all the packages and return the result.
I have found a workaround. I am Playing around batch status and my code returns me the IDs which i need and packages are created.
This is not the ultimated best solution it is a work around. i am still open to know what the actual problem is.
parentBatchDoc['childBatches'][childId]['batchStatus'] = "In Processing";
const parentBatchDocResponse = await db.collection('batches').doc(parentId).set(parentBatchDoc, { merge: true });
if(parentBatchDoc['childBatches'][childId]['batchStatus'] !== "In Processing"){
===================Rest of the case of =======================
}

Google Calendar API V3 android - Get all day events for freeBusyRequest

I'm trying to get the Free busy data of other people that are within my Google organization using the google-api-services-calendar:v3 for Android (using Kotlin). I'm getting the times just fine for events with a set duration. But all day events don't show up on the list. Documentation on this is almost nowhere to be found and the stuff that I find on developers.google.com contains code that was deprecated in 2013...
// ...
val busyTimesList = mutableListOf<AgendaPlotter.TimeSpan>()
SessionService.sharedInstance.getGoogleAccount(activity)
observeOn(Schedulers.io())
.subscribe {
mCredential!!.selectedAccount = it.account
val request = FreeBusyRequest()
val durationCal = Calendar.getInstance()
durationCal.time = startDay.time
Calendars.startOfDay(durationCal)
request.timeMin = DateTime(durationCal.time)
durationCal.add(Calendar.DATE, 1)
request.timeMax = DateTime(durationCal.time)
val requestItems = listOf(FreeBusyRequestItem().setId("email#from.colleague"))
request.items = requestItems
request.timeZone = TimeZone.getDefault().id
val busyTimes: FreeBusyResponse
try {
val query = mService!!.freebusy().query(request)
// Use partial GET to retrieve only needed fields.
query.fields = "calendars"
busyTimes = query.execute()
busyTimes.calendars.forEach {
it.toPair().second.busy.forEach { timeSpan ->
val busyTime = AgendaPlotter.TimeSpan()
busyTime.fromTime.timeInMillis = timeSpan.start.value
busyTime.toTime.timeInMillis = timeSpan.end.value
busyTimesList.add(busyTime)
}
}
emitter.onNext(busyTimesList)
} catch (e: IOException) {
e.printStackTrace()
// ...
}
}
// ...
So my question, how do I also obtain the whole day events?
After some searching I noticed that there is actually nothing wrong with the API. It's a setting for a whole day event to be busy of free.
By default this is set to free, which makes it not show as a busy time, which makes sense. This goes unnoticed by a lot of people and they will be "free" on that day.

soomla : cocos2dx : Profile -> "ProviderNotFoundException" (cocos2d3.x)

I don't understand why Profile always return error : "ProviderNotFoundException". I followed pre-comipiled integration instructions, and I use latest versions on github for soomla-cocos2dx-core,cocos2dx-profile and cocos2dx-store.
Here is an example done with cocos2dx v3.5 (same behaviour on 3.4):
soomla::CCError *profileError = nullptr;
bool isLoggedIn = soomla::CCSoomlaProfile::getInstance()->isLoggedIn(soomla::TWITTER, &profileError);
if (profileError)
MessageBox(profileError->getInfo(), "Error");
else
CCLOG("logged in TWITTER: %d",isLoggedIn);
Application compiles successfully but that code throws a MessageBox saying "ProviderNotFoundException".
In AppDelegate.cpp here is the init I do from applicationDidFinishLaunching:
#define NEWSTRING(s) __String::create(s)
SOOMLA_STORE_EVENTS = new TSoomlaStoreEvents(); // My defined store events
PRODUCTSFORSALE = TItemsForSale::create(); //class for buy items
STOREITEMS = __Dictionary::create();
soomla::CCSoomla::initialize(SOOMLA_CUSTOM_SECRET);//"customSecret");
STOREITEMS->setObject(NEWSTRING(SOOMLA_ANDROID_PUBLIC_KEY), "androidPublicKey");
STOREITEMS->setObject(Bool::create(true), "SSV");
soomla::CCSoomlaStore::initialize(PRODUCTSFORSALE, STOREITEMS);
//----- SOOMLA PROFILE
__Dictionary *profileParams = __Dictionary::create();
__Dictionary *twitterParams = __Dictionary::create();
__Dictionary *googleParams = __Dictionary::create();
twitterParams->setObject(NEWSTRING(SOOMLA_TWITTER_CONSUMER_KEY), "consumerKey");
twitterParams->setObject(NEWSTRING(SOOMLA_TWITTER_CONSUMER_SECRET), "consumerSecret");
googleParams->setObject( NEWSTRING(SOOMLA_GOOGLE_CLIENTID), "clientId");
profileParams->setObject(twitterParams, soomla::CCUserProfileUtils::providerEnumToString(soomla::TWITTER)->getCString());
profileParams->setObject(googleParams, soomla::CCUserProfileUtils::providerEnumToString(soomla::GOOGLE)->getCString());
soomla::CCSoomlaProfile::initialize(profileParams);
Can you help me going further with Profile, please?
this is not an answer, but you might be able to glean something from here: http://answers.soom.la/t/resolved-twitter-providernotfoundexception/675/6
and here: http://answers.soom.la/t/resolved-exception-with-cocos2d-x-profile/1572
As I understand they use reflection in order to load providers (
https://github.com/soomla/ios-profile/blob/9e887f07e0d7f1acb680e02c593a8ce485c93252/SoomlaiOSProfile/ProviderLoader.m#L43). Maybe those classed just have not been loaded.
You can try to use "-ObjC" linker flag, or something like that.

Unity WebPlayer to Android Build Issues

I am new to Unity so a well stepped out answer would be nice. I am trying to make a dice roller on an Android platform. I was following this very well put together tutorial http://games.ucla.edu/resource/unity-1-beginner-tutorial-dice-making-pt-1/ (There is a second part too)
The problem is that it was made for a Web Player. If I try to build it for Android I get two particular errors.
I have two simple scripts with one error associated with each one.
SideTrigger.js - Error: BCE0019: 'currentValue' is not a member of 'UnityEngine.Component'.
public var faceValue = 0;
function OnTriggerEnter( other : Collider ) {
var dieGameObject = GameObject.Find("SixSidedDie");
var dieValueComponent = dieGameObject.GetComponent("DieValue");
dieValueComponent.currentValue = faceValue; //ERROR HERE
Debug.Log("Die1: " + faceValue);
}
DieValue.js - Error: BCE0019: 'text' is not a member of 'UnityEngine.Component'.
public var currentValue = 0;
function Update () {
var dieTextGameObject = GameObject.Find("DieText");
var textMeshComponent = dieTextGameObject.GetComponent("TextMesh");
textMeshComponent.text = currentValue.ToString(); //ERROR HERE
}
I'm assume it's purely a syntactical issue, but I can't seem to find a solution.
GetComponent using string is not recommended due to performance reasons, it is documented here.
It is better to use this:
var dieValueComponent : DieValue = dieGameObject.GetComponent(DieValue)
Or this:
var dieValueComponent : DieValue = dieGameObject.GetComponent.<DieValue>()
See if that works.

ERROR_WRONG_LABEL when trying to print wireless using Android Brother Sdk for label printer

I have trying to print using labels from my android app which using wifi commands Brother QL-720NW label printer. Since I performed factory reset on the printer , I'm getting this error
Problem: ERROR_WRONG_LABEL( means wrong roll specified in the sdk guide) error is thrown on print command, since I performed factory
reset on the printer .
CODE:
void printTemplateSample()
{
Printer myPrinter = new Printer();
PrinterInfo myPrinterInfo = new PrinterInfo();
try{
// Retrieve printer informations
myPrinterInfo = myPrinter.getPrinterInfo();
// Set printer informations
myPrinterInfo.printerModel = PrinterInfo.Model.QL_720NW;
myPrinterInfo.port=PrinterInfo.Port.NET;
myPrinterInfo.printMode=PrinterInfo.PrintMode.FIT_TO_PAGE;
// :
myPrinterInfo.paperSize = PrinterInfo.PaperSize.A4;
myPrinterInfo.ipAddress="192.168.1.13";
myPrinterInfo.macAddress="00:80:92:BD:35:7D";
myPrinter.setPrinterInfo(myPrinterInfo);
// Start creating P-touch Template command print data
// myPrinter.startPTTPrint(1, null);
Boolean val= myPrinter.startPTTPrint(6, null);
Log.i("print", "startPTTPrint "+val);
// Replace text
myPrinter.replaceText("abcde");
// myPrinter.replaceText("12345");
// Trasmit P-touch Template command print data
PrinterStatus status=myPrinter.flushPTTPrint();//ERROR thrown here
Log.i("print", "PrinterStatus err"+status.errorCode);
}catch(Exception e){
e.printStackTrace();
}
}
I'm using there sample code from here
Objective - my ultimate objective is to replace text in template and print but currently I'm not able to print anything
I'm using this Brother SDK.
I tried the Brother sample code for android , it also gives the same error
BUT brother i print app and Ptouch software are successfully printing without any error.
Please help!
Thanks
I resolved this by creating a LabelInfo object, since you have a Label Printer. It's not clear at all in the documentation. You need to set the label info after the printer info.
PrinterInfo info = myPrinter.getPrinterInfo();
info.paperSize = PrinterInfo.PaperSize.CUSTOM;
LabelInfo mLabelInfo = new LabelInfo();
mLabelInfo.labelNameIndex = 5;
mLabelInfo.isAutoCut = true;
mLabelInfo.isEndCut = true;
mLabelInfo.isHalfCut = false;
mLabelInfo.isSpecialTape = false;
myPrinter.setPrinterInfo(info);
myPrinter.setLabelInfo(mLabelInfo);
The ERROR_WRONG_LABEL means that you have a wrong value in paperSize or labelNameIndex.
I have a P750W label printer with a 24'' paper. I found that value 5 is the good one for this size, but I don't know for your printer.
I had the same problem and figured out that you should specify the labelNameIndex field to the PrinterInfo object.
I had the QL-810W printer. I tried many values and nothing worked until I set it to:
printerInfo.labelNameIndex = LabelInfo.QL700.W62RB.ordinal // -> 17
I figured out the correct value by making a for loop with all integers from 0 to 100 and logging the result until the printing succeeded with this value. I know this is not the optimal solution but I can't find any documentation or reference for these codes.
Here is the code I used to specify the PrinterInfo object:
val printerInfo = PrinterInfo()
printerInfo.printerModel = PrinterInfo.Model.QL_810W
printerInfo.port = PrinterInfo.Port.NET
printerInfo.orientation = PrinterInfo.Orientation.PORTRAIT
printerInfo.paperSize = PrinterInfo.PaperSize.CUSTOM
printerInfo.align = PrinterInfo.Align.CENTER
printerInfo.valign = PrinterInfo.VAlign.MIDDLE
printerInfo.printMode = PrinterInfo.PrintMode.ORIGINAL
printerInfo.numberOfCopies = 1
printerInfo.labelNameIndex = LabelInfo.QL700.W62RB.ordinal // -> 17
printerInfo.isAutoCut = true
printerInfo.isCutAtEnd = false
return printerInfo
TL;DR
I solved by setting the workPath attribute:
printerInfo.workPath = context.cacheDir.Path
I noticed that the setPrinterInfo was returning false and when trying to print I received the WRONG_LABEL error code. Debugging the code I figured out that it's related to file writing permission that Brother SDK requires. The documentation is confusing and mentions about needing the WRITE_EXTERNAL_STORAGE if workPath isn't set. Even having this permission I could not make it work. I solved by setting the workPath attribute as shown above.

Categories

Resources