We tried the quick start code and the tutorial given for android to setup sync between mongo and realm. The following code is used. We have setup backend and also the gradle dependencies.
public class TaskActivity extends AppCompatActivity {
Realm realm;
App rApp;
Credentials credentials;
int i=0;
private MongoClient mongoClient;
private MongoCollection<Document> mongoCollection;
private User user;
private String TAG = "EXAMPLE";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task);
credentials = Credentials.anonymous();
realm = Realm.getDefaultInstance();
TextView txt = findViewById(R.id.txt);
String appID = "task-tracker-tutorial-xomxk"; // replace this with your App ID
rApp = new App(new AppConfiguration.Builder(appID)
.build());
rApp.loginAsync(credentials, it -> {
if (it.isSuccess()) {
user = rApp.currentUser();
assert user != null;
mongoClient = user.getMongoClient("mongodb-atlas");
if (mongoClient != null) {
mongoCollection = mongoClient.getDatabase("tracker").getCollection("tasks");
Toast.makeText(getApplicationContext(), "Successfully authenticated anonymous.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Error connecting to the MongoDB instance.", Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(getApplicationContext(),"Error in login",Toast.LENGTH_SHORT).show();
}
});
Button btn = findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// all realm writes need to occur inside of a transaction
rApp.loginAsync(credentials, it -> {
if (it.isSuccess()) {
user = rApp.currentUser();
Toast.makeText(getApplicationContext(),"Data sent"+(Math.random()*20),Toast.LENGTH_SHORT).show();
String partitionValue = "myPartition";
SyncConfiguration config = new SyncConfiguration.Builder(user, partitionValue)
.build();
realm = Realm.getInstance(config);
Task task = new Task("New Task: "+(Math.random()*20), partitionValue);
realm.executeTransaction( transactionRealm -> {
transactionRealm.insert(task);
});
}
else {
Toast.makeText(getApplicationContext(),"Not working",Toast.LENGTH_SHORT).show();
}
});
realm.close();
}
});
}