IONIC 3 : UnhandledPromiseRejectionWarning when generating APK File - java

I'm facing problems when generating apk file. I get the following error.
Command : ionic cordova build android
Output :
> cordova build android
Android Studio project detected
ANDROID_HOME=C:\Users\****\AppData\Local\Android\Sdk
JAVA_HOME=C:\Program Files\Java\jdk-9.0.4
(node:17504) UnhandledPromiseRejectionWarning: Unhandled promise rejection (reje
ction id: 1): CordovaError: Requirements check failed for JDK 1.8 or greater
(node:17504) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate th
e Node.js process with a non-zero exit code.
[13:47:49] lint finished in 8.47 s
This is the content of my rest file rest.ts
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
#Injectable()
export class RestProvider {
private baseUrl = 'http://localhost/project/web/rest/mobile/v1/';
private nomsvillesUrl = this.baseUrl + 'ville/nomsvilles/1';
constructor(public http: HttpClient) {
console.log('Hello RestProvider Provider');
}
getNomvilles(): Observable<string[]> {
return this.http.get(this.nomsvillesUrl)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res;
return body || { };
}
private handleError (error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const err = error || '';
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}
This is the content of my main class main.ts
import { Component } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { RestProvider } from '../../providers/rest/rest';
#Component({
selector: 'page-main',
templateUrl: 'main.html',
})
export class MainPage {
villes: string[]
errorMessage: string
constructor(public navCtrl: NavController, public navParams: NavParams, public rest: RestProvider) {
}
ionViewDidLoad() {
this.getVilles();
}
getVilles() {
this.rest.getNomvilles().subscribe(
villes => this.villes = villes,
error => this.errorMessage = <any>error
);
}
}
Please help me ! I want to know how to handle Promise in order to prevent promise rejection.
Thank you .

The error has nothing related to your code. It's asking for jdk 1.8 or higher you can download it from this link. But first uninstall jdk 1.9 you're using because it's not compatible with android.
Then create a environment variable JAVA_HOME=C:\path\to\jdk\bin

Related

Grails3: The return type of java.lang.Boolean hasErrors() in AuthRoleController is incompatible with boolean in grails.artefact.Controller

