Java Question Another onActivityResult: wi is null

jahswant

Well-Known Member
Licensed User
Longtime User
I'm trying to create a wrapper of this repository with little success. Always getting wi is null. I also tried with JavaObject with no success still same result. This is my wrapper code.

B4X:
package cm.jahswant.docscanner;


import java.io.FileNotFoundException;
import java.io.InputStream;

import com.example.monscanner.ScanActivity;
import com.example.monscanner.ScanConstants;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import anywheresoftware.b4a.BA;
import anywheresoftware.b4a.BA.Events;
import anywheresoftware.b4a.BA.Hide;
import anywheresoftware.b4a.BA.ShortName;
import anywheresoftware.b4a.BA.Version;
import anywheresoftware.b4a.IOnActivityResult;
import anywheresoftware.b4a.objects.drawable.CanvasWrapper.BitmapWrapper;

@Version(0.20f)
@ShortName("DocScannerUp")
@Events(values={"onCameraResult(scannedImage As Bitmap)","onGaleryResult(scannedImage As Bitmap)"})
@BA.DependsOn(values = {"monscanner-release.aar"})
public class DocScannerWrapper{
    private BA ba;
    private String eventName;
    private Intent intent;
    private static IOnActivityResult ion;

    /*
     * Initialize the MonScanner  *
     */       
    public void Initialize(BA ba, String EventName) {
        _initialize(ba, null, EventName);
    }

    @Hide
    public void _initialize(BA ba, Object activityClass, String EventName) {
        this.eventName = EventName.toLowerCase(BA.cul);
        this.ba = ba;
     }
        
    public void openCamera(){
        intent = new Intent("com.example.monscanner.ScanActivity");
         intent.putExtra(ScanConstants.OPEN_INTENT_PREFERENCE, ScanConstants.OPEN_CAMERA);       
         ion = new IOnActivityResult() {           
            @Override
            public void ResultArrived(int resultCode, Intent intent) {
                // TODO Auto-generated method stub                               
                try {               
                    if( intent != null) {
                           Uri imageUri = (intent.getExtras()).getParcelable(ScanActivity.SCAN_RESULT);
                           if( imageUri != null) {
                               InputStream imageStream = ba.context.getContentResolver().openInputStream(imageUri);
                               Bitmap scannedImage = BitmapFactory.decodeStream(imageStream);
                               ba.context.getContentResolver().delete(imageUri, null, null);
                               BitmapWrapper bm = new BitmapWrapper();
                               bm.setObject(scannedImage);
                               ba.raiseEvent(this, eventName + "_oncameraresult",scannedImage);       
                           }                     
                       }   
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }           
                
            }
        };           
        ba.startActivityForResult(ion, intent);   
    }
    
    public void openGalery(){
        intent = new Intent("com.example.monscanner.ScanActivity");
         intent.putExtra(ScanConstants.OPEN_INTENT_PREFERENCE, ScanConstants.OPEN_GALERIE);       
         ion = new IOnActivityResult() {           
            @Override
            public void ResultArrived(int resultCode, Intent intent) {
                // TODO Auto-generated method stub                               
                try {               
                   if( intent != null) {
                       Uri imageUri = (intent.getExtras()).getParcelable(ScanActivity.SCAN_RESULT);
                       if( imageUri != null) {
                           InputStream imageStream = ba.context.getContentResolver().openInputStream(imageUri);
                           Bitmap scannedImage = BitmapFactory.decodeStream(imageStream);
                           ba.context.getContentResolver().delete(imageUri, null, null);
                           BitmapWrapper bm = new BitmapWrapper();
                           bm.setObject(scannedImage);
                           ba.raiseEvent(this, eventName + "_ongaleryresult",scannedImage);       
                       }                     
                   }
                  
               } catch (FileNotFoundException e) {
                   e.printStackTrace();
               }           
                
            }
        };           
        ba.startActivityForResult(ion, intent);   
    }
        
}

This the try with JavaObject

