How to connect to a MongoDB database, in Android?

TooLazy picture TooLazy · Jul 19, 2015 · Viewed 12.5k times · Source

This is how I add a Java driver to my project

compile 'org.mongodb:mongo-java-driver:2.13.2'

after I run my Android app Gradle crushes. if I add the jar directly, my app crushes anyway.

Connection code below:

MongoClient mongoClient = new MongoClient("mongodb://Dbuser:[email protected]:47692");
DB db = mongoClient.getDB("testdb");
Set<String> collectionNames = db.getCollectionNames();

All I need is to connect from my app to the mongo database. I am not sure of the correctness of my connection string. In my db account I have found:

To connect using a driver via the standard URI: mongodb://blablauser:[email protected]:47692/urdb

But in the code it doesn't connect.

I use mongo-java-driver. But every time i try to even read my db i get

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.artem.mongodb/com.example.artem.mongodb.MainActivity}: com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=ds047692.mongolab.com:47692, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.SocketException: socket failed: EACCES (Permission denied)}, caused by {android.system.ErrnoException: socket failed: EACCES (Permission denied)}}]

Document myDoc = collection.find().first();//crash point

Why i have no access to my own db?

Answer

Ravin Gupta picture Ravin Gupta · Nov 20, 2015

Try using this

MongoClientURI mongoUri  = new MongoClientURI("mongodb://Dbuser:[email protected]:47692");
MongoClient mongoClient = new MongoClient(mongoUri);
DB db = mongoClient.getDB("testdb");
Set<String> collectionNames = db.getCollectionNames();

First you need to convert the uri into MongoClientURI format.