Android Tutorial Inline Java Code

The next versions of B4A (4.30) and B4J (2.80) will allow you to embed Java code inside your B4X code. B4i supports similar feature with Objective C.

The purpose of this feature is to make it easier to access third party SDKs and also to allow developers to add existing Java code snippets to their projects.

Adding Java code is done with an #If Java block:
B4X:
#If JAVA
public String FirstMethod() {
   return "Hello World!";
}
#End If

You need an instance of JavaObject to access the Java methods:
B4X:
Sub Process_Globals
   Private NativeMe As JavaObject
End Sub

Sub Globals

End Sub

Sub Activity_Create(FirstTime As Boolean)
   If FirstTime Then
     NativeMe.InitializeContext
   End If
   Dim s As String = NativeMe.RunMethod("FirstMethod", Null)
   Log(s) 'will print Hello World!
End Sub
The Java code can also include imports. The compiler will find these imports and add them at the top of the class.

The Java code will be added at the end of the class. Right before the closing bracket.

Methods added to Activity or Service modules will be executed with the component context ('this' will be the activity or service instance).

Hooks

Hooks are similar to the standard events but they run Java methods. Hooks are mainly used by SDKs that require you to add code in the various Activity events.
Note that there are no hooks in B4J implementation.

For example the following code will run in the standard Activity onCreate method (before the call to setContentView):
B4X:
#If JAVA
public void _onCreate() {
   requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
}
#End If

Activity hooks:
_onCreate()
_onResume()
_onPause()
_onDestroy()
_onStop()
_onStart()
_onPrepareOptionsMenu (android.view.Menu menu)
boolean _onCreateOptionsMenu (android.view.Menu menu) <--- If you return true from this method then the standard B4A code in onCreateOptionsMenu will not run.
boolean _onkeydown (int keyCode, android.view.KeyEvent event) <-- Return true from this method to return true from the native onKeyDown (and skip Activity_KeyPress event).
boolean _onkeyup (int keyCode, android.view.KeyEvent event) <-- same comment as above

Service hooks:
_onCreate()
_onStartCommand(Intent intent, int flags, int startId)
_onDestroy()

Tips

- The methods you add should be public methods.
- Methods in static code modules should be public static.
- See the attached project. It shows how to call Java methods in all types of modules.

Don't misuse this feature. There are no performance advantages for using it and it can make your project more difficult to debug and maintain.
 

Attachments

  • InlineJava.zip
    12.7 KB · Views: 3,165
  • B4J-InlineJava.zip
    1.2 KB · Views: 1,743
Last edited:

Lee Gillie CCP

Active Member
Licensed User
ok.... I see now...
B4X:
    'lower cased module name
    NativeMe.InitializeStatic(Application.PackageName & ".globals")
instead.... but still failing....
globals_getstacktrace (java line: 348)
java.lang.ClassCastException: anywheresoftware.b4a.objects.collections.List cannot be cast to java.util.List
at odp.eljaydelivery.globals._getstacktrace(globals.java:348)
at odp.eljaydelivery.globals._reporterror(globals.java:922)
at odp.eljaydelivery.main._btntest_click(main.java:513)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at anywheresoftware.b4a.BA.raiseEvent2(BA.java:187)
at anywheresoftware.b4a.BA.raiseEvent2(BA.java:175)
at anywheresoftware.b4a.BA.raiseEvent(BA.java:171)
at anywheresoftware.b4a.objects.ViewWrapper$1.onClick(ViewWrapper.java:78)
at android.view.View.performClick(View.java:4764)
at android.view.View$PerformClick.run(View.java:19844)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5376)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
java.lang.ClassCastException: anywheresoftware.b4a.objects.collections.List cannot be cast to java.util.List
 

Lee Gillie CCP

Active Member
Licensed User
Found my issue. My problem is that I created B4A code and looked at the Java created from it, and tried to model after that. It really wants you to use native java, and it magically performs any conversions.

B4X:
#if JAVA
import java.util.*;
public static List GetStackTraceJava()
{
    List jlst = new ArrayList();
    jlst.add("Test 1");
    jlst.add("Test 2");
    return jlst;
}
#End If

And the above works perfectly.

The other lesson learned is that initialization for Class and Module differs. You gotta pay attention and study the download samples from Inline Java tutorial. Resolving class members is a different process apparently than resolving module methods.
 
Last edited:

jcohedman

