Nagendra555 Nagendra555 - 1 month ago 8
Android Question

Android cannot connect to MongoDB even with AsyncTask

public class StartNewActivity extends Activity{

public static final String TEST_SKETCH_APP = "testSketchApp";
public static final String SKETCH_COLLECTION = "sketchCollection";
private EditText editText;
private EditText editText2;
private EditText editText3;
private EditText editText4;

private String name;
private String password;
private String email;
private String phoneNumber;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
editText = (EditText) findViewById(R.id.editText);
editText2 = (EditText) findViewById(R.id.editText2);
editText3 = (EditText) findViewById(R.id.editText3);
editText4 = (EditText) findViewById(R.id.editText4);

}

@Override
public void onBackPressed() {
Intent mainActivityIntent = new Intent(StartNewActivity.this, MainActivity.class);
startActivity(mainActivityIntent);
super.onBackPressed();

}

public void onSubmitButton(View view){

name = editText.getText().toString();
password = editText2.getText().toString();
email = editText3.getText().toString();
phoneNumber = editText4.getText().toString();


// Gets the URL from the UI's text field.
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new MakeDataBaseConnection().execute(name, password, email, phoneNumber);
} else {
final Toast toast = Toast.makeText(getApplicationContext(), "No Network available", Toast.LENGTH_SHORT);
toast.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
toast.cancel();
}
}, 500);
}

}



private class MakeDataBaseConnection extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {

// params comes from the execute() call: params[0] is the url.
return saveValues(urls);
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
final Toast toast = Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT);
toast.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
toast.cancel();
}
}, 500);
}
}

private String saveValues(String[] url) {

try {

MongoClientURI uri = new MongoClientURI("mongodb://localhost:27017");

MongoClient instance = MongoDatabaseConnection.getInstance(uri);
DB db = instance.getDB(TEST_SKETCH_APP);
DBCollection collection = db.getCollection(SKETCH_COLLECTION);

BasicDBObject dbObject = new BasicDBObject();

dbObject.put("name", url[0]);
dbObject.put("password", url[1]);
dbObject.put("email", url[2]);
dbObject.put("phoneNumber", url[3]);

collection.insert(dbObject);

return "Values Saved";
}catch (Exception e){
return "Not Saved, "+e.getMessage();
}

}
}


I am trying to save values in MongoDB Database, my database is definitely running in background. But when I try to insert the Document object it throws an exception as:

com.mongodb.MongoTimeoutException: Timed out after 10000 ms while waiting for a server that matches AnyServerSelector{}. Client view of
cluster state is {type=Unknown, servers=[{address=localhost:27017, type=Unknown, state=Connecting, exception={com.mongodb.MongoException$Network: Exception opening the socket}, caused by {java.net.ConnectException: failed
to connect to localhost/127.0.0.1 (port 27017) after 20000ms: isConnected failed: ECONNREFUSED (Connection refused)}, caused by {android.system.ErrnoException: isConnected failed: ECONNREFUSED (Connection refused)}}]


I am using the WorkerThread for saving operations as suggested, and using an AsyncTask too for database operation, but the database socket is not getting opened.
Can you please let me know what am i missing ? Or show an example to how should I connect to database through network.

Answer

I don't think MongoDB is running on your android device, the connection to localhost will time out because there is no MongoDB Server running on 127.0.0.1.