Advertisements

FS DB Reading custom object

//Getting instance
FirebaseFirestore db = FirebaseFirestore.getInstance();


//Getting Reference to "new doc" document
//You can get the path in this way too, lot easier!
final DocumentReference documentReference = db.collection("users").document("new doc");


//Calling the get() method with a callback function
documentReference.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        //Checking request result
        if (task.isSuccessful()) {
            //Request was successful but it never means that data is found
            DocumentSnapshot data = task.getResult();
            if (data.exists()) {
                //document named "new doc" found

                //We know in which format we have writen data to that document, so we will get it in same manner
                //We used map to store that value, now we will get that
                User user = data.toObject(User.class);

               String userName = user.getUserName();
               String lastName = user.getLastName();

                Toast.makeText(MainActivity.this, "username: " + userName, Toast.LENGTH_SHORT).show();


            } else {
                //document with name "new doc" not found at the path specified.
            }

        } else {
            //Request was not successful
            //Could be some rules or internet problem
            Log.i(TAG, "onComplete: Request unsuccessful, error: " + task.getException().getLocalizedMessage());
        }
    }
});