LibGDX http request not working - android

I want to send a String message to database when user presses a specific button in the LibGDX game I am designing for android. How do I go about doing that? Following is the code I tried. But it does not work.
Net.HttpRequest httpRequest = new Net.HttpRequest();
httpRequest.setMethod("POST");
httpRequest.setUrl("URL is here");
httpRequest.setContent("INSERT INTO `game_table` (`Button`) VALUES ('Button 1 Pressed')");
Net.HttpResponseListener httpResponseListener = new Net.HttpResponseListener() {
#Override
public void handleHttpResponse(Net.HttpResponse httpResponse) {
Gdx.app.log("Log httpResponse", httpResponse.getResultAsString());
}
#Override
public void failed(Throwable t) {
}
#Override
public void cancelled() {
}
};
Gdx.net.sendHttpRequest(httpRequest,httpResponseListener);
Log does not provide anything in android monitor. I also tried using AsyncTask and without AsyncTask to implement this code. But neither works.
Am I missing something? If so could you give me small code snippet that will work?

You don't need to use an AsyncTask, libGDX' HTTPRequest is async out of the box.
You did not log anything if the request fails or is cancelled so probably that's the case.

Related

React native: Callback in Native Module not being called?

I'm facing a issue in an app I'm developing that someone may be able to help me with.
I'm working on an app for payment machines that use Android (7.1), with it you are able to pay with credit card. The company that developed these machines offer a java sdk. Since this app is using React Native, I wrote a Native Module to connect with it. The SDK is really simple.
After the app is authenticated (done just once), All I have to do is call the doAsyncPayment method with the right parameters, and once its done, it will call the onSuccess or onError method of the listener.
When either of these methods is called, I call the callback parameter I got from the React Native side. In theory it's supposed to work, and it does, most of the time. Every once in a while, something happens that these callbacks are not called, so the client stays on the loading payment screen forever. No error is reported on sentry.
The only thing I'm thinking is that somehow the bridge is losing it? Maybe because these method runs asyncronously in the native side (another thread?), the connection is maybe lost?
I haven't been able to reproduce it, because it happens rarely and at random (I suppose).
I don't know much of Native Android, so any help is appreciated.
Here is a resumed piece of code of what's happening:
Native method being called:
#ReactMethod
public void startPayment(...other params,
Callback onErrorCallback, Callback onSuccessCallback) {
setPlugPag();
PlugPagPaymentData paymentData = new PlugPagPaymentData(paymentType, amountCents,
installmentType, installments, userReference, printReceipt);
PlugPagInitializationResult initResult = plugPag.initializeAndActivatePinpad(new
PlugPagActivationData(activationCode));
if(initResult.getResult() == PlugPag.RET_OK) {
plugPag.doAsyncPayment(paymentData, new PlugPagPaymentListener() {
PlugPagPrintResult printResult;
#Override
public void onSuccess(#NonNull PlugPagTransactionResult plugPagTransactionResult) {
if(printResult != null) {
WritableMap printResultMap = Arguments.createMap();
printResultMap.putInt("result", printResult.getResult());
printResultMap.putString("message", printResult.getMessage());
printResultMap.putString("errorCode", printResult.getErrorCode());
onSuccessCallback.invoke(TransactionResult.toRNWritableMap(plugPagTransactionResult), printResultMap);
}else {
onSuccessCallback.invoke(TransactionResult.toRNWritableMap(plugPagTransactionResult));
}
}
#Override
public void onError(#NonNull PlugPagTransactionResult plugPagTransactionResult) {
onErrorCallback.invoke(TransactionResult.toRNWritableMap(plugPagTransactionResult));
}
#Override
public void onPaymentProgress(#NonNull PlugPagEventData plugPagEventData) {
WritableMap eventDataMap = Arguments.createMap();
eventDataMap.putString("customMessage", plugPagEventData.getCustomMessage());
eventDataMap.putInt("eventCode", plugPagEventData.getEventCode());
sendEvent(Constants.EVENT_PLUG_PAG_PAYMENT_PROGRESS_CHANGED, eventDataMap);
}
#Override
public void onPrinterSuccess(#NonNull PlugPagPrintResult plugPagPrintResult) {
}
#Override
public void onPrinterError(#NonNull PlugPagPrintResult plugPagPrintResult) {
}
});
}else {
onErrorCallback.invoke(String.valueOf(initResult.getResult()));
}
}
on React native side, I just call:
startPayment(...other params, errorCallback, successCallback);
Maybe because the way the listener is instantiated?
Thanks in advance.

Android, Zxing: Not able to pass result into asynctask

I am trying to pass results from scanning into asynctask, because then I need to call php script from server. But somehow it does not work.
Asynctask should be functional, but now after some time I am not sure about anything.
But when I use this code:
#Override
public void handleResult(com.google.zxing.Result result) {
Log.v("TAG", result.getText());
mScannerView.resumeCameraPreview(this);
}
It works and logs my result.
And when I change it into this:
#Override
public void handleResult(com.google.zxing.Result result) {
Log.v("MATEJ", result.getText());
ScannerService scannerService = new ScannerService(this);
scannerService.execute(result.getText());
mScannerView.resumeCameraPreview(this);
}
It logs nothing and application stops working without error message.

How would you write a test for this method using Mockito?

