How to import Guava into Android applications - android

What is the proper way to import Guava into an Android project? Every time I try to use it I get a NoClassDefFoundError.
This is what I'm doing to generate the crash. I'm using Android Studio 3.0 Canary 7.
Create an new project File > New > New Project, target API 26.0, using the Empty Activity template.
Add to app/build.gradle in the dependencies section
implementation "com.google.guava:guava:20.0"
Add this to the onCreate method in MainActivity.java
ImmutableList<String> foo = ImmutableList.of("A", "B", "C");
Log.d("MainActivity", foo.get(0));
Run the App and open up Logcat to see this exception:
FATAL EXCEPTION: main
Process: com.letsdoit.guavaissue, PID: 14366
java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/common/collect/ImmutableList;
at com.letsdoit.guavaissue.MainActivity.onCreate(MainActivity.java:20)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.common.collect.ImmutableList" on path: DexPathList[[zip file "/data/app/com.letsdoit.guavaissue-1/base.apk", zip file "/data/app/com.letsdoit.guavaissue-1/split_lib_dependencies_apk.apk", zip file "/data/app/com.letsdoit.guavaissue-1/split_lib_slice_0_apk.apk", zip file "/data/app/com.letsdoit.guavaissue-1/split_lib_slice_1_apk.apk", zip file "/data/app/com.letsdoit.guavaissue-1/split_lib_slice_2_apk.apk", zip file "/data/app/com.letsdoit.guavaissue-1/split_lib_slice_3_apk.apk", zip file "/data/app/com.letsdoit.guavaissue-1/split_lib_slice_4_apk.apk", zip file "/data/app/com.letsdoit.guavaissue-1/split_lib_slice_5_apk.apk", zip file "/data/app/com.letsdoit.guavaissue-1/split_lib_slice_6_apk.apk", zip file "/data/app/com.letsdoit.guavaissue-1/split_lib_slice_7_apk.apk", zip file "/data/app/com.letsdoit.guavaissue-1/split_lib_slice_8_apk.apk", zip file "/data/app/com.letsdoit.guavaissue-1/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.letsdoit.guavaissue-1/lib/x86, /system/lib, /vendor/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at com.letsdoit.guavaissue.MainActivity.onCreate(MainActivity.java:20) 
at android.app.Activity.performCreate(Activity.java:6679) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6119) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
I'm almost certain it has to do with Gauva being large and not playing well with multidex, but am not sure what to do about it. These are some of the note worthy things I've tried to no avail:
Enabling multidex and specifying ImmutableList in the multiDexKeepFile.
Disabling instant run.
Pulled the APKs from the device and verified the Guava classes are in the APKs.
Following the recommendations in this stack overflow question.

TL;DR
Use guava version 22.0-android and up. Make sure to use the -android flavor, otherwise you'll run into the NoClassDefFoundError.
Explanation
I learned after posting the question how to manually clean the project and uninstall apks from the emulator. It turns out that version 20.0 actually does work, but I had tried version 21.0 right before then and failed to clean.
The non-android flavors of guava as of version 21.0 are using Java 8. The android flavors and versions before 21.0 use Java 7. This is described in these release notes for version 22.0.
I tested these flavors and versions:
20.0 (Java 7) - works
21.0 (Java 8) - doesn't work
22.0 (Java 8) - doesn't work
22.0-android (Java 7) - works
When using version 21.0 or 22.0 (no -android) the ImmutableList class is getting referenced but not compiled into the dex files (since it's in italics). This was causing the NoClassDefFoundError.
APK with dangling references to ImmutableList
As the android developer docs explain
In the tree view, italicized nodes are references that do not have a
definition in the selected DEX file.
It further explains that
A DEX file can reference methods and fields that are defined in a
different a file. For example System.out.println() is a reference to
the println() method in the Android framework.
But in this case, there is no other file that these methods and class definition should end up in. It's just failing to add them.
Contrast that to using 20.0 or 22.0-android, where the ImmutableList class actually gets compiled in.
APK with ImmutableList defined
And the app starts up as expected.

Related

java.lang.UnsatisfiedLinkError- While loading customized .so files

OpenCV increasing size of apk So I customized OpenCV and reduced its size by this. All scripts ran fine and I got new libopencv_java4.so with reduced size. Now I updated these files into my project which already working fine (Only has issue with size) But now I am getting error like:`
java.lang.UnsatisfiedLinkError: dlopen failed: could not load library "C:/Users/ubuntu/Desktop/Development/Android/MyProject/opencv/native/libs/armeabi-v7a/libopencv_java4.so" needed by "libnative-lib.so"; caused by library "C:/Users/ubuntu/Desktop/Development/Android/MyProject/opencv/native/libs/armeabi-v7a/libopencv_java4.so" not found
at java.lang.Runtime.loadLibrary(Runtime.java:371)
at java.lang.System.loadLibrary(System.java:989)
at com.abc.android.count_ai.BaseActivity.<clinit>(BaseActivity.java:11)
at com.abc.android.sdk.MainActivity.<init>(MainActivity.java:46)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1650)
at android.app.Instrumentation.newActivity(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2640)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2873)
at android.app.ActivityThread.access$900(ActivityThread.java:181)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1482)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6145)
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:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
`
I just updated newly generated customized opencv shared libs in project. Before that project was working. Am I missing something? or I have to do something with newly generated opencv .so files to make these working.
As I faced this issue I again switch to original files and ran the project. Its working. Issue is with only new files. I ran `
arm-linux-androideabi-strip --strip-unneeded libopencv_tiny.so
`
This command at last as given in link. Is this creating problem?

ClassNotFoundException thrown after Data/Cache cleaning - second run OK

The application I am working on shows a strange symptom - if one cleans data and cache of the application, the application will crash on the first next run with exception, but on the second run it will run without a problem. Does anybody have any idea what could be going on and how to fix it.
What I already did:
deleted all the build dirs and rebuild
disabled instant run
check that the class is in the apk
tired it on multiple phones - all behave the same
Sadly nothing helped...
I am using the latest Android Studio 3.2.1. Compile and target SDK is 28, minimal 21. The app is written in Kotlin. Support lib is 28.0.0 and build tools 28.0.3.
The exception thrown on the first run (the name of the application was changed to protect the innocent):
2018-11-26 18:18:38.780 17135-17135/com.myapp.app E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.myapp.app, PID: 17135
java.lang.RuntimeException: Unable to instantiate service service.ServerNotificationService: java.lang.ClassNotFoundException: Didn't find class "service.ServerNotificationService" on path: DexPathList[[zip file "/data/app/com.myapp.app-YIEEjJIdfXs58PSDfpg4Ew==/base.apk"],nativeLibraryDirectories=[/data/app/com.myapp.app-YIEEjJIdfXs58PSDfpg4Ew==/lib/arm64, /data/app/com.myapp.app-YIEEjJIdfXs58PSDfpg4Ew==/base.apk!/lib/arm64-v8a, /system/lib64, /system/vendor/lib64]]
at android.app.ActivityThread.handleCreateService(ActivityThread.java:3459)
at android.app.ActivityThread.-wrap4(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1702)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6710)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:770)
Caused by: java.lang.ClassNotFoundException: Didn't find class "service.ServerNotificationService" on path: DexPathList[[zip file "/data/app/com.myapp.app-YIEEjJIdfXs58PSDfpg4Ew==/base.apk"],nativeLibraryDirectories=[/data/app/com.myapp.app-YIEEjJIdfXs58PSDfpg4Ew==/lib/arm64, /data/app/com.myapp.app-YIEEjJIdfXs58PSDfpg4Ew==/base.apk!/lib/arm64-v8a, /system/lib64, /system/vendor/lib64]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:93)
at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at android.app.ActivityThread.handleCreateService(ActivityThread.java:3456)
at android.app.ActivityThread.-wrap4(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1702) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6710) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:770) 
So I managed to fix it. It was related to how Android tools merge AndroidManifest.xml files.
Let me explain (for posterity):
The application I am building is composed from a core - which is an android library and the actual application. The class service.ServerNotificationService is part of the library and was declared in AndroidManifest.xml of the said library as:
<service android:name="service.ServerNotificationService" />
Which is correct and the app will run - just not with the clean cache (I still do not understand this part, but I presume it has something to do with the black magic which is Android ART). To fix the problem I changed the line to:
<service android:name="com.myapp.app.core.service.ServerNotificationService" />
Which is the full name for the class. The lesson learned here is always use full class name in the libraries...

TensorFlow + AndroidScanner - couldn't find "libopencv_java3.so"

I'm having a problem with combining Tensorflow and AndroidScanner.
I use Tensorflow to display an overlay over the camera feed. I take a picture with the camera, and then send it to a server. It works.
Now I imported the AndroidScannerDemo, I want to use the taken picture and crop/transform it with the newly imported module. It crashes. When I open the ScanActivity (from the AndroidScannerDemo), it tries to load opencv, and never succeeds. The error message is as follows:
FATAL EXCEPTION: main
Process: fr.pacifica.insurancechat.debug, PID: 2139
java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/fr.pacifica.insurancechat.debug-OI_d1EANbiczpZEwAHYdkw==/base.apk"],nativeLibraryDirectories=[/data/app/fr.pacifica.insurancechat.debug-OI_d1EANbiczpZEwAHYdkw==/lib/arm64, /data/app/fr.pacifica.insurancechat.debug-OI_d1EANbiczpZEwAHYdkw==/base.apk!/lib/arm64-v8a, /system/lib64, /system/vendor/lib64]]] couldn't find "libopencv_java3.so"
at java.lang.Runtime.loadLibrary0(Runtime.java:1011)
at java.lang.System.loadLibrary(System.java:1657)
at com.scanlibrary.ScanActivity.(ScanActivity.java:125)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1190)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2837)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3046)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1688)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6809)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
When I delete TensorFlow references from gradle/code, the imported module works just fine.
The project you imported, only builds 32-bit versions of libScanner.so, and therefore only uses the 32-bit versions of libopencv_java3.so. In the short run, you can keep that, only set
android {
defaultConfig {
ndk {
abiFilters 'armeabi-v7a'
}
}
}
This will cause your APK run in 32-bit mode on arm64 devices.
In the long run, you should update the Scanner library to build in 64-bit, too. This may have a significant performance gain.
from August 2019, 64-bit support is required for all apps in Play Store
I had the same problem with some mobiles (64 bits processor)
Here is the libs you need for every single arquitecture. You can download it and import manually.
https://github.com/jhansireddy/AndroidScannerDemo/tree/2cd23d3d362d0a6248cf489a79ebc4ba2c425c60/ScanDemoExample/scanlibrary/src/main/libs

Android Wear - java.lang.ClassNotFoundException