Member
Licensed User
Someone of goodwill, with more knowledge than me,
can think and give a tip on how to use OpenCV, maybe is best JavaCV (https://github.com/bytedeco/javacv),
with this new features of b4a (#Additionaljar and java code)?
Thanks

P.S.:
In https://github.com/bytedeco/javacv we can obtain JavaCV 0.10 binary archive:
  • javacv-0.10-bin.zip
The binary archive contains builds for Linux, Mac OS X, Windows, and Android
(it contain the files: javacv-android-x86.jar, opencv-android-x86.jar, ffmpeg-android-x86.jar etc..
as well as javacv-android-arm.jar, opencv-android-arm.jar, ffmpeg-android-arm.jar etc..).
The hamletic doubt about desired JAR files to use is dissolved? We can use these jar files?
The *-android-arm.jar or *-android-x86.jar files?

I'm working with images, using imagej http://imagej.nih.gov/ij/ . I use #AdditionalJar: ij (ij.jar), and at least I can open an image...
 

mshafiee110

Active Member
Licensed User
Hi Erel,

cheers

ok i have understand principal.
Great work!

greetings
espi


B4X:
Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    Activity.LoadLayout("x")
    If FirstTime Then
    NativeMe.InitializeContext
    End If
End Sub

..
..


#If JAVA

import android.app.AlertDialog;

// import android.content.BroadcastReceiver;
// import android.content.Context;
// import android.content.Intent;
// import android.os.Bundle;
// import android.content.DialogInterface;
// import android.app.Activity;


public void txs() {

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("You Are Welcome")
        .setMessage("Txs for Inline Erel ;-)")
        .setNeutralButton("Ok", null);
AlertDialog dialog = builder.create();
dialog.show();
}
#end if



Sub Button1_Down
        NativeMe.RunMethod("txs", Null)
End Sub
Hi.
How to know which button was clicked?
 

DonManfred

Expert
Licensed User
How to know which button was clicked?
1. You should start a new thread for your question.
2. You should give us more informaiton. A sample project uploaded for example.
 

MarcoRome

Expert
Licensed User

MarcoRome

Expert
Licensed User
Example #1 is easy to understand, but how about my example ? Is there any tutorial to write Java from "https://developer.android.com" ?
Don't you think the Example #1 is like 1+1=2, but the real world is like (2!/3.2216749347027!)^0.6763271392719... ?
Thank you anyways...

??
There are many tutorials on the net that you can read ( LINK )
And...also our great @Johan Schoeman he has written several tutorial. For example you can watch this ( LINK )
 

walterf25

Expert
Licensed User
The next versions of B4A (4.30) and B4J (2.80) will allow you to embed Java code inside your B4X code. B4i supports similar feature with Objective C.

The purpose of this feature is to make it easier to access third party SDKs and also to allow developers to add existing Java code snippets to their projects.

Adding Java code is done with an #If Java block:
B4X:
#If JAVA
public String FirstMethod() {
   return "Hello World!";
}
#End If

You need an instance of JavaObject to access the Java methods:
B4X:
Sub Process_Globals
   Private NativeMe As JavaObject
End Sub

Sub Globals

End Sub

Sub Activity_Create(FirstTime As Boolean)
   If FirstTime Then
     NativeMe.InitializeContext
   End If
   Dim s As String = NativeMe.RunMethod("FirstMethod", Null)
   Log(s) 'will print Hello World!
End Sub
The Java code can also include imports. The compiler will find these imports and add them at the top of the class.

The Java code will be added at the end of the class. Right before the closing bracket.

Methods added to Activity or Service modules will be executed with the component context ('this' will be the activity or service instance).

Hooks

Hooks are similar to the standard events but they run Java methods. Hooks are mainly used by SDKs that require you to add code in the various Activity events.
Note that there are no hooks in B4J implementation.

For example the following code will run in the standard Activity onCreate method (before the call to setContentView):
B4X:
#If JAVA
public void _onCreate() {
   requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
}

Activity hooks:
_onCreate()
_onResume()
_onPause()
_onDestroy()
_onStop()
_onStart()
_onPrepareOptionsMenu (android.view.Menu menu)
boolean _onCreateOptionsMenu (android.view.Menu menu) <--- If you return true from this method then the standard B4A code in onCreateOptionsMenu will not run.
boolean _onkeydown (int keyCode, android.view.KeyEvent event) <-- Return true from this method to return true from the native onKeyDown (and skip Activity_KeyPress event).
boolean _onkeyup (int keyCode, android.view.KeyEvent event) <-- same comment as above

Service hooks:
_onCreate()
_onStartCommand(Intent intent, int flags, int startId)
_onDestroy()

Tips

- The methods you add should be public methods.
- Methods in static code modules should be public static.
- See the attached project. It shows how to call Java methods in all types of modules.

Don't misuse this feature. There are no performance advantages for using it and it can make your project more difficult to debug and maintain.
How about _onOptionsItemSelected(MenuItem item)
does this hook exist and can it be called in B4A?

Thanks,
Walter
 

MarcoRome

Expert
Licensed User
thanks for examples.what about write a lib using JavaObject ? after the compiling succefully a library with java inline code using JavaObject why in the call of library(on press a button call code from library) will say the method java ,inline,wasn't found then apk will crash?

Example lib using JavaObject:
Accesing third party Jar with #Additionaljar and JavaObject - Picasso by @Erel
Android Speech Recognition API Wrapper by @stevel05
PDFDocument API 19+ by @stevel05


For next question ( "after the compiling succefully a library with java inline code using JavaObject why in the call of library(on press a button call code from library) will say the method java ,inline,wasn't found then apk will crash?" )
Open new thread and put more details ( type error log, code that you use, etc )

 
Top