Please assist in this. I can't seem to create a suitable test for this method:
protected void startInterfacing() {
mLiveAuthClient.login(mView.context(), Arrays.asList(SCOPES), new LiveAuthListener() {
#Override
public void onAuthComplete(final LiveStatus liveStatus, final LiveConnectSession liveConnectSession,
Object o) {
// Login successful and user consented, now retrieve user ID and connect with backend server
getUserIdAndConnectWithBackendServer(liveConnectSession, mLiveAuthClient);
}
#Override
public void onAuthError(LiveAuthException e, Object o) {
// We failed to authenticate with auth service... show error
if (e.getError().equals("access_denied") ||
e.getMessage().equals("The user cancelled the login operation.")) {
// When user cancels in either the login or consent page, we need to log the user out to enable
// the login screen again when trying to connect later on
logUserOut(mLiveAuthClient, false);
} else {
onErrorOccured();
}
}
});
}
I'll explain abit what goes on here:
I'm trying to authenticate my client and log into OneDrive.
The method starts with a call to the Live SDK's login method. That SDK object is given to me from outside this class. So I can basically mock it.
Here's what I'm struggling with:
I do not need to test the call to the login method because it is not mine. I do need to test the call to getUserIdAndConnectWithBackendServer() inside onAuthComplete. But this method requires a liveConnectSession object. How do I provide that? It is given to me on the onAuthComplete method.
How do I mock the calls to onAuthComplete and onAuthError? I read about ArgumentCaptor but when I use that, I need to provide the arguments to those methods when I call the actual method.
For instance, argument.getValue().onAuthComplete() requires me to add arguments to this call. What do I actually provide here?
Here is the next method which is roughly the same but has its own issues:
protected void getUserIdAndConnectWithBackendServer(final LiveConnectSession liveConnectSession, final LiveAuthClient
authClient) {
final LiveConnectClient connectClient = new LiveConnectClient(liveConnectSession);
connectClient.getAsync("me", new LiveOperationListener() {
#Override
public void onComplete(LiveOperation liveOperation) {
// We got a result. Check for errors...
JSONObject result = liveOperation.getResult();
if (result.has(ERROR)) {
JSONObject error = result.optJSONObject(ERROR);
String code = error.optString(CODE);
String message = error.optString(MESSAGE);
onErrorOccured();
} else {
connectWithBackend(result, liveConnectSession, authClient);
}
}
#Override
public void onError(LiveOperationException e, LiveOperation liveOperation) {
// We failed to retrieve user information.... show error
onErrorOccured();
logUserOut(authClient, false);
}
});
}
In here I would like to mock the JSONObject for instance. But how do I call the onComplete method, or the onError method. And what would I provide as the arguments the methods provide me with. LiveOperation for instance?
Thank you!!
The solution I eventually used was to use mockito's doAnswer() structure.
This enabled me to get the callback argument and call one of its methods.
Another solution was to use an ArgumentCator.

Built.io upload progress - android

I want to show progress of my file upload. I use built.io to store my files, but really don't know how I can show progress, because I think built.io does not support this.
This is how I send file:
final BuiltFile builtFileObject = new BuiltFile();
builtFileObject.setFile(tempFile.getPath());
builtFileObject.save(new BuiltResultCallBack() {
#Override
public void onSuccess() {
}
#Override
public void onError(BuiltError builtError) {
Toast.makeText(getContext(),"blad zapisu pliku",Toast.LENGTH_SHORT).show();
}
#Override
public void onAlways() {
}
});
This is not possible using the current SDK provided by built.io. There is a plan to support this in the future.
A workaround is to call built.io using the REST APIs (check out the REST section on https://docs.built.io/guide#uploads). The regular HTTP upload call can then be tracked to get the progress detail.
Please mail us at support#built.io if you have any more queries with this! Glad to help.

Robospice. Retry failed request on demand

I need to implement quite popular template of app behaviour - give opportunity to user to retry failed requests. Right now I catch failed request with SpiceServiceListener, and shows dialog where user can press "Retry" button. Unfortunately, using the same CachedSpiceRequest object with SpiceManager.execute() don't give desired behaviour, because RS removing all request listeners from mapRequestToLaunchToRequestListener if request wasn't successful. So request can work fine, but it will not return any information to my Activity.
Is there easy way (without modifying code of library) to implement this?
Unfortunately looks like there are no abstract solution for situation like this, so I had to add code like this in every request.
getSpiceManager().execute(r, new RequestListener<CountProfiles>() {
#Override
public void onRequestFailure(SpiceException spiceException) {
if (act.getSupportFragmentManager().findFragmentByTag("network_problem") == null) {
NetworkProblemDialogFragm.newInstance(r, this).show(act.getSupportFragmentManager(), "network_problem");
} else {
((NetworkProblemDialogFragm) act.getSupportFragmentManager().findFragmentByTag("network_problem")).setSpiceRequest(r);
((NetworkProblemDialogFragm) act.getSupportFragmentManager().findFragmentByTag("network_problem")).setRequestListener(this);
}
}
#Override
public void onRequestSuccess(CountProfiles countProfiles) {
}
});
NetworkProblemDialogFragm is a DialogFragment with Retry button, on click on this button I re execute failed request, using given RequestListener.
Not very beautiful solution, but looks like there no better one.

Categories

Resources