Android Studio: connecting to MongoDB server with Mongo Java Driver Android Studio: connecting to MongoDB server with Mongo Java Driver mongodb mongodb

Android Studio: connecting to MongoDB server with Mongo Java Driver


Unfortunately, the Mongo Java Driver does not work on Android, as Android is missing some Java classes, according to this StackOverflow post. However, a kind StackOverflow user has forked the Mongo Java Driver and fixed the issue. You can see their version of the library on Github.

Scroll down to the description and download the latest jar file. Right now, it's this one:

https://github.com/matfur92/mongo-java-driver/blob/gh-pages/JARs/mongo-java-driver-3.4.0-SNAPSHOT.jar?raw=true.

Next, go ahead and delete the line in your build.gradle dependencies for mongo-java-driver. The line to delete should look something like this:

dependencies {    ...    compile 'org.mongodb:mongodb-driver:3.4.2'    ...}

Finally, add the jar you downloaded to your application (guide here). Now your code should work without modification. I was able to use regular MongoDB functionality just fine, but I was not able to get GridFS to work.


I had the same issue. Indeed problem is that you call the connection in the main thread.add the following to the onCreate method.

@Override    protected void onCreate(Bundle savedInstanceState) { if (android.os.Build.VERSION.SDK_INT > 9)        {            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();            StrictMode.setThreadPolicy(policy);        }

Hope that helps.