在android应用中单击按钮时,数据未插入mongodb

时间:2018-12-19 06:25:03

标签: java android mongodb gradle jar

在将文件作为Java文件执行时,数据已插入mongodb中。 但是单击按钮时不起作用。

但是我想在单击按钮时插入数据。

Jave文件(数据库连接):

package com.example.raji.tfsystem;

import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class excellent {

public static void main(String args[]){
    raji();
}

public static void raji() {

    MongoClientURI uri = new MongoClientURI("mongodb://localhost:27017/raji");
    System.out.println("Get the URI");

    MongoClient client = new MongoClient(uri);
    System.out.println("Get the client");

    MongoDatabase db = client.getDatabase("raji");
    System.out.println("Get the DB");

    MongoCollection collection = db.getCollection("testcollection", BasicDBObject.class);
    System.out.println("Get the collection");

    BasicDBObject document= new BasicDBObject();
    document.put("name", "mkyong");
    document.put("age", 30);
    collection.insertOne(document);

    System.out.println("Document inserted successfully");


    client.close();
    System.out.println("connection closed");
}
}

运行Java文件的日志:()数据已成功插入):

"C:\Program Files\Android\Android Studio\jre\bin\java.exe" -Didea.launcher.port=51628 "-Didea.launcher.bin.path=C:\Program Files\Android\Android Studio\bin" -Dfile.encoding=UTF-8 -classpath "C:\Users\raji\AppData\Local\Android\Sdk\platforms\android-28\android.jar;C:\Users\raji\AppData\Local\Android\Sdk\platforms\android-28\data\res;C:\Users\raji\AndroidStudioProjects\TFSystem\app\build\intermediates\javac\debug\compileDebugJavaWithJavac\classes;C:\Users\raji\AndroidStudioProjects\TFSystem\app\build\generated\res\rs\debug;C:\Users\raji\AndroidStudioProjects\TFSystem\app\build\generated\res\resValues\debug;C:\Users\raji\.gradle\caches\transforms-1\files-1.1\customview-28.0.0.aar\17ad713aa4fe1c671b4ede1f37241832\jars\classes.jar;C:\Users\raji\.gradle\caches\transforms-1\files-1.1\localbroadcastmanager-28.0.0.aar\2fef515b48347abdcb28c6929cfd6c06\jars\classes.jar;C:\Users\raji\.gradle\caches\transforms-1\files-1.1\support-vector-drawable-28.0.0.aar\34e13ebdab35205549dc2987c8abfc7e\jars\classes.jar;C:\Users\raji\.gradle\caches\transforms-1\files-1.1\interpolator-28.0.0.aar\9f63a0c776c41ce3d0439fe49548df77\jars\classes.jar;C:\Users\raji\.gradle\caches\transforms-1\files-1.1\support-core-utils-28.0.0.aar\4e6592432ebd3f0519082a4a86a6875a\jars\classes.jar;C:\Users\raji\.gradle\caches\transforms-1\files-1.1\support-core-ui-28.0.0.aar\b015b46a05f9077fe9839519412457f7\jars\classes.jar;C:\Users\raji\.gradle\caches\transforms-1\files-1.1\slidingpanelayout-28.0.0.aar\bdb2b944fc7a1c1bac3e0731ef7bca4a\jars\classes.jar;C:\Users\raji\.gradle\caches\transforms-1\files-1.1\viewmodel-1.1.1.aar\7ac8ae9cb17c6514812cabe11569a463\jars\classes.jar;C:\Users\raji\.gradle\caches\transforms-1\files-1.1\drawerlayout-28.0.0.aar\fdb1da94ab6877aab2d0825f189bcf07\jars\classes.jar;C:\Users\raji\.gradle\caches\transforms-1\files-1.1\coordinatorlayout-28.0.0.aar\d2b6e491f82e7f84c85cf70584592189\jars\classes.jar;C:\Users\raji\.gradle\caches\transforms-1\files-1.1\coordinatorlayout-28.0.0.aar\d2b6e491f82e7f84c85cf70584592189\res;C:\Users\raji\.gradle\caches\modules-2\files-2.1\com.android.support\collections\28.0.0\c1bcdade4d3cc2836130424a3f3e4182c666a745\collections-28.0.0.jar;C:\Users\raji\.gradle\caches\transforms-1\files-1.1\documentfile-28.0.0.aar\4f2694955c01be226ed31bdc6c7d9050\jars\classes.jar;C:\Users\raji\.gradle\caches\transforms-1\files-1.1\constraint-layout-1.1.3.aar\1712982f5dcfdeba280d142375ccc2d6\jars\classes.jar;C:\Users\raji\.gradle\caches\transforms-1\files-1.1\constraint-layout-1.1.3.aar\1712982f5dcfdeba280d142375ccc2d6\res;C:\Users\raji\AndroidStudioProjects\TFSystem\libs\mongo-java-driver-3.3.0.jar;C:\Users\raji\.gradle\caches\transforms-1\files-1.1\swiperefreshlayout-28.0.0.aar\440f7bea4955e65de27de845f49fb5cc\jars\classes.jar;C:\Users\raji\.gradle\caches\transforms-1\files-1.1\cursoradapter-28.0.0.aar\78a277ba5c66f8d71c68186789accb68\jars\classes.jar;C:\Users\raji\.gradle\caches\transforms-1\files-1.1\asynclayoutinflater-28.0.0.aar\53fc8689c44c5782de3f6b1184ada75a\jars\classes.jar;C:\Users\raji\.gradle\caches\transforms-1\files-1.1\livedata-1.1.1.aar\5c2dc9beb7306bb33eee72cfb344b112\jars\classes.jar;C:\Users\raji\.gradle\caches\modules-2\files-2.1\android.arch.core\common\1.1.1\e55b70d1f5620db124b3e85a7f4bdc7bd48d9f95\common-1.1.1.jar;C:\Users\raji\.gradle\caches\transforms-1\files-1.1\versionedparcelable-28.0.0.aar\64f88816c66dc93916f41c64d17ad0e3\jars\classes.jar;C:\Users\raji\.gradle\caches\transforms-1\files-1.1\runtime-1.1.1.aar\cf1d41dc6a3ec0a1c46f2cad4143cd90\jars\classes.jar;C:\Users\raji\.gradle\caches\transforms-1\files-1.1\print-28.0.0.aar\06a68bc91d15203790b28ac845398676\jars\classes.jar;C:\Users\raji\.gradle\caches\transforms-1\files-1.1\loader-28.0.0.aar\8e35a1e68dd97b1cc1d3ed5224f41c59\jars\classes.jar;C:\Users\raji\.gradle\caches\transforms-1\files-1.1\viewpager-28.0.0.aar\f0f1f061bdbdad9bae552352496bc65e\jars\classes.jar;C:\Users\raji\.gradle\caches\transforms-1\files-1.1\support-fragment-28.0.0.aar\a02e0c4e125cc0ceb701bebc8333828f\jars\classes.jar;C:\Users\raji\.gradle\caches\modules-2\files-2.1\com.android.support\support-annotations\28.0.0\ed73f5337a002d1fd24339d5fb08c2c9d9ca60d8\support-annotations-28.0.0.jar;C:\Users\raji\.gradle\caches\modules-2\files-2.1\android.arch.lifecycle\common\1.1.1\207a6efae6a3555e326de41f76bdadd9a239cbce\common-1.1.1.jar;C:\Users\raji\.gradle\caches\transforms-1\files-1.1\livedata-core-1.1.1.aar\bf596f1e36e40fab05155a7fbbb5e62a\jars\classes.jar;C:\Users\raji\.gradle\caches\transforms-1\files-1.1\support-compat-28.0.0.aar\66054686eab03269bc7e5ea212080dff\jars\classes.jar;C:\Users\raji\.gradle\caches\transforms-1\files-1.1\support-compat-28.0.0.aar\66054686eab03269bc7e5ea212080dff\res;C:\Users\raji\.gradle\caches\transforms-1\files-1.1\animated-vector-drawable-28.0.0.aar\88e421448a190098b3789f8192bb1883\jars\classes.jar;C:\Users\raji\.gradle\caches\transforms-1\files-1.1\appcompat-v7-28.0.0.aar\d5a38ae1191d6408dbdaee74a5a71138\jars\classes.jar;C:\Users\raji\.gradle\caches\transforms-1\files-1.1\appcompat-v7-28.0.0.aar\d5a38ae1191d6408dbdaee74a5a71138\res;C:\Users\raji\.gradle\caches\modules-2\files-2.1\com.android.support.constraint\constraint-layout-solver\1.1.3\bde0667d7414c16ed62d3cfe993cff7f9d732373\constraint-layout-solver-1.1.3.jar;C:\Users\raji\.gradle\caches\transforms-1\files-1.1\runtime-1.1.1.aar\19463e142230a99be31543e87b6d7bd3\jars\classes.jar;C:\Program Files\Android\Android Studio\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMainV2 com.example.raji.tfsystem.excellent
Get the URI
Dec 18, 2018 4:36:55 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
Get the client
Get the DB
Get the collection
Dec 18, 2018 4:36:55 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: No server chosen by WritableServerSelector from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, serverDescriptions=[ServerDescription{address=localhost:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out
Dec 18, 2018 4:36:55 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:1, serverValue:8}] to localhost:27017
Dec 18, 2018 4:36:55 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 0, 4]}, minWireVersion=0, maxWireVersion=7, maxDocumentSize=16777216, roundTripTimeNanos=776983}
Dec 18, 2018 4:36:55 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:2, serverValue:9}] to localhost:27017
Document inserted successfully
Dec 18, 2018 4:36:55 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Closed connection [connectionId{localValue:2, serverValue:9}] to localhost:27017 because the pool has been closed.
connection closed