B4X:
#Region  Project Attributes
    #ApplicationLabel: B4A Example
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
    #AdditionalJar:monscanner-release.androidx.aar
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Private ion As Object
End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.

End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    'Activity.LoadLayout("Layout1")
    ShowPicker
End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Sub ShowPicker
    Dim i As Intent
    i.Initialize("com.example.monscanner.ScanActivity", "")
    i.PutExtra("open_intent_preference", 1)
    StartActivityForResult(i)
End Sub


Sub ion_Event (MethodName As String, Args() As Object) As Object
    'Args(0) = resultCode
    'Args(1) = intent
    Return Null
End Sub

Sub StartActivityForResult(i As Intent)
    Dim jo As JavaObject = GetBA
    ion = jo.CreateEvent("anywheresoftware.b4a.IOnActivityResult", "ion", Null)
    jo.RunMethod("startActivityForResult", Array As Object(ion, i))
End Sub

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

What am I doing wrong. Advice to make this work correctly.
 

DonManfred

Expert
Licensed User
Longtime User
@BA.DependsOn(values = {"monscanner-release.aar"})
try remove this reference as you are referencing it with #AdditionalJar already (but another aar)...
 

jahswant

Well-Known Member
Licensed User
Longtime User
Sorry for the late answer.
Can you post the logs?
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = false **
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = false **
onActivityResult: wi is null
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = false **
onActivityResult: wi is null
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = false **
onActivityResult: wi is null
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = false **
onActivityResult: wi is null
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = false **
onActivityResult: wi is null
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = false **
onActivityResult: wi is null
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = false **
onActivityResult: wi is null
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = false **
onActivityResult: wi is null
** Activity (main) Resume **
 

jahswant

Well-Known Member
Licensed User
Longtime User
try remove this reference as you are referencing it with #AdditionalJar already (but another aar)...
I use this without AdditionalJar Directive.

#AdditionalJar:monscanner-release.androidx.aar

I use this with JavaObject.
 

jahswant

Well-Known Member
Licensed User
Longtime User
You need to find the correct intent that starts the scanner app.
MainActivity:
package com.example.openscan;

This the code used in the MainActivity of the Example the intent Started is ScanActivity.

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;

import com.example.monscanner.ScanActivity;
import com.example.monscanner.ScanConstants;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Objects;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;

public class MainActivity extends AppCompatActivity {

    private final int REQUEST_CODE = 7;
    private ImageView imageView;