I have upgrade my app from grails 2.5 to grails 3.3.11.I have followed all the step and everything seem to be fine,but when I run the app. I am having this error :
startup failed:
/home/server-dev/Documents/dev_repo/tms/grails-app/controllers/org/niport/auth/AuthRoleController.groovy: -1: The return type of java.lang.Boolean hasErrors() in org.niport.auth.AuthRoleController is incompatible with boolean in grails.artefact.Controller
. At [-1:-1] # line -1, column -1.
1 error
FAILURE: Build failed with an exception.
What went wrong:
Execution failed for task ':compileGroovy'.
Compilation failed; see the compiler error output for details.
Any idea or assistance will be helpfull, thanks a lot
------------------------AuthUserController.groovy ---------------------
import grails.plugin.springsecurity.SpringSecurityService
import grails.transaction.Transactional
import org.niport.com.ComTrainingCenter
import org.niport.com.ComTrainingCenterService
import org.niport.com.FileService
import org.niport.com.TrackerService
import org.springframework.security.core.context.SecurityContextHolder
import javax.imageio.ImageIO
import java.awt.image.BufferedImage
import static org.springframework.http.HttpStatus.CREATED
import static org.springframework.http.HttpStatus.OK
#Transactional(readOnly = true)
class AuthUserController {
private static final allowedImageType = ['image/png', 'image/jpeg']
SpringSecurityService springSecurityService
AuthUserService authUserService
TrackerService trackerService
FileService fileService
def dateParseFormat,
currentDate
AuthUser currentUser
#Transactional
save(AuthUser userInstance) {
if (userInstance == null) {
flash.error = message(code: "default.message.noRecordFound.label", default: "Error-Save-AuthUser-L21 : Record not found...!")
redirect(action: "create")
return
}
userInstance.avatarType = params.attachment ? fileService.uploadFile("auth", "auth_user", userInstance?.username, "any", 1, 5000000, params.attachment) : null
userInstance.createdBy = currentUser?.id
userInstance.properties["hdCode"] = trackerService.getHdCode(params.password)
userInstance.validate()
if (userInstance.hasErrors()) {
flash.error = "Error-Save-AuthUser-L27 : " + userInstance.errors
redirect(action: "create", userInstance: userInstance)
return
}
try {
userInstance.save(failOnError: true)
}
catch (Exception e) {
println "ex-user-sa-L112 : " + e
flash.error = "Error-Save-AuthUser-L113 : " + e
redirect(action: "create", userInstance: userInstance)
return
}
request.withFormat {
form multipartForm {
flash.success = message(code: "default.message.created", args: [message(code: "user.pageTitle.label", default: "AuthUser"), userInstance.id])
redirect userInstance
}
'*' { respond userInstance, [status: CREATED] }
}
}}
--------------------------AuthRoleController.groovy ----------------------
mport grails.transaction.Transactional
import grails.validation.Validateable
//import grails.artefact.Controller
//import java.lang.*
import static org.springframework.http.HttpStatus.CREATED
import static org.springframework.http.HttpStatus.OK
class AuthRoleController implements Validateable {
static allowedMethods = [save: "POST", update: "PUT"]
def springSecurityService, dateFormat, currentDate, currentUser
def beforeInterceptor = {
currentDate = new Date()
currentUser = springSecurityService.getCurrentUser()
dateFormat = grailsApplication.config.format.dtp.date
}
#Transactional
def save(AuthRole roleInstance) {
roleInstance.createdBy=(AuthUser)currentUser
roleInstance.validate()
if (roleInstance == null) {
flash.error = message(code: "default.message.noRecordFound.label", default: "Error-Save-AuthRole-L21 : Record not found...!")
redirect(action: "create")
return
}
log.info "${roleInstance}";
if (roleInstance.hasErrors()) {
flash.error = "Error-Save-AuthRole-L27 : " + roleInstance.errors
redirect(action: "create", roleInstance: roleInstance)
return
}
try {
roleInstance.save failOnError: true
}
catch (Exception e) {
flash.error = "Error-Save-AuthRole-L36 : " + e
redirect(action: "create", roleInstance: roleInstance)
return
}
request.withFormat {
form multipartForm {
flash.success = message(code: "default.message.created", args: [message(code: "role.pageTitle.label", default: "AuthRole"), roleInstance.id])
redirect roleInstance
}
'*' { respond roleInstance, [status: CREATED] }
}
}
}
}
class AuthRoleController implements Validateable
There is no good reason to have a controller implement the Validateable trait, and doing so will cause problems.
The issue is you are going to get 2 methods named hasErrors, one from https://github.com/grails/grails-core/blob/1979b62d0ef9ebbaa547c8744263376557a10459/grails-plugin-validation/src/main/groovy/grails/validation/Validateable.groovy#L58 and one from https://github.com/grails/grails-core/blob/1979b62d0ef9ebbaa547c8744263376557a10459/grails-plugin-controllers/src/main/groovy/grails/artefact/Controller.groovy#L123, and they have different return types.

Does Kotlin supports AIDL?

