Skip to content

Instantly share code, notes, and snippets.

@hennasingh
Created May 23, 2022 20:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hennasingh/e4fd3f25aca7b1315681e3b850c15cbe to your computer and use it in GitHub Desktop.
Save hennasingh/e4fd3f25aca7b1315681e3b850c15cbe to your computer and use it in GitHub Desktop.
public class AirbnbActivity extends AppCompatActivity {
String appID = "Your APP ID";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_airbnb);
Realm.init(this);
App app = new App(new AppConfiguration.Builder(appID).build());
app.loginAsync(Credentials.anonymous(), result -> {
if (result.isSuccess()) {
Log.v("QUICKSTART", "Successfully authenticated anonymously.");
User user = app.currentUser();
MongoClient mongoClient =
user.getMongoClient("mongodb-atlas"); // service for MongoDB Atlas cluster containing custom user data
MongoDatabase mongoDatabase =
mongoClient.getDatabase("sample_airbnb");
MongoCollection<Document> mongoCollection =
mongoDatabase.getCollection("listingsAndReviews");
Log.v("EXAMPLE", "Successfully instantiated the MongoDB collection handle");
Document queryFilter = new Document("price", 80.00);
//Read a Single Document
mongoCollection.findOne(queryFilter).getAsync(task -> {
if (task.isSuccess()) {
Document resultBack = task.get();
// Log.d("EXAMPLE","Count found is " + resultBack.size());
Log.d("EXAMPLE", "successfully found a document: " + resultBack);
} else {
Log.e("EXAMPLE", "failed to find document with: ", task.getError());
}
});
// Read Multiple Documents
Document readMultiple = new Document("property_type", "House");
RealmResultTask<MongoCursor<Document>> findTask = mongoCollection.find(readMultiple).iterator();
findTask.getAsync(task -> {
if (task.isSuccess()) {
MongoCursor<Document> results = task.get();
Log.v("EXAMPLE", "successfully found all properties of type House:");
while (results.hasNext()) {
Log.d("EXAMPLE", results.next().toString());
}
} else {
Log.e("EXAMPLE", "failed to find documents with: ", task.getError());
}
});
//Update Query
Document updateFilter = new Document("name", "Ribeira Charming Duplex");
Document updateDocument = new Document("$set", new Document("bedrooms", 4));
mongoCollection.updateOne(updateFilter, updateDocument).getAsync(task -> {
if (task.isSuccess()) {
long count = task.get().getModifiedCount();
if (count == 1) {
Log.v("EXAMPLE", "successfully updated a document.");
} else {
Log.v("EXAMPLE", "did not update a document.");
}
} else {
Log.e("EXAMPLE", "failed to update document with: ", task.getError());
}
});
} else{
Log.e("QUICKSTART", "Failed to log in. Error: " + result.getError());
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment