SQLite JDBC driver on Android

Viewed 5876

I'm trying to use xerial sqlite-jdbc to manage my database in Android with no success.I'm getting an java.lang.NoClassDefFoundError: org.sqlite.SQLiteConnection exception.I've imported this dependency 'org.xerial:sqlite-jdbc:3.18.0' in my gradle. My code is as follows,

 try {

        Class.forName("org.sqlite.JDBC");
        Connection connection = DriverManager.getConnection("jdbc:sqlite:hs.db");

    } catch (ClassNotFoundException eString) {System.err.println("Could not init JDBC driver - driver not found");
    } catch (java.sql.SQLException e) {e.printStackTrace();}

Using android.database.sqlite in my project is not option so please don't suggest that as an answer.

4 Answers

I needed to share some database code between my server DB and my phone DB, so I spent a lot of time writing the common code to use JDBC.

However, what I found out, after already being neck deep in this endeavor, is that there essentially isn't a working JDBC implementation on Android. I would strongly urge you not to go down this path - both Xerial and SQLDroid JDBC drivers have significant problems that I uncovered only during testing.

Problems with Xerial

It just doesn't work on Android :) It doesn't even load - I ran into this issue and couldn't work around it even after trying for hours.

Problems with SQLDroid

  1. See the Open Issues page - some of them were pretty scary to me. The deal breaker for me was the lack of batch support.
  2. See the Known Issues page before you start.

Finally, I ended up creating an implementation of the small subset of the java.sql interfaces and methods that I needed, using the android.database.sqlite classes. This was far less painful than I imagined (it took me just a couple of hours, for the subset of the functionality I needed) and it works great!

Here's my way:

  1. do some config in app/build.gradle, and copy a so file, looks ugly, but really works in my Android 9.0 system.
android {
    defaultConfig {
        ndk {
            abiFilters "armeabi-v7a"
        }
    }
    sourceSets {
        main {
            jniLibs.srcDirs = ['libs']
        }
    }
}
dependencies {
    implementation 'org.xerial:sqlite-jdbc:3.34.0'
}
  1. then copy this file sqlite-jdbc-3.34.0.jar!\org\sqlite\native\Linux\android-arm\libsqlitejdbc.so to app/libs/armeabi-v7a/, which looks like this: enter image description here.

  2. and the built apk looks like: enter image description here

  3. now you can enjoy javax.sql.DataSource of sqlite on android.

update gradle plugin version and gradle version to latest version

File -> Project Structure

project structure image

Related