B4A Library JavaObject library

Status
Not open for further replies.
The purpose of JavaObject library is similar to the purpose of Reflection library. Both libraries allow you to directly call Java APIs based on Java reflection features.

JavaObject design is different than Reflection library and in most cases simpler to use. However JavaObject doesn't replace Reflection library as it doesn't support all of its features. In many cases you can use both libraries together (both are lightweight libraries).

JavaObject approach is more "object oriented". You declare a JavaObject object which then "wraps" any other object and provide three methods: SetField, GetField and RunMethod.

JavaObject variable is similar to an Object variable with the addition of the reflection methods.

For example to set the padding of a view:
B4X:
Dim jLabel As JavaObject = Label1 'wrap the Label object
jLabel.RunMethod("setPadding", Array As Object(10dip, 10dip, 10dip, 10dip))
Note that you do not need to specify the parameters types. However the types should be the exact types. The call will fail if you pass a double instead of an int.

One exception is that you can pass a string instead of Enum.

There are also two Initialize methods.
InitializeStatic - Use this method when you want to call a static method or access a static field.

For example this code calls the static Bitmap.createScaledBitmap method:
B4X:
Sub CreateScaledBitmap(Original As Bitmap, Width As Int, Height As Int) As Bitmap
  Dim bo As JavaObject
  bo.InitializeStatic("android.graphics.Bitmap")
  Dim bmp As Bitmap = bo.RunMethod("createScaledBitmap", Array As Object(Original, Width, Height, False))
  Return bmp
End Sub

InitializeNewInstance - Creates a new instance of the given class with the given parameters (or Null)


Notes
- JavaObject can only access public methods and fields (unlike Reflection library).
- JavaObject doesn't include the helper methods to access the context and other fields as in Reflection library. You can use both libraries together when these fields are needed.
- There is almost no overhead for a JavaObject instance. It is better to create multiple JavaObjects instead of reusing a single instance.

V2.05 is attached.
 

Attachments

  • JavaObject.zip
    10.3 KB · Views: 1,788
Last edited:

Informatix

Expert
Licensed User
Longtime User
Hi Erel,
I am trying to use "android.view.View.OnSystemUiVisibilityChangeListener" like this
B4X:
Sub Activity_Create(FirstTime As Boolean)
   Dim jo As JavaObject = Activity
   Dim e As Object = jo.CreateEvent("android.view.View.OnSystemUiVisibilityChangeListener", "VisibilityChanged", Null)
   jo.RunMethod("setOnSystemUiVisibilityChangeListener", Array As Object(e))

but the compiler says "Syntax error" for the following code line :
B4X:
Dim e As Object = jo.CreateEvent("android.view.View.OnSystemUiVisibilityChangeListener", "VisibilityChanged", Null)
and I don't know why?

What is the Sub for the "VisibilityChange Event" ?
What is your version of the JavaObject library?
 

rhochzwei

Member
Licensed User
Longtime User
Can you post the error message?

Seems to work fine here:
B4X:
Sub Activity_Create(FirstTime As Boolean)
  Dim jo As JavaObject = Activity
  Dim e As Object = jo.CreateEvent("android.view.View.OnSystemUiVisibilityChangeListener", "VisibilityChanged", Null)
  jo.RunMethod("setOnSystemUiVisibilityChangeListener", Array As Object(e))
End Sub

It is just red underlined and says "Syntax error".

The Version of B4A I use is Version 3.82
JavaObject version 1.25
jdk version is 1.7.0_02
android.jar is under android-13

Maybe one of this versions are too old ?
 

rhochzwei

Member
Licensed User
Longtime User
Can you post a screenshot?
Here are the screenshots testet with the 3.5 version of B4A:
upload_2014-7-26_10-10-46.png


upload_2014-7-26_10-12-0.png
 

Attachments

  • upload_2014-7-26_10-11-30.png
    upload_2014-7-26_10-11-30.png
    15 KB · Views: 318

rhochzwei

Member
Licensed User
Longtime User
Maybe there is an invisible character on this line which causes this problem. Can you upload your project (File - Export as zip)?
I found it, it was a invisible character on this line. I deleted the line and typed it (and not copied it) new and it worked :)
 

dagofo

Member
Licensed User
Longtime User
Hello. I'm trying to complete one action comented bellow (Post #18).

The main objective is clean media library when one file is deleted. I found that in "scan_Event" I have to write this java code, but I don't know how traslate to V4A.

Any idea??

Thanks

B4X:
Private void scanaddedFile(String Path) {
    Try {
        MediaScannerConnection.scanFile(context, new String[] { Path },
                Null, new MediaScannerConnection.OnScanCompletedListener() {
                    Public void onScanCompleted(String Path, Uri Uri) {
                        Log.i("ExternalStorage", "Scanned " + Path + ":");
                        Log.i("ExternalStorage", "-> uri=" + Uri);

///////////// This line clean the media library in ScanCompleted event /////////////////////
                        context.getContentResolver().delete(Uri, Null, Null);  //This code clean the media libary from deleted file
///////////// This line clean the media library in ScanCompleted event /////////////////////
                    }
                });
    } Catch (Exception e) {
        e.printStackTrace();
    }
}