Process finished with exit code 0

使用应用程序运行Java文件:

mainActivity.java:

package com.example.raji.tfsystem;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;

public class MainActivity extends AppCompatActivity {

ImageButton exce;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    exce = findViewById(R.id.excellent);



    exce.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            excellent.raji();//we are calling the method from another class .
        }
    });
}
}

应用运行期间的日志:: :(应用崩溃)

I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/OpenGLRenderer: Swap behavior 0
D/EGL_emulation: eglCreateContext: 0x9b5e08a0: maj 3 min 1 rcv 4
D/EGL_emulation: eglMakeCurrent: 0x9b5e08a0: ver 3 1 (tinfo 0xa85367d0)
E/eglCodecCommon: glUtilsParamSize: unknow param 0x000082da
    glUtilsParamSize: unknow param 0x00008cdf
E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008824
D/EGL_emulation: eglMakeCurrent: 0x9b5e08a0: ver 3 1 (tinfo 0xa85367d0)
W/art: Verification of com.mongodb.TaggableReadPreference com.mongodb.ReadPreference.primaryPreferred(java.util.List) took 406.560ms
**I/System.out: Get the URI**
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:506)
        at org.bson.types.ObjectId.<clinit>(ObjectId.java:464)
        at com.mongodb.connection.ClusterId.<init>(ClusterId.java:47)
        at com.mongodb.connection.DefaultClusterFactory.create(DefaultClusterFactory.java:72)
        at com.mongodb.Mongo.createCluster(Mongo.java:728)
        at com.mongodb.Mongo.createCluster(Mongo.java:712)
        at com.mongodb.Mongo.createCluster(Mongo.java:687)
        at com.mongodb.Mongo.<init>(Mongo.java:295)
        at com.mongodb.MongoClient.<init>(MongoClient.java:283)
        at com.example.raji.tfsystem.excellent.raji(excellent.java:27)
        at com.example.raji.tfsystem.MainActivity$1.onClick(MainActivity.java:43)
        at android.view.View.performClick(View.java:5610)
        at android.view.View$PerformClick.run(View.java:22265)
        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:6077)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "java.lang.management.ManagementFactory" on path: DexPathList[[zip file "/data/app/com.example.raji.tfsystem-2/base.apk", zip file "/data/app/com.example.raji.tfsystem-2/split_lib_dependencies_apk.apk", zip file "/data/app/com.example.raji.tfsystem-2/split_lib_slice_0_apk.apk", zip file "/data/app/com.example.raji.tfsystem-2/split_lib_slice_1_apk.apk", zip file "/data/app/com.example.raji.tfsystem-2/split_lib_slice_2_apk.apk", zip file "/data/app/com.example.raji.tfsystem-2/split_lib_slice_3_apk.apk", zip file "/data/app/com.example.raji.tfsystem-2/split_lib_slice_4_apk.apk", zip file "/data/app/com.example.raji.tfsystem-2/split_lib_slice_5_apk.apk", zip file "/data/app/com.example.raji.tfsystem-2/split_lib_slice_6_apk.apk", zip file "/data/app/com.example.raji.tfsystem-2/split_lib_slice_7_apk.apk", zip file "/data/app/com.example.raji.tfsystem-2/split_lib_slice_8_apk.apk", zip file "/data/app/com.example.raji.tfsystem-2/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.example.raji.tfsystem-2/lib/x86, /system/lib, /vendor/lib]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at org.bson.types.ObjectId.createProcessIdentifier(ObjectId.java:506) 
        at org.bson.types.ObjectId.<clinit>(ObjectId.java:464) 
        at com.mongodb.connection.ClusterId.<init>(ClusterId.java:47) 
        at com.mongodb.connection.DefaultClusterFactory.create(DefaultClusterFactory.java:72) 
        at com.mongodb.Mongo.createCluster(Mongo.java:728) 
        at com.mongodb.Mongo.createCluster(Mongo.java:712) 
        at com.mongodb.Mongo.createCluster(Mongo.java:687) 
        at com.mongodb.Mongo.<init>(Mongo.java:295) 
        at com.mongodb.MongoClient.<init>(MongoClient.java:283) 
        at com.example.raji.tfsystem.excellent.raji(excellent.java:27) 
        at com.example.raji.tfsystem.MainActivity$1.onClick(MainActivity.java:43) 
        at android.view.View.performClick(View.java:5610) 
        at android.view.View$PerformClick.run(View.java:22265) 
        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:6077) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 
I/cluster: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}

