Skip to content
Advertisement

Retrieve subcollection data from Firestore in Android

I keep failed to retrieve the data from subcollection “Diary” when trying on click on a RecyclerView. What I want is when I on click on a RecyclerView, it will display that data stored in the “Diary”. What’s the problem with my codes?

RecyclerView Java codes:

private void setUpRecyclerView() {
    fStore = FirebaseFirestore.getInstance();
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    Query query = fStore.collection("Users").document(user.getUid()).collection("Diary").orderBy("Date", Query.Direction.ASCENDING);

    FirestoreRecyclerOptions<ModelClass> options = new FirestoreRecyclerOptions.Builder<ModelClass>()
            .setQuery(query, ModelClass.class)
            .build();

    adapters = new CustomAdapter(options,this);

    adapters.startListening();
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.setAdapter(adapters);

    new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,
            ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
        @Override
        public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
            return false;
        }

        @Override
        public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
            adapters.deleteItem(viewHolder.getAdapterPosition());
        }
    }).attachToRecyclerView(recyclerView);


}

@Override
public void onItemClick(final DocumentSnapshot snapshot, int position) {
    final ModelClass diary = snapshot.toObject(ModelClass.class);
    String id = snapshot.getId();
   startActivity(new Intent(diary_user.this,onClickRecyclerViewDiary_user.class));
    Toast.makeText(diary_user.this,"Position: " + position + "ID: " + id,Toast.LENGTH_SHORT).show();

}

Stored data Java codes:

check.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FirebaseUser user = fAuth.getCurrentUser();
            String uid = user.getUid();
            String id = fStore.collection("Users").document(user.getUid()).collection("Diary").document().getId();
            DocumentReference df = fStore.collection("Users").document(user.getUid()).collection("Diary").document(id);
            Map<String, Object> diaryInfo = new HashMap<>();
            diaryInfo.put("Symptom", symptom.getEditText().getText().toString());
            diaryInfo.put("Note", note.getEditText().getText().toString());
            diaryInfo.put("Date", dateButton.getText().toString());
            diaryInfo.put("ID",id);

            SimpleDateFormat tf = new SimpleDateFormat("hh:mm a");
            String currentTime = tf.format(Calendar.getInstance().getTime());
            time.setText(currentTime);
            diaryInfo.put("Time", time.getText().toString());

            feeling = spinner.getSelectedItem().toString();
            diaryInfo.put("Feeling", feeling);

            df.set(diaryInfo).addOnSuccessListener(new OnSuccessListener() {
                @Override
                public void onSuccess(Object o) {
                    Toast.makeText(add_diary_user.this, "Data successfully stored", Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(add_diary_user.this, diary_user.class));
                    finish();
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Toast.makeText(add_diary_user.this, e.toString(), Toast.LENGTH_SHORT).show();
                }
            });

        }
    });

Retrieve data Java codes:

private void getDiary() {
    fStore = FirebaseFirestore.getInstance();
    FirebaseUser user = fAuth.getCurrentUser();
    String id = fStore.collection("Users").document(user.getUid()).collection("Diary").document().getId();
    fStore.collection("Users").document(user.getUid()).collection("Diary");
            diary.whereEqualTo("ID", id)
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        for (DocumentSnapshot document : task.getResult()) {
                            // Do something with your retrieved documents
                            dateButton.setText((CharSequence) document.getString("Date"));
                            note.getEditText().setText((CharSequence) document.getString("Note"));
                            symptom.getEditText().setText((CharSequence) document.getString("Symptom"));
                        }
                    }
                }
            });
}

Database structure:

enter image description here

enter image description here

Output:

enter image description here

enter image description here

Advertisement

Answer

I believe the problem in your code is in this line:

String id = fStore.collection("Users").document(user.getUid()).collection("Diary").document().getId();

Where you are using .document().getId(); but without specifying which document you want, which makes id not have the expected value and because of that you don’t get any results in the comparison that uses that value later in your execution. To fix that you would need to have this Id stored somewhere and pass it as a parameter to your getDiary() function, or something similar to that.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement