How to import Guava into Android applications

后端 未结 1 419
梦谈多话
梦谈多话 2021-01-27 17:42

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 generat

相关标签:
1条回答
  • 2021-01-27 18:22

    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.

    0 讨论(0)
提交回复
热议问题