连接Android与MongoDB时由于超时连接失败

时间:2018-05-30 07:48:33

标签: android mongodb android-studio

我正在尝试将我的Android应用程序连接到MongoDB并向其插入值。应用程序因提示以下错误而崩溃:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.preyanshu.mongodblogin/com.example.preyanshu.mongodblogin.MainActivity}: com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting to connect. Client view of cluster state is {type=UNKNOWN, servers=[{address=10.100.17.139:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.SocketTimeoutException: failed to connect to /10.100.17.139 (port 27017) after 20000ms}}]

这是我用来直接连接到数据库的代码:

public class MainActivity extends AppCompatActivity {
Button login, ViewBtn;
EditText u_name, pwd;
TextView showView;
    @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);
        }
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        showView = (TextView)findViewById(R.id.showView);
        ViewBtn = (Button)findViewById(R.id.login);
        u_name = (EditText)findViewById(R.id.userName);
        pwd = (EditText)findViewById(R.id.password);
        login = (Button)findViewById(R.id.login);

        MongoClient mongoClient = new MongoClient("10.100.17.139",27017);

        MongoCredential credential;
        credential = MongoCredential.createCredential("sampleUser", "LoginSample", "password".toCharArray());

        MongoDatabase dbs = (MongoDatabase) mongoClient.getDatabase("LoginSample");

        MongoCollection<Document> coll = dbs.getCollection("LoginData");

        Document docs = new Document("name","Test").append("password","Test");

        coll.insertOne(docs);

    }
}

仅当我尝试插入文档时才会提示错误。当我评论该行 -

coll.insertOne(docs);

应用程序运行得非常好。

如果我得到一个解决方案,这将是一个很大的帮助。

1 个答案:

答案 0 :(得分:0)

错误明确指出无法找到/连接数据库。这不是代码错误,如果您正在阅读而不是插入,仍会出现相同的错误。它是您的andriod应用程序,您是否尝试通过手机连接?还是通过开发系统?如果它通过系统,然后尝试通过mongo客户端甚至mongo指南针连接到Mongo。很确定这也会失败。只是网络问题,要么机器不可用,要么安全组没有暴露端口。你的开发人员将是解决问题的最佳人选: - 祝你好运!

编辑,快速查看您的代码并且您的网址格式看起来不对,现在我觉得输入所有网络hullalala很傻

<main>
    <div class="square">
        <p>catch me!</p>
    </div>
</main>

IT不遵循URL模式,正确的模式将是:

 MongoClient mongoClient = new MongoClient("10.100.17.139",27017);

或者您需要将其包装为新服务器!