Android中的MongoDB mlab连接

时间:2018-04-21 07:31:16

标签: android mongodb android-studio android-asynctask mlab

我是android的新手。创建一个新的应用程序来连接Android应用程序与MongoDB(mlab.com)。我已成功连接Java。但在android中,我没有得到如何做到这一点。我已经检查过没有AsyncTask但也得到了相同的错误任何人都可以帮忙!

这是我的代码

import com.mongodb.MongoClient;
import com.mongodb.MongoClientException;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private ProgressDialog pDialog;

    EditText et1,et2,et3;
    Button b1;
    MongoClientURI uri = new MongoClientURI("mongodb://user:malak@ds149309.mlab.com:49309/mydb");

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

    et1=(EditText) findViewById(R.id.nameText);
    et2 = (EditText) findViewById(R.id.emailText);
    et3 =(EditText) findViewById(R.id.mobText);
    b1=(Button) findViewById(R.id.button);

    b1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String name = et1.getText().toString();
            String email = et2.getText().toString();
            String mob = et3.getText().toString();
            InsertData(name,email);
        }
    });
}
public void InsertData(final String name, final String email) {

    class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            try {
                MongoClient mongoClient = new MongoClient(uri);
                Toast.makeText(getApplicationContext(),"Coonected",Toast.LENGTH_LONG).show();
                MongoDatabase database = mongoClient.getDatabase("aghori");
                Toast.makeText(getApplicationContext(),"Dtabase connected",Toast.LENGTH_LONG).show();
                MongoCollection<Document> collection = database.getCollection("sampleCollection");


                // collection.insertOne(document);


            } catch (MongoClientException e) {

            }
            return "Data Inserted Successfully";
        }

        @RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
        @Override
        protected void onPostExecute(String result) {

            super.onPostExecute(result);

            Toast.makeText(MainActivity.this, "Data Submit Successfully", Toast.LENGTH_LONG).show();

        }
    }

    SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();

    sendPostReqAsyncTask.execute(name, email);
}

}

当我运行此应用程序并单击按钮提交时,它会自动停止。 Hvae任何人都有任何想法请帮助。

0 个答案:

没有答案