Android Studio: connecting to MongoDB server with Mongo Java Driver
There's a lot of posts about this problem, but noone seems to work, so maby some things have changed.
I am trying to connect my android application to a MongoDB server located on mLab. I'm using Mongo Java Drived and have off course added the library to android studio.
It is possible to start the app, but when I click on the register button the application craches.
Here's my code:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText username = (EditText)findViewById(R.id.username);
final Button bRegister = (Button) findViewById(R.id.bRegister);
bRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String stringUsername = username.toString();
try {
addToDatabase(stringUsername);
} catch(Exception e) {
e.printStackTrace();
}
}
});
}
private static void addToDatabase(String username){
MongoClientURI uri = new MongoClientURI("mongodb:///*mLab database URL */");
MongoClient client = new MongoClient(uri);
MongoDatabase db = client.getDatabase(uri.getDatabase());
MongoCollection<Document> coll = db.getCollection("newDB");
Document doc = new Document("username", username);
coll.insertOne(doc);
client.close();
}
}
I also have permision.INTERNET in the manifest file.
Any help would be very appreciated!
//Edit Stacktrace:
03/10 02:43:09: Launching app
Cold swapped changes.
$ adb shell am start -n "com.newhdc.pedergb.mongodb_servertester/com.newhdc.pedergb.mongodb_servertester.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Client not ready yet..Waiting for process to come online
Connected to process 4752 on device emulator-5554
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
W/org.bson.ObjectId: Failed to get process identifier from JMX, using random number instead
java.lang.NoClassDefFoundError: Failed resolution of: Ljava/lang/management/ManagementFactory;
at org.bson.types.ObjectId.createProcessIdentifier(ObjectId.java:533)
at org.bson.types.ObjectId.<clinit>(ObjectId.java:491)
at com.mongodb.connection.ClusterId.<init>(ClusterId.java:47)
at com.mongodb.connection.DefaultClusterFactory.create(DefaultClusterFactory.java:105)
at com.mongodb.Mongo.createCluster(Mongo.java:744)
at com.mongodb.Mongo.createCluster(Mongo.java:728)
at com.mongodb.Mongo.createCluster(Mongo.java:702)
at com.mongodb.Mongo.<init>(Mongo.java:310)
at com.mongodb.Mongo.<init>(Mongo.java:306)
at com.mongodb.MongoClient.<init>(MongoClient.java:284)
at com.newhdc.pedergb.mongodb_servertester.MainActivity.addToDatabase(MainActivity.java:39)
at com.newhdc.pedergb.mongodb_servertester.MainActivity.access$000(MainActivity.java:14)
at com.newhdc.pedergb.mongodb_servertester.MainActivity$1.onClick(MainActivity.java:29)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
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 "java.lang.management.ManagementFactory" on path: DexPathList[[dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-support-annotations-25.1.0_11ac1b6ae4b8623fca16868c12f685674e962f99-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-slice_9-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-slice_8-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-slice_7-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-slice_6-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-slice_5-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-slice_4-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-slice_3-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-slice_2-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-slice_1-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-slice_0-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-mongodb-driver-core-3.4.2_cf1ecbf321a58b8bf97e118b2c0ff7614ac982a5-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-mongodb-driver-3.4.2_cfefe7ed281d321e57736b38e1e68fc6160680ac-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-com.android.support-support-vector-drawable-25.1.0_3dbe341ffa762dac2cc1137bc6aae1731f3bc1c0-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-com.android.support-support-v4-25.1.0_c534a46cb17b55c593319a94e0d90e0b75103a24-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-com.android.support-support-media-compat-25.1.0_b58e3876df91b49420cb0766dd6edfdbff0dedbc-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-com.android.support-support-fragment-25.1.0_d616629f11d994c207dfc4b5d01648e3194bccbc-classes.dex", dex f
I/cluster: Cluster created with settings {hosts=[ds123080.mlab.com:23080], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: **FATAL EXCEPTION**: main
Process: com.newhdc.pedergb.mongodb_servertester, PID: 4752
java.lang.ExceptionInInitializerError
at com.mongodb.connection.InternalStreamConnectionFactory.<init>(InternalStreamConnectionFactory.java:41)
at com.mongodb.connection.DefaultClusterableServerFactory.create(DefaultClusterableServerFactory.java:68)
at com.mongodb.connection.BaseCluster.createServer(BaseCluster.java:360)
at com.mongodb.connection.SingleServerCluster.<init>(SingleServerCluster.java:54)
at com.mongodb.connection.DefaultClusterFactory.create(DefaultClusterFactory.java:114)
at com.mongodb.Mongo.createCluster(Mongo.java:744)
at com.mongodb.Mongo.createCluster(Mongo.java:728)
at com.mongodb.Mongo.createCluster(Mongo.java:702)
at com.mongodb.Mongo.<init>(Mongo.java:310)
at com.mongodb.Mongo.<init>(Mongo.java:306)
at com.mongodb.MongoClient.<init>(MongoClient.java:284)
at com.newhdc.pedergb.mongodb_servertester.MainActivity.addToDatabase(MainActivity.java:39)
at com.newhdc.pedergb.mongodb_servertester.MainActivity.access$000(MainActivity.java:14)
at com.newhdc.pedergb.mongodb_servertester.MainActivity$1.onClick(MainActivity.java:29)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
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.NullPointerException: Attempt to invoke virtual method 'java.security.CodeSource java.security.ProtectionDomain.getCodeSource()' on a null object reference
at com.mongodb.connection.ClientMetadataHelper.getDriverVersion(ClientMetadataHelper.java:111)
at com.mongodb.connection.ClientMetadataHelper.getDriverInformation(ClientMetadataHelper.java:201)
at com.mongodb.connection.ClientMetadataHelper.addDriverInformation(ClientMetadataHelper.java:182)
at com.mongodb.connection.ClientMetadataHelper.<clinit>(ClientMetadataHelper.java:64)
at com.mongodb.connection.InternalStreamConnectionFactory.<init>(InternalStreamConnectionFactory.java:41)
at com.mongodb.connection.DefaultClusterableServerFactory.create(DefaultClusterableServerFactory.java:68)
at com.mongodb.connection.BaseCluster.createServer(BaseCluster.java:360)
at com.mongodb.connection.SingleServerCluster.<init>(SingleServerCluster.java:54)
at com.mongodb.connection.DefaultClusterFactory.create(DefaultClusterFactory.java:114)
at com.mongodb.Mongo.createCluster(Mongo.java:744)
at com.mongodb.Mongo.createCluster(Mongo.java:728)
at com.mongodb.Mongo.createCluster(Mongo.java:702)
at com.mongodb.Mongo.<init>(Mongo.java:310)
at com.mongodb.Mongo.<init>(Mongo.java:306)
at com.mongodb.MongoClient.<init>(MongoClient.java:284)
at com.newhdc.pedergb.mongodb_servertester.MainActivity.addToDatabase(MainActivity.java:39)
at com.newhdc.pedergb.mongodb_servertester.MainActivity.access$000(MainActivity.java:14)
at com.newhdc.pedergb.mongodb_servertester.MainActivity$1.onClick(MainActivity.java:29)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
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)
Application terminated.
Solution 1:
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.
Solution 2:
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.