B4X:
Sub Activity_Create(FirstTime As Boolean)
   Dim MediaScanner As JavaObject
   MediaScanner.InitializeStatic("android.media.MediaScannerConnection")
   'Create the interface
   Dim e As Object = MediaScanner.CreateEvent("android.media.MediaScannerConnection.OnScanCompletedListener", "scan", Null)
   MediaScanner.RunMethod("scanFile", Array As Object(GetContext, _
     Array As String(File.Combine(File.DirRootExternal, "1.jpg")), _
     Null, _
     e))
End Sub

Sub scan_Event (MethodName As String, Args() As Object) As Object
   Log("Path = " & Args(0))
   Log("Uri = " & Args(1))

///////////// This line clean the media library in ScanCompleted event /////////////////////
HERE ??? (JAVA to V4A) context.getContentResolver().delete(Uri, Null, Null);  //This code clean the media libary from deleted file
///////////// This line clean the media library in ScanCompleted event /////////////////////

   Return False
End Sub

Sub GetContext As Object
   Dim jo As JavaObject = Activity
   Return jo.RunMethod("getContext", Null)
End Sub
 

Johan Schoeman

Expert
Licensed User
Longtime User
I am using library JavaObject V2.01 and it reports "The XML was improperly formatted. Please escape it if necessary" when using InitializeContext. Is there a later version of this library on the B4A forum where this has been sorted?
 

Robert Valentino

Well-Known Member
Licensed User
Longtime User
B4X:
Sub CreateScaledBitmap(Original As Bitmap, Width As Int, Height As Int) As Bitmap
  Dim bo As JavaObject
  bo.InitializeStatic("android.graphics.Bitmap")
  Dim bmp As Bitmap = bo.RunMethod("createScaledBitmap", Array As Object(Original, Width, Height, False))
  Return bmp
End Sub

When I try the above code I get an Error: java.lang.RuntimeException: Method: createScaledBitmap not matched.

ALSO get the same error (NOT MATCHED) if I try the following code:

B4X:
       Dim JavaObj   As JavaObject
   	   
   JavaObj.InitializeStatic("android.media.ThumbnailUtils")	   
   RoundBitmap = JavaObj.RunMethod("extractThumbnail", Array As Object(RoundBitmap, ((RoundBitmap.Width * 50)/100), ((RoundBitmap.Height * 50)/100), False))
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
Just tried this code and it works:
B4X:
Sub Activity_Create(FirstTime As Boolean)
   Log(CreateScaledBitmap(LoadBitmap(File.DirAssets, "image.png"), 100, 100))
End Sub

Sub CreateScaledBitmap(Original As Bitmap, Width As Int, Height As Int) As Bitmap
  Dim bo As JavaObject
  bo.InitializeStatic("android.graphics.Bitmap")
  Dim bmp As Bitmap = bo.RunMethod("createScaledBitmap", Array As Object(Original, Width, Height, False))
  Return bmp
End Sub
 

Phayao

Active Member
Licensed User
Longtime User
Hello that looks all very powerful - but as a complete Java-ignorant person I wonder if there is some reference webpage that lists and explains all these available methods like "createscaledBitmap" etc.
I'm sure there are thousands of these, how can we look them up ?
Thanks for some ideas,
Chris
 

Phayao

Active Member
Licensed User
Longtime User
Thanks Manfred, probably a very obvious place to look.
Nevertheless it's hard stuff for non-java people like me :(, especially it has little examples. But it's a start. For example i could not figure out how to get an image from the clipboard (for text we got a library)
Thanks, Chris :cool:
 

santiago

Member
Licensed User
Longtime User
I develop a software using an external bluetooth printer.It works fine. But I received a device with built-in printer. The vendor sent me the SDK and library and Eclipse example.
The library ,named j1009.jar has a folder with 2 files (.so files)

I copied the library and the folder inside VB4A libraries folder.

From the eclipse I attach the library class structure

I read your post and tried to use the library in several ways but allways received an error message

I show the last attempt I wrote, but it is not the only one.

#AdditionalJar:j1009

Sub GetContext As JavaObject
Return GetBA.GetField("context")
End Sub

Sub GetBA As JavaObject
Dim jo As JavaObject
Dim cls As String = Me
cls = cls.SubString("class ".Length)
jo.InitializeStatic(cls)
Return jo.GetFieldJO("processBA")
End Sub

Sub printe AsJavaObject

Dim jo AsJavaObject

Return jo.InitializeStatic("com.bw.spdev.Printer")

End Sub


Sub Button3_Click

Return printe.RunMethodJO("PrintString",Array("ggggg"))

End Sub

When click on button3, the error message is :
An error in sub:java.lang
illegalArgumentException:
expected received of type com.bw.spdev.printer ,but got java.lang.Class<com.bw.spdev.Printer>


Vendor's documentation for Printer class incluye ….. Printer.PrintString(string)


Any help or technical orientation would be appreciated. If you need more information I will suply.

ANother question is Can I build a VB4A library from eclipse based in this j1009 library ‘?

Thanks in advance for your time and beg your pardon if the question is silly (I am not java developer)
 

Attachments

  • lib1.png
    lib1.png
    5.8 KB · Views: 283
Status
Not open for further replies.
Top