I have a simple AIDL definition and I want to use in Kotlin code but when it builds shows Unresolved reference error for all variables that uses the interface. but the same AIDL has no problem in Java code. does Kotlin support it? how to solve
here my AIDL in src/main/aidl/
// ServiceInterface.aidl
package com.example.test;
interface ServiceInterface {
void test(String arg1);
}
and activity code is
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.os.RemoteException
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.swiftytime.clientappcommunication.R
import com.example.test.ServiceInterface
class MainActivity : AppCompatActivity() {
var mServiceAidl: ServiceInterface? = null
var mIsBound = false
private val mConnection: ServiceConnection = object : ServiceConnection {
override fun onServiceConnected(className: ComponentName, service: IBinder) {
try {
mServiceAidl = ServiceInterface.Stub.asInterface(service)
Log.e("app", "Attached")
} catch (e: RemoteException) {
}
}
override fun onServiceDisconnected(className: ComponentName) {
mServiceAidl = null
Log.e("app", "Disconnected.")
}
}
private fun doBindService() {
val intent = Intent().apply {
component = ComponentName(
"com.example.test", "com.example.test.MyService"
)
}
bindService(
intent,
mConnection, Context.BIND_AUTO_CREATE
)
mIsBound = true
Log.e("app", "Binding.")
}
private fun doUnbindService() {
if (mIsBound) {
unbindService(mConnection)
mIsBound = false
Log.e("app", "Unbinding.")
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
doBindService()
}
}
this is error
[ERROR] [org.gradle.api.Task] e: /Volumes/Projects/AndroidProject/ClientAppCommunication/app/src/main/java/com/example/test/MainActivity.kt: (16, 23): Unresolved reference: ServiceInterface
After many hours, I found the problem which is buildToolsVersion 29.0.0 generate wrong path for generated java files, I submitted a bug
Just changing to buildToolsVersion 28.0.3 solve the issue.
Update:
Problem Solved and now it works in buildToolsVersion 29.0.1
I'm using AIDL with Kotlin and what I have is interfaces written in Java and all model classes that are used by defined interfaces are written in Kotlin and it is working perfectly.
For example. I have I*Subscriber.aidl with method
void onSomeEventHappened(in AidlEvent event);
and also I have the .aidl file and .kt file for AidlEvent class.
AidlEvent.aidl file
// AidlEvent.aidl
parcelable AidlEvent;
AidlEvent.kt
data class AidlEvent(
val eventType: Int,
val eventMessage: String):
Parcelable {
// add parcelable methods
}
I'm not sure that you will be able to write .aidl interface in Kotlin, haven't managed to do that. It should not be an issue if you need to write few methods in Java, as you don't need to implement them in Java, you will just declare them.

How to make an alert Box that ask user if he wants to leave the page or not only angular?

I see every day that some app has a function that when you are on a page and you are filling, for example, a form and when you tried and click somewhere else for example in nav menu or even leave the page and you have unsafe change they ask the user if he wants to leave the page, I would really appreciate if someone can provide me an example of how can this be implemented in Angular, I am not sure if this is a front or backend job in backend I am working with java. Thanks a lot, each idea count :D.
You can use canDeactivate guard for every component,
First you have to add this service file "deactivate-guard.service.ts":
import { Injectable } from '#angular/core';
import { CanDeactivate } from '#angular/router';
import { Observable } from 'rxjs/Observable';
export interface CanComponentDeactivate {
canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}
#Injectable()
export class DeactivateGuardService implements CanDeactivate<CanComponentDeactivate>{
canDeactivate(component: CanComponentDeactivate) {
return component.canDeactivate ? component.canDeactivate() : true;
}
}
then you have to provide in the app module:
providers: [
DeactivateGuardService
]
now in the component you want to protect, add the function:
export class ExampleComponent {
loading: boolean = false;
#ViewChild('exampleForm') exampleForm: NgForm;
canDeactivate(): Observable<boolean> | boolean {
if (this.loading|| this.exampleForm.dirty) {
return this.confirmBox('Discard Unsaved Changes?');
}
return true;
}
confirmBox(message?: string): Observable<boolean> {
const confirmation = window.confirm(message || 'Are you sure?');
return of(confirmation);
};
}
Add the directive to the component in the routing module:
#NgModule({
imports: [
RouterModule.forRoot([
{
path: 'example',
canDeactivate: [DeactivateGuardService],
component: ExampleComponent
}
])
]
You can use the canDeactivate guard to check a page leave and display the warning message you wish to display something like this
import { Injectable } from '#angular/core';
import { CanDeactivate } from '#angular/router';
import { Observable } from 'rxjs/Observable';
export interface CanComponentDeactivate {
canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}
#Injectable()
export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate>{
canDeactivate(component: CanComponentDeactivate) {
return component.canDeactivate ? component.canDeactivate() : true;
}
}
include set the can activate guard to the route like this
{ path: 'sample-path', component: SampleComponent, canDeactivate: [CanDeactivateGuard] },
and the canDeactivate method to the component
canDeactivate() {
if (this.formIsIncomplete > 0) {
let result: boolean = window.confirm("You have unsaved Changes");
return result;
}
return true;
}
it may helpful for you to make alert
https://stackblitz.com/edit/angular-confirmation-dialog

secuesocial 3.0-M1 on play2.1.0?

I've been using play 2.1.0 for a while and I've been having trouble looking for a way to get securesocial to work. I tried different versions, even downloaded the latest typesafe activator to try to use it with play2.4 but no luck.
Does anyone know if can I use securesocial 3.0-M1 with play 2.1.0?
my controllers\application.java
package controllers;
import play.Logger;
import play.libs.F;
import play.mvc.Controller;
import play.mvc.Result;
import securesocial.core.BasicProfile;
import securesocial.core.RuntimeEnvironment;
import securesocial.core.java.SecureSocial;
import securesocial.core.java.SecuredAction;
import securesocial.core.java.UserAwareAction;w
import service.DemoUser;
import views.html.index;
import views.html.linkResult;
public class Application extends Controller {
public static Logger.ALogger logger =
Logger.of("application.controllers.Application");
private RuntimeEnvironment env;
public Application(RuntimeEnvironment env) {
this.env = env;
}
public Result index() {
if(logger.isDebugEnabled()){
logger.debug("access granted to index
DemoUser user = (DemoUser) ctx().args.get(SecureSocial.USER_KEY);
return ok(index.render(user, SecureSocial.<DemoUser>env()));
}
#UserAwareAction
public Result userAware()
{
DemoUser demoUser = (DemoUser) ctx().args.get(SecureSocial.USER_KEY);
String userName ;
if ( demoUser != null ) {
BasicProfile user = demoUser.main;
if ( user.firstName().isDefined() ) {
userName = user.firstName().get();
} else if ( user.fullName().isDefined()) {
userName = user.fullName().get();
} else {
userName = "authenticated user";
}
} else {
userName = "guest";
}
return ok("Hello " + userName + ", you are seeing a public page");
}
#SecuredAction(authorization = WithProvider.class, params = {"twitter"})
public Result onlyTwitter() {
return ok("You are seeing this because you logged in using Twitter");
}
#SecuredAction
public Result linkResult() {
DemoUser current = (DemoUser) ctx().args.get(SecureSocial.USER_KEY
}
public F.Promise currentUser() {
return SecureSocial.currentUser(env).map( new F.Function<Object, Result>() {
#Override
public Result apply(Object maybeUser) throws Throwable {
String id;
if ( maybeUser != null ) {
DemoUser user = (DemoUser) maybeUser;
id = user.main.userId();
} else {
id = "not available. Please log in.";
}
return ok("your id is " + id);
}
});
}
}
my routes
Home page
GET / #controllers.Application.index
GET /userAware #controllers.Application.userAware
GET /only-twitter #controllers.Application.onlyTwitter
GET /link-result #controllers.Application.linkResult
GET /current-user #controllers.Application.currentUser
GET /assets/*file controllers.Assets.at(path="/public", file)
-> /auth securesocial.Routes
my error
[info] Set current project to playMongoDemooo (in build file:/C:/Users/kayjee%20
lahong/demo2/)
[info] Updating {file:/C:/Users/kayjee%20lahong/demo2/}playMongoDemooo...
[info] Resolving org.hibernate.javax.persistence#hibernate-jpa-2.0-api;1.0.1.Fin
[info] Done updating.
--- (Running the application from SBT, auto-reloading is enabled) ---
[info] play - Listening for HTTP on /0:0:0:0:0:0:0:0:9000
(Server started, use Ctrl+D to stop and go back to the console...)
[info] Compiling 6 Scala sources and 6 Java sources to C:\Users\kayjee lahong\de
mo2\target\scala-2.10\classes...
[error] C:\Users\kayjee lahong\demo2\conf\routes:10: Cannot use a method returni
ng play.libs.F.Promise[play.mvc.Result] as an Handler
[error] GET /current-user #controllers.Application.currentUser
[error] C:\Users\kayjee lahong\demo2\conf\routes:10: Cannot use a method returni
ng play.libs.F.Promise[play.mvc.Result] as an Handler
[error] GET /current-user #controllers.Application.currentUser
[error] two errors found
[error] (compile:compile) Compilation failed
[error] application -
thank you
For Play 2.4 compatibility use 3.0-M4 or newer. The version you were trying to use does not work with 2.4.

Error developing phonegap cordova 2.2.0 plugin for android

I'm trying to write a PhoneGap Cordova 2.2.0 plugin for Android, but I'm having issues, and I'm unsure what the cause is.
Here is my JS:
PushCapure.js
var PushCapture = {
init : function () {
console.log('Attempting to call the PushCapture plugin');
return cordova.exec(function() {
alert('PushCapture was successful');
}, function(error) {
alert('PushCapture failed');
}, "PushCapture", "capture", []);
}
};
Now here is my native code I want to run
com.ron.camanon.PushCapture.java
package com.ron.camanon;
import org.apache.cordova.api.CordovaPlugin;
import android.util.Log;
public class PushCapture extends CordovaPlugin {
public void capture()
{
Log.i("PushCapture", "PushCapture called, capture video stream intended...");
}
}
This isn't working for me, I've also added this line to my res/config.xml :
<plugin name="PushCapture" value="com.ron.camanon.PushCapture"/>
The error callback is the only thing that is executed when I try my plugin.
What am I doing wrong?
This is Cordova 2.2.0 for Android
That isn't how the plugins work in Android, looks like you are using the iOS model where it calls a certain method. In Android the "method" or specific command for the plugin will be sent as a string within the exec function see the code example below from the Phonegap tutoral for plugins on Android
#Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if ("beep".equals(action)) {
this.beep(args.getLong(0));
callbackContext.success();
return true;
}
return false; // Returning false results in a "MethodNotFound" error.
}

Categories

Resources