Back to Blog Home
← all posts

How to use Java code with NativeScript

October 22, 2022 — by Nandee Tjihero

I'd like to show you how to use Java code you may write in Android Studio with NativeScript. This solution resulted from implementing the Room Persistence library for NativeScript.

To use the Java code in NativeScript, you have two options as illustrated in the following image from the NativeScript docs:


You either use the individual Java classes or package them into a library and use that library. In both cases, you should add the necessary dependencies to the app.gradle. In the case of the Room library, you need to add the following dependencies:

app-gradle.png Even if you decide to use the Java classes directly without the .aar and you're using Typescript, you'll still want to generate the .aar file to generate types for IntelliSense and strong type checking.

You can start by writing and testing the code you need in Android Studio. When you're satisfied:

  1. Convert the project(app module) to a library module by following steps 1-4 at Convert an app module to a library module.
  2. Package the library module, containing all the classes, into a .aar file. The image below shows the steps to take in order to produce the .aar file:

create-aar-file.png You can find the generated file at the location shown below: aar-file-location.png

  1. Drag and drop the app-release.aar onto The Archiver or a similar tool to get the classes.jar file that you use to generate the types for IntelliSense.
  2. To generate the types, run ns typings android –jar <path to the .jar > file from step 4.
  3. Reference the generated android.d.ts(you can rename it appropriately) file in the reference.d.ts.


Now when you type the full package name(com.ombuweb.testroomdb) the Java classes get suggested in VS Code: IntelliSense-in-action.png

See this NativeScript app demo using the Java code . You can find the Java code here.

Hopefully you found this post useful.


  • The Android Studio in the images: 4.1.1