小编典典

Android Studio:使用Mongo Java驱动程序连接到MongoDB服务器

java

关于此问题的文章很多,但是似乎没人能解决,因此maby的某些情况已经改变。

我正在尝试将我的Android应用程序连接到位于mLab上的MongoDB服务器。我正在使用Mongo Java
Drived,当然已经将该库添加到android studio中。

可以启动应用程序,但是当我单击注册按钮时,应用程序崩溃了。

这是我的代码:

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();
}
}

我在清单文件中也有permision.INTERNET。

任何帮助将不胜感激!

//编辑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.


阅读 220

收藏
2020-11-01

共1个答案

小编典典

我遇到过同样的问题。确实存在问题是您在主线程中调用了连接。将以下内容添加到onCreate方法。

@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);
        }

希望能有所帮助。

2020-11-01