Skip to content

tjoshi03/FireStoreDemo

Repository files navigation

FireStoreDemo

Demo for the android developer to add firestore database to there app.

1.Follow the instructions to add Firebase to your Android app.

2.Add the Cloud Firestore Android library to your app/build.gradle file:

compile 'com.google.firebase:firebase-firestore:11.4.2'

Initialize an instance of Cloud Firestore:

// Access a Cloud Firestore instance from your Activity

FirebaseFirestore db = FirebaseFirestore.getInstance();

// Create a new user with a first and last name Map<String, Object> user = new HashMap<>(); user.put("first", "Ada"); user.put("last", "Lovelace"); user.put("born", 1815);

// Add a new document with a generated ID db.collection("users") .add(user) .addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(DocumentReference documentReference) { Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId()); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.w(TAG, "Error adding document", e); } });

    Now add another document to the users collection. Notice that this document includes a key-value pair (middle name) that does not appear in the first document.
    Documents in a collection can contain different sets of information.
    
    // Create a new user with a first, middle, and last name

Map<String, Object> user = new HashMap<>(); user.put("first", "Alan"); user.put("middle", "Mathison"); user.put("last", "Turring"); user.put("born", 1912);

// Add a new document with a generated ID db.collection("users") .add(user) .addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(DocumentReference documentReference) { Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId()); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.w(TAG, "Error adding document", e); } });

    Read data

To quickly verify that you've added data to Cloud Firestore, use the data viewer in the Firebase console.

You can also use the "get" method to retrieve the entire collection. db.collection("users") .get() .addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { if (task.isSuccessful()) { for (DocumentSnapshot document : task.getResult()) { Log.d(TAG, document.getId() + " => " + document.getData()); } } else { Log.w(TAG, "Error getting documents.", task.getException()); } } });