Reputation: 123
Im making an android app to fetch data from user and store it in a mongodb database
mongodb runs on localhost:27017 and im able to connect to it using 10.0.3.2:27017 on genymotion emulator
here is LoginActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.json.JSONException;
import org.json.JSONObject;
public class LoginActivity extends AppCompatActivity {
static DB db;
static DBCollection locations;
public String name,middlename,surname,userid,profilelink,imageUrl,emailid,gender,birthday;
private CallbackManager callbackManager;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker profileTracker;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_login);
callbackManager = CallbackManager.Factory.create();
accessTokenTracker = new AccessTokenTracker() {
@Override
protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
}
};
profileTracker = new ProfileTracker() {
@Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
nextActivity(newProfile);
}
};
accessTokenTracker.startTracking();
profileTracker.startTracking();
LoginButton loginButton = (LoginButton)findViewById(R.id.login_button);
FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
Profile profile = Profile.getCurrentProfile();
nextActivity(profile);
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.v("JSON",response.toString());
try {
emailid=object.getString("email");
gender=object.getString("gender");
birthday=object.getString("birthday");
TextView nameView6 = (TextView)findViewById(R.id.emailr);
nameView6.setText(emailid);
TextView nameView7 = (TextView)findViewById(R.id.genderr);
nameView7.setText(gender);
TextView nameView8 = (TextView)findViewById(R.id.birthdayr);
nameView8.setText(birthday);
String[] dset={emailid,gender,birthday};
yalla(dset);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "email,gender,birthday");
request.setParameters(parameters);
request.executeAsync();
}
@Override
public void onCancel() {
}
@Override
public void onError(FacebookException e) {
}
};
loginButton.setReadPermissions("user_friends");
loginButton.setReadPermissions("public_profile");
loginButton.setReadPermissions("email");
loginButton.setReadPermissions("user_birthday");
loginButton.registerCallback(callbackManager, callback);
}
@Override
protected void onResume() {
super.onResume();
//Facebook login
Profile profile = Profile.getCurrentProfile();
nextActivity(profile);
}
@Override
protected void onPause() {
super.onPause();
}
protected void onStop() {
super.onStop();
accessTokenTracker.stopTracking();
profileTracker.stopTracking();
}
@Override
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
super.onActivityResult(requestCode, responseCode, intent);
callbackManager.onActivityResult(requestCode, responseCode, intent);
}
private void nextActivity(Profile profile){
if(profile != null){
Intent main = new Intent(LoginActivity.this, MainActivity.class);
main.putExtra("name", profile.getFirstName());
main.putExtra("middlename", profile.getMiddleName());
main.putExtra("surname", profile.getLastName());
main.putExtra("userid", profile.getId());
main.putExtra("profilelink", profile.getLinkUri());
main.putExtra("imageUrl", profile.getProfilePictureUri(200,200).toString());
startActivity(main);
}
}
public static void yalla(String[] args){
String[] dset;
dset=args;
//try {
String uri = "mongodb://10.0.3.2:27017";
Log.v("enterhere", dset[0]);
MongoClientURI mongoClientURI=new MongoClientURI(uri);
//MongoClient mongoClient = new MongoClient("mongodb://10.0.3.2:27017/test");
Log.v("connectedserver", dset[0]);
MongoClient mongoClient = new MongoClient(mongoClientURI);
MongoDatabase database = mongoClient.getDatabase("users");
Log.v("Connect to database successfully",database.getName());
MongoCollection mongoCollection = database.getCollection("assest");
Log.v("collection", dset[0]);
Document doc = new Document("emailid", dset[0])
.append("gender", dset[1])
.append("birthday", dset[2]);
Log.v("document update", dset[0]);
mongoCollection.insertOne(doc);
Log.v("doc insertion", dset[0]);
mongoClient.close();
//} catch (MongoException e)
//{
// e.getStackTrace();
//}
}
}
Error on android studio
V/document update: [email protected]
I/cluster: No server chosen by PrimaryServerSelector from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, all=[ServerDescription{address=10.0.3.2:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out
I/connection: Opened connection [connectionId{localValue:1, serverValue:17}] to 10.0.3.2:27017
I/cluster: Monitor thread successfully connected to server with description ServerDescription{address=10.0.3.2:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 0, 14]}, minWireVersion=0, maxWireVersion=3, electionId=null, maxDocumentSize=16777216, roundTripTimeNanos=9233253}
D/dalvikvm: GC_CONCURRENT freed 413K, 5% free 12382K/12935K, paused 11ms+1ms, total 17ms
I/connection: Closed connection [connectionId{localValue:2}] to 10.0.3.2:27017 because the underlying connection was closed.
D/AndroidRuntime: Shutting down VM
W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa62fe288)
E/AndroidRuntime: FATAL EXCEPTION: main
com.mongodb.MongoException: android.os.NetworkOnMainThreadException
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:125)
at com.mongodb.connection.UsageTrackingInternalConnection.open(UsageTrackingInternalConnection.java:46)
at com.mongodb.connection.DefaultConnectionPool$PooledConnection.open(DefaultConnectionPool.java:366)
at com.mongodb.connection.DefaultConnectionPool.get(DefaultConnectionPool.java:94)
at com.mongodb.connection.DefaultConnectionPool.get(DefaultConnectionPool.java:80)
at com.mongodb.connection.DefaultServer.getConnection(DefaultServer.java:69)
at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.getConnection(ClusterBinding.java:86)
at com.mongodb.operation.OperationHelper.withConnectionSource(OperationHelper.java:184)
at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:177)
at com.mongodb.operation.MixedBulkWriteOperation.execute(MixedBulkWriteOperation.java:141)
at com.mongodb.operation.MixedBulkWriteOperation.execute(MixedBulkWriteOperation.java:72)
at com.mongodb.Mongo.execute(Mongo.java:747)
at com.mongodb.Mongo$2.execute(Mongo.java:730)
at com.mongodb.MongoCollectionImpl.executeSingleWriteRequest(MongoCollectionImpl.java:482)
at com.mongodb.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:277)
at com.sujithsizon.lzlogin3.LoginActivity.yalla(LoginActivity.java:224)
at com.sujithsizon.lzlogin3.LoginActivity$3$1.onCompleted(LoginActivity.java:99)
at com.facebook.GraphRequest$1.onCompleted(GraphRequest.java:304)
at com.facebook.GraphRequest$5.run(GraphRequest.java:1368)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
at libcore.io.IoBridge.connectErrno(IoBridge.java:144)
at libcore.io.IoBridge.connect(IoBridge.java:112)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
at java.net.Socket.connect(Socket.java:842)
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:114)
at com.mongodb.connection.UsageTrackingInternalConnection.open(UsageTrackingInternalConnection.java:46)
at com.mongodb.connection.DefaultConnectionPool$PooledConnection.open(DefaultConnectionPool.java:366)
at com.mongodb.connection.DefaultConnectionPool.get(DefaultConnectionPool.java:94)
at com.mongodb.connection.DefaultConnectionPool.get(DefaultConnectionPool.java:80)
at com.mongodb.connection.DefaultServer.getConnection(DefaultServer.java:69)
at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.getConnection(ClusterBinding.java:86)
at com.mongodb.operation.OperationHelper.withConnectionSource(OperationHelper.java:184)
at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:177)
at com.mongodb.operation.MixedBulkWriteOperation.execute(MixedBulkWriteOperation.java:141)
at com.mongodb.operation.MixedBulkWriteOperation.execute(MixedBulkWriteOperation.java:72)
at com.mongodb.Mongo.execute(Mongo.java:747)
at com.mongodb.Mongo$2.execute(Mongo.java:730)
at com.mongodb.MongoCollectionImpl.executeSingleWriteRequest(MongoCollectionImpl.java:482)
at com.mongodb.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:277)
at com.sujithsizon.lzlogin3.LoginActivity.yalla(LoginActivity.java:224)
at com.sujithsizon.lzlogin3.LoginActivity$3$1.onCompleted(LoginActivity.java:99)
at com.facebook.GraphRequest$1.onCompleted(GraphRequest.java:304)
at com.facebook.GraphRequest$5.run(GraphRequest.java:1368)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
Upvotes: 0
Views: 601
Reputation: 43
I am actually trying to do the same and found mongoclient won't work so I used the common class to connect to my server on mlab then I used an asynkTask inner class with HTTPUrlConnection to get the data I stored, check out this link for querying urls for mlab-> http://docs.mlab.com/data-api/ Also check this out-> https://m.youtube.com/watch?v=RSZ2pyhfR0I
public class Common {
private static String DB_NAME = "edmtdev";
private static String COLLECTION_NAME = "user";
public static String API_KEY = "YOUR API KEY";
public static String getAddressSingle(User user) {
String baseUrl = String.format("https://api.mlab.com/api/1/databases/%s/collections/%s", DB_NAME, COLLECTION_NAME);
StringBuilder stringBuilder = new StringBuilder(baseUrl);
stringBuilder.append("/"+user.get_id().getOid()+"?apiKey="+API_KEY);
return stringBuilder.toString():
}
Upvotes: 0
Reputation: 5557
You can use Async Task for this. I don't know much about mongoDB, but assuming your yalla
method has heavy network operation which includes mongoDB.
Try to add yalla
method into new AyancTask.
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
//Include your mongoDB accessing method here, in background thread.
}
}
And you can execute this method by the following line from your activity.
new DownloadFilesTask().execute(url1, url2, url3);
Hope this helps.
EDIT: Now you are including your method in AsyncTask, and passing URL
as arguments, Just provide the links via execute()
method. No need to use this String[] = args
, which currently you are using in your methos.
For more details on AsyncTask, refer the official docs from this link :)
Upvotes: 2