    [USER=69643]@override[/USER]
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView= findViewById(R.id.finalImageView);
    }


    public void openGalerie(View view) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }
        else {
            startScan(ScanConstants.OPEN_GALERIE);
        }
    }

    public void openCamera(View view) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2);
        }
        else {
            startScan(ScanConstants.OPEN_CAMERA);
        }
    }

    private void startScan(int preference) {
        Intent intent = new Intent(this, ScanActivity.class);
        intent.putExtra(ScanConstants.OPEN_INTENT_PREFERENCE, preference);
        startActivityForResult(intent, REQUEST_CODE);
    }

    [USER=69643]@override[/USER]
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE) {
                try {
                    assert data != null;
                    Uri imageUri = Objects.requireNonNull(data.getExtras()).getParcelable(ScanActivity.SCAN_RESULT);
                    assert imageUri != null;
                    InputStream imageStream = getContentResolver().openInputStream(imageUri);
                    Bitmap scannedImage = BitmapFactory.decodeStream(imageStream);
                    getContentResolver().delete(imageUri, null, null);
                    imageView.setImageBitmap(scannedImage);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
 

Johan Schoeman

Expert
Licensed User
Longtime User
For what it might be worth (and I might probably be wrong) - I had the same error on numerous occasions with wrappers and more often than not the issue was in the B4A manifest file. Once the Manifest was sorted out the project(s) ran fine.

You should have something similar to this in your B4A Manifest file:

B4X:
AddApplicationText(<activity android:name="com.example.monscanner.ScanActivity"
    android:screenOrientation="portrait" android:configChanges="orientation|keyboardHidden"
    android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
    android:windowSoftInputMode="stateAlwaysHidden">
</activity>)
 
Last edited:

jahswant

Well-Known Member
Licensed User
Longtime User
I will let this down, didn't succeed. I will do the app directly from Android Studio.
 

Johan Schoeman

Expert
Licensed User
Longtime User
I have done a shortcut wrap for it (i.e kickstarting the MainActivity of the sample project from within B4A) and it is working.

Attached is :
1. the Java project (src folder only). You need to add the libs folder and the additional/lib folder with the contents that they need. I have appcompat-v7-28.0.0.jar, support-annotations-28.0.0.jar, and android-support-v4.jar in my libs folder. The additional/lib folder must be populated with the arm64-v8a, armeabi-v7a, x86, and x86_64 folders (these 4 folder should contain their respective libopencv_java4.so files)

Made some changes to some of the layout files to add full package names to for eg CameraActivity, ScanActivity, MainActivity, etc
Edited the Java code with Notepad++ and compiled it with Simple Library Compiler (-b4a ignore must be set to com.,org.). The library must be Jetified and the project cleaned prior to compiling the B4A project.

Extract the folders and their contents from ResFoldersForB4Aproject.zip and copy the folders and their contents to be on the same folder level as that of the /Objects and /Files folders of the B4A project.

B4A Manifest is as follows:
B4X:
AddManifestText(
<uses-sdk android:minSdkVersion="5" android:targetSdkVersion="19"/>
<supports-screens android:largeScreens="true"
    android:normalScreens="true"
    android:smallScreens="true"
    android:anyDensity="true"/>)
SetApplicationAttribute(android:icon, "@drawable/icon")
SetApplicationAttribute(android:label, "$LABEL$")
CreateResourceFromFile(Macro, Themes.DarkTheme)

SetApplicationAttribute(android:theme, "@style/MyAppTheme")

AddApplicationText(<activity android:name="com.example.openscan.MainActivity">
        </activity>)

    AddApplicationText(<activity android:name="com.example.monscanner.CameraActivity"
            android:configChanges="orientation"
            android:screenOrientation="portrait"
            android:theme="@style/NoActionBar" />
        <activity
            android:name="com.example.monscanner.ScanActivity"
            android:configChanges="orientation"
            android:label="@string/lib_name"
            android:screenOrientation="portrait"
            android:theme="@style/NoActionBar" />)



Not uploading the compiled library as it is 45MB. Sure you will be able to compile it.


1.png


2.png


3.png



4.png


Sample code:

B4X:
#Region  Project Attributes
    #ApplicationLabel: b4aDocumentScanner
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: portrait
    #CanInstallToExternalStorage: False
#End Region

#AdditionalRes: ..\openCVres
#AdditionalRes: ..\LibRes
#AdditionalRes: ..\DemoRes
#AdditionalRes: ..\resource

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.

End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.

    Dim ds As DocumentScanner

    Private Button1 As Button
End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    Activity.LoadLayout("main")

    ds.Initialize("ds")


End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub


Sub Button1_Click

    ds.startDetection

End Sub

Have not added anything to the Java code to raise events etc in the B4A project. You can change the code in the attached Java code (src.zip)

Enjoy and have fun...:);) No wi is null error...
 

Attachments

  • b4aDocumentScanner.zip
    9.6 KB · Views: 532
  • ResFoldersForB4Aproject.zip
    165.5 KB · Views: 509
  • src.zip
    96.8 KB · Views: 540
Last edited:

idrotelapp

Member
Licensed User
Dear friend ,
will you please send me the compiled version of document scanner lib.
I am badly in need of lib and cannot compile it.

Many thanks in advance
 

Situ LLC

Active Member
Licensed User
Nice , very nice but I need this lib
DocumentScanner
please any link where I cans download it
thanks
 
Top