**I/System.out: Get the client**

**I/System.out: Get the DB**

**I/cluster: Exception in monitor thread while connecting to server localhost:27017**

    com.mongodb.MongoSocketOpenException: Exception opening socket
        at com.mongodb.connection.SocketStream.open(SocketStream.java:63)
        at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115)
        at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:116)
        at java.lang.Thread.run(Thread.java:761)
     Caused by: java.net.ConnectException: Connection refused
        at java.net.PlainSocketImpl.socketConnect(Native Method)
        at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:334)
        at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:196)
        at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356)
        at java.net.Socket.connect(Socket.java:586)
        at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:50)
        at com.mongodb.connection.SocketStream.open(SocketStream.java:58)
        at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115) 
        at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:116) 
        at java.lang.Thread.run(Thread.java:761)
 
**I/System.out: Get the collection**

**I/cluster: No server chosen by WritableServerSelector from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, serverDescriptions=[ServerDescription{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused}}]}. Waiting for 30000 ms before timing out**

**D/AndroidRuntime: Shutting down VM**

**E/AndroidRuntime: FATAL EXCEPTION: main**
    Process: com.example.raji.tfsystem, PID: 22707
    com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches WritableServerSelector. Client view of cluster state is {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused}}]
        at com.mongodb.connection.BaseCluster.createTimeoutException(BaseCluster.java:375)
        at com.mongodb.connection.BaseCluster.selectServer(BaseCluster.java:104)
        at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:75)
        at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:71)
        at com.mongodb.binding.ClusterBinding.getWriteConnectionSource(ClusterBinding.java:68)
        at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:221)
        at com.mongodb.operation.MixedBulkWriteOperation.execute(MixedBulkWriteOperation.java:169)
        at com.mongodb.operation.MixedBulkWriteOperation.execute(MixedBulkWriteOperation.java:75)
        at com.mongodb.Mongo.execute(Mongo.java:827)
        at com.mongodb.Mongo$2.execute(Mongo.java:810)
        at com.mongodb.MongoCollectionImpl.executeSingleWriteRequest(MongoCollectionImpl.java:515)
        at com.mongodb.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:306)
        at com.mongodb.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:297)
        at com.example.raji.tfsystem.excellent.raji(excellent.java:39)
        at com.example.raji.tfsystem.MainActivity$1.onClick(MainActivity.java:43)
        at android.view.View.performClick(View.java:5610)
        at android.view.View$PerformClick.run(View.java:22265)
        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:6077)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)

**Application terminated.**

0 个答案:

没有答案