Search code examples
javaandroidtypescriptnativescriptnativescript-angular

Cannot read property MyToast.java of undefined


I have been following this Tutorial to achieve Write Java code in nativescript and use directly in typescript

But I got an error Cannot read property 'MyToast' of undefined

app.component.ts:

import {Component} from "@angular/core";
let application = require("application");

declare var org:any;
@Component({
    selector: "my-app",
    templateUrl: "app.component.html",
})
export class AppComponent {


    public onTap() {
        org.example.MyToast.showToast(application.android.context,"You pressed the button","short");
    }
}

I have create MyToast.java class in platforms-> src -> java -> org ->example :

package org.example;

import android.widget.Toast;
import android.content.Context;


public class MyToast{

    public static void showToast(Context context,String text ,String StrDuration ){

        Toast.makeText(context,text, Toast.LENGTH_SHORT).show();
    }
}

Solution

  • Did you perform a build? Metadata for JavaScript->Java invocation will not be generated in a simple tns run android where a build has not been triggered.

    If you touch platforms/android, a build will not be provoked, as that directory is not being watched.

    tns build android - this will ensure that, when making manual changes in platforms/android, a build will be triggered.

    Offtopic: Also, I am happy to share that you will be able to create those classes directly in your App_Resources/Android directory in the 4.0 release of NativeScript, without worrying for your custom class being wiped clean when changing workstations, cleaning your project.