I'm developing an Android Wear extension to an existing app. While working on Android Studio I'm getting the following every time I'm running the wear module AFTER I run the main app, and the wear app crashes on start:
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.mobile.activities.MainActivity" on path: DexPathList[[zip file "/data/app/com.example.mobile-2/base.apk"],nativeLibraryDirectories=[/data/app/com.example.mobile-2/lib/x86, /vendor/lib, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5422)
The only solution I found for this is File > Invalidate Caches/Restart and then Build > Clean project.
After that I can run the wear module (until the next main run).
This makes my work very slow. Can someone help me here? 
ClassNotFoundException was thrown when an application tries to load in a class through its string name using:
The forName method in class Class.
The findSystemClass method in class ClassLoader .
The [loadClass](https://developer.android.com/reference/java/lang/ClassLoader.html#loadClass(java.lang.String, boolean)) method in class ClassLoader.
but no definition for the class with the specified name could be found.
As of release 1.4, this exception has been retrofitted to conform to the general purpose exception-chaining mechanism. The "optional exception that was raised while loading the class" that may be provided at construction time and accessed via the getException() method is now known as the cause, and may be accessed via the getCause() method, as well as the aforementioned "legacy method."
Found this SO related ticket, issue was resolved by doing steps below:
Right click on your project and select Properties.
Select Java Build Path from the menu on the left.
Select the Order and Export tab.
From the list make sure the libraries or external jars you added to your project are checked.
Finally, clean your project & run.
You may also check this SO ticket: Android Activity ClassNotFoundException - tried everything

Android Tesseract App crashes on OCR Function

I am trying to implement Tesseract into my android project but am getting a crash when trying to complete the OCR.
Here is how I'm setting up Tesseract:
TessBaseAPI baseApi = new TessBaseAPI();
baseApi.setDebug(true);
baseApi.init(imagePath, "eng");
baseApi.setImage(bitmap);
String recognizedText = baseApi.getUTF8Text();
baseApi.end();
This is how I'm setting up the image information to pass into the TesseractAPI:
destination = new File(Environment.getExternalStorageDirectory(), name + ".png");
imagePath = destination.getAbsolutePath();
String name = dateToString(new Date(),"yyyy-MM-dd-hh-mm-ss");
Here is the Logcat:
10734-10734/www.rshdev.com.ocr E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: www.rshdev.com.ocr, PID: 10734
java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/www.rshdev.com.ocr-1/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]] couldn't find "libpngt.so"
at java.lang.Runtime.loadLibrary(Runtime.java:366)
at java.lang.System.loadLibrary(System.java:988)
at com.googlecode.tesseract.android.TessBaseAPI.<clinit>(TessBaseAPI.java:43)
at www.rshdev.com.ocr.MainActivity.ocr(MainActivity.java:140)
at www.rshdev.com.ocr.MainActivity.onActivityResult(MainActivity.java:86)
at android.app.Activity.dispatchActivityResult(Activity.java:6192)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3570)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3617)
at android.app.ActivityThread.access$1300(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1352)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Your tesseract does not crash in the OCR function, it crashes trying to load a library:
java.lang.UnsatisfiedLinkError: ... couldn't find "libpngt.so"
...
at com.googlecode.tesseract.android.TessBaseAPI.<clinit>(TessBaseAPI.java:43)
But line 43 in the source that I have reads:
System.loadLibrary("tess");
therefore it tries to load libtess.so but reports a failure on libpngt.so.
Either:
1) your source code of TessBaseAPI.java is different, it contains System.loadLibrary("pngt"); and that library is missing. Make sure the .apk contains it. Eclipse used to have a misfeature: if your code depends on a library, you configure that dependency for compilation in one place and for delivery in another place. And IIRC .so dependency was specified in a 3rd place.
2) libtess.so is compiled with dynamic linking (try to use static linking then)
3) you are trying to run it in the emulator (try on a real device then).
This is all what can be said from the information you provided.
More info about solution:
I faced with this issue when I moved from Windows to Linux. My Linux had no NDK installed.
I've downloaded it from official source.
Instructions for installing under Linux:
Go to the directory where you downloaded it.
Execute the package. For example:
ndk$ chmod a+x android-ndk-r10c-darwin-x86_64.bin
ndk$ ./android-ndk-r10c-darwin-x86_64.bin
You also need to rebuild tess-two under Linux. Follow the instruction in oficial source.
Make sure that you are using the same gradle version on your project and in the tess lib project. Example:
buildscript {
dependencies {
classpath 'com.android.tools.build:gradle:1.5.0'
}
}
The value on classpath must be equals on both projects.
do not update any gradle aur sdk update... i repeat ..do ignore all
the update if asking and it will work smoothly. Just import the
project of priyankverma######## from github and IGNORE all the
updates ... i am sure you wont get this libpngt.so error.
Download or clone the project
import in android studio
let the gradle and sdk versions as it is and
IGNORE all the UPDATES even it is saying "Strongly Recommended.
simply run the project. :)

Categories

Resources