I want to delete my document from firebase. But first I need to determine the document id. I tried to get document id:
docId = queryDocumentSnapshots.getDocuments().get(pos).getId();
Then, I just wanted to delete my document. But firebase works async so code doesnt work in 'if' statement. When we first click the button, docId variable is null or it takes the docId which was clicked before till the async code part done.
#Override
public void onBindViewHolder(#NonNull AdvertisementHolder holder, int position) {
imgUrl = publishedAdvertisements.get(position).getImgUrl();
holder.petName.setText(publishedAdvertisements.get(position).getPetName());
holder.petCategory.setText(publishedAdvertisements.get(position).getPetCategory());
Picasso.get().load(publishedAdvertisements.get(position).getImgUrl()).into(holder.petImage);
holder.btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
firebaseFirestore = FirebaseFirestore.getInstance();
firebaseFirestore.collection("Pets").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(#NonNull QuerySnapshot queryDocumentSnapshots) {
if (!queryDocumentSnapshots.isEmpty()) {
System.out.println("bos döndü");
docId = queryDocumentSnapshots.getDocuments().get(pos).getId();
}
}
});
System.out.println(docId);
if (docId != null) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("Pets").document(docId)
.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully deleted!");
publishedAdvertisements.clear();
getPublishedAnimals();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error deleting document", e);
}
});
}
notifyDataSetChanged();
}
});
You should structure your code so that any logic that depends on your asynchronous operation is executed or triggered within the response callback.
You can do something like this:
#Override
public void onBindViewHolder(#NonNull AdvertisementHolder holder, int position) {
imgUrl = publishedAdvertisements.get(position).getImgUrl();
holder.petName.setText(publishedAdvertisements.get(position).getPetName());
holder.petCategory.setText(publishedAdvertisements.get(position).getPetCategory());
Picasso.get().load(publishedAdvertisements.get(position).getImgUrl()).into(holder.petImage);
holder.btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
firebaseFirestore = FirebaseFirestore.getInstance();
firebaseFirestore.collection("Pets").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(#NonNull QuerySnapshot queryDocumentSnapshots) {
// The asynchronous operation has successfully completed
// and returned a value to our 'onSuccess()' callback.
if (!queryDocumentSnapshots.isEmpty()) {
System.out.println("bos döndü");
docId = queryDocumentSnapshots.getDocuments().get(pos).getId();
System.out.println(docId);
// We can now use the value of docId.
if (docId != null) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("Pets").document(docId)
.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully deleted!");
publishedAdvertisements.clear();
getPublishedAnimals();
// (1)
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error deleting document", e);
}
});
}
// I'm not sure how your RecyclerView is set up
// but I'm guessing you might want to move this call
// to 'notifyDataSetChanged()' to the section marked (1)
notifyDataSetChanged();
}
}
});
}
});
}
Related
How to check Firebase data success write data in database (handle error)?
because I want to set massage Toast if data write success show massage
reg_money.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAuth = FirebaseAuth.getInstance();
FirebaseUser userfirebase = mAuth.getInstance().getCurrentUser();
mDatabase = FirebaseDatabase.getInstance();
mDbRef = mDatabase.getReference("Student/information");
String email = userfirebase.getEmail();
Uaser_register_money user = new Uaser_register_money(namesemster, email.substring(0,11), count2);
mDbRef.child("Student/information").setValue(user);
}
});
Just Add Listeners
mDbRef.child("Student/information").setValue(user)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
// Write was successful!
// ...
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// Write failed
// ...
}
});
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:
Output:
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.
In my app, the homepage activity holds a sectioned recyclerview, in which the value is initiated by querying Firebase. The data retrieval and the recyclerview was working well at first.
Then, I tried to implement addsnapshotlistener to automatically update my activity without needing the user to refresh the page independently.
However, when I run my code, the recyclerview repeated the same sectioned recyclerview twice.
Here is the code for my activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.homepage);
mAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
///storageRef = FirebaseStorage.getInstance().getReference();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
UserId = FirebaseAuth.getInstance().getCurrentUser().getUid();
MainRecyclerView = findViewById(R.id.MainContainer);
SignoutButton = findViewById(R.id.SignOutbutton);
checkUserType();
SignoutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseAuth.getInstance().signOut();
///mAuth.GoogleSignInApi.signOut(apiClient);
Intent i = new Intent(HomePage.this, Login.class);
startActivity(i);
}
});
///queries data from firebase
initData();
BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNavigationView);
bottomNavigationView.setSelectedItemId(R.id.appointment);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.search:
startActivity(new Intent(getApplicationContext(),Search.class));
overridePendingTransition(0,0);
return true;
case R.id.appointment:
return true;
case R.id.profile:
startActivity(new Intent(getApplicationContext(),Profile.class));
overridePendingTransition(0,0);
return true;
}
return false;
}
});
UpdateToken();
}
#Override
protected void onStart() {
super.onStart();
sectionList.clear();
apnmntList.clear();
CollectionReference colref = db.collection("appointmentsColl").document(UserId)
.collection("Date");
///check for updates inside of the collections
HPListener= colref.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value, #Nullable FirebaseFirestoreException error) {
for (QueryDocumentSnapshot document : value) {
///query all the values again
db.collection("appointmentsColl").document(UserId)
.collection("Date").document(document.getId())
.collection("appointmentsID")
.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
apnmntList = new ArrayList();
for (DocumentSnapshot querysnapshot: task.getResult()){
apnmtDetails details = new apnmtDetails(
querysnapshot.getString("customer name"),
querysnapshot.getString("barberID"),
querysnapshot.getString("shop name"),
querysnapshot.getString("name"),
querysnapshot.getString("type"),
querysnapshot.getString("status"),
querysnapshot.getString("price"),
querysnapshot.getString("time slot"));
apnmntList.add(details);
section = new Section(document.getString("date"),apnmntList);
}
///notify recyclerview
sectionList.add(section);
mainRecyclerAdapter.notifyDataSetChanged();
}
});
}
}
});
}
#Override
protected void onStop() {
super.onStop();
HPListener.remove();
}
private void checkUserType() {
DocumentReference docRef = db.collection("Users").document(UserId);
docRef.addSnapshotListener(new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot value, #Nullable FirebaseFirestoreException error) {
if (value.exists()) {
userType = "Users";
} else {
userType = "Barbers";
}
}
});
}
private void initData(){
db.collection("appointmentsColl").document(UserId)
.collection("Date")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
///getting the list of appointments and their details
db.collection("appointmentsColl").document(UserId)
.collection("Date").document(document.getId())
.collection("appointmentsID")
.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
apnmntList = new ArrayList();
for (DocumentSnapshot querysnapshot: task.getResult()){
apnmtDetails details = new apnmtDetails(
querysnapshot.getString("customer name"),
querysnapshot.getString("barberID"),
querysnapshot.getString("shop name"),
querysnapshot.getString("name"),
querysnapshot.getString("type"),
querysnapshot.getString("status"),
querysnapshot.getString("price"),
querysnapshot.getString("time slot"));
///adding appointmnets into an arraylist
apnmntList.add(details);
///saving the value of the section title and the appointments arraylist inside one object
section = new Section(document.getString("date"),apnmntList);
}
////initializing a new array list with the section's objects
sectionList.add(section);
///initializes the main recyclerview
LinearLayoutManager manager = new LinearLayoutManager(HomePage.this);
manager.setReverseLayout(true);
manager.setStackFromEnd(true);
MainRecyclerView.setLayoutManager(manager);
MainRecyclerView.setAdapter(mainRecyclerAdapter);
}
});
}
}else{
Toast.makeText(HomePage.this,"failed",Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.i("Check", e.toString() );
}
});
}
private void UpdateToken() {
FirebaseUser firebaseUser= FirebaseAuth.getInstance().getCurrentUser();
String refreshToken= FirebaseInstanceId.getInstance().getToken();
Token token= new Token(refreshToken);
FirebaseDatabase.getInstance().getReference("Tokens").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(token);
}
Here is what my output looks like before and after implementing addsnapshotlistener:
Before
After
I tinkered with the addsnapshotlistener for a while because I was not sure whether it is the cause for the problem, so I tried to replace the method inside the addsnapshotlistener with:
finish();
startActivity(getIntent()
I thought this would work, but when I tried to run my code, the homepage started to refresh itself endlessly without stopping.
I tried to search for people with the same problem as my own, but the posts that I find stated that their addsnapshotlistener triggers correctly but return twice the instance of the data.
The method triggers itself when I open my activity, and it triggers itself even if there are no updates in Firebase.
I would appreciate it if anyone can help me with this problem or maybe guide me to any link or post that can help solve my problem.
You mention that your data retrieval was working well at first. Have you changed anything recently?
From reading your code, I cannot see where you are handling any errors you might encounter. A listener may fail due to a security setting change or an invalid query.
It would help if you implemented an error callback to help you better understand what has happened. For example, you can capture the error message as e and output the error.
if (e != null) {
System.err.println("Listen failed: " + e);
return;
}
Documentation:
db.collection("cities")
.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot snapshots,
#Nullable FirestoreException e) {
if (e != null) {
System.err.println("Listen failed: " + e);
return;
}
for (DocumentChange dc : snapshots.getDocumentChanges()) {
if (dc.getType() == Type.ADDED) {
System.out.println("New city: " + dc.getDocument().getData());
}
}
}
});
I am trying to read the data that i have in my cloud firestore and to put it in an array called "urlList". The arrayList is in the onComplete and if i log the array there, it works(it's filled with the data it's suppose to have). Whenever i log the arrayList outside the onComplete, the array is empty. The problem seems to be with the onCompletelistener but i can't find what is going wrong / how to avoid the problem. I added the log of the number 5 and 6 to check where the problem is, and the log in the onCreate does see the 5, but not the 6
public static ArrayList<String> urlList = new ArrayList<String>();
public static ArrayList<String> groupList = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_middel_scherm);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.imageLayout);
setSupportActionBar(toolbar);
db = FirebaseFirestore.getInstance();
mAuth = FirebaseAuth.getInstance();
CurrentUser = FirebaseAuth.getInstance().getCurrentUser().getUid();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() == null) {
startActivity(new Intent(MiddelScherm.this, LoginScherm.class));
}
}
};
ivImage = (ImageView) findViewById(R.id.ivImage);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SelectImage();
}
});
databaseDownload();
Log.d(TAG, "egregergegre");
Log.d(TAG, String.valueOf(urlList));
Log.d(TAG, "egregergegre");
showEachImage(layout);
}
public void showEachImage(ConstraintLayout layout) {
for (String element: urlList) {
ImageView image = new ImageView(this);
image.setLayoutParams(new android.view.ViewGroup.LayoutParams(80,60));
image.setMaxHeight(20);
image.setMaxWidth(20);
Picasso.get().load(element).into(image);
layout.addView(image);
}
}
public void databaseDownload() {
urlList.add("5");
db.collection("user").document(CurrentUser).collection("meta-data")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
urlList.add("6");
for (DocumentSnapshot document : task.getResult()) {
String imageValue = document.getString("URL");
urlList.add(imageValue);
Log.d(TAG, String.valueOf(urlList));
}
} else {
Log.w(TAG, "Error getting documents.", task.getException());
}
}
});
db.collection("user").document(CurrentUser).collection("Group")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
String groupValue = document.getString("Group");
groupList.add(groupValue);
Log.d(TAG, String.valueOf(groupList));
}
} else {
Log.w(TAG, "Error getting documents.", task.getException());
}
}
});
}
I even tried to put the public void showEachImage(ConstraintLayout layout) inside the onCompletelistener but it gave an error at "this" at the line of: ImageView image = new ImageView(this): So i gave up on this structure as well
public void databaseDownload() {
urlList.add("5");
db.collection("user").document(CurrentUser).collection("meta-data")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
urlList.add("6");
for (DocumentSnapshot document : task.getResult()) {
String imageValue = document.getString("URL");
ImageView image = new ImageView(this);
image.setLayoutParams(new
android.view.ViewGroup.LayoutParams(80,60));
image.setMaxHeight(20);
image.setMaxWidth(20);
Picasso.get().load(imageValue).into(image);
layout.addView(image);
Log.d(TAG, String.valueOf(urlList));
}
} else {
Log.w(TAG, "Error getting documents.", task.getException());
}
}
});
db.collection("user").document(CurrentUser).collection("Group")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
String groupValue = document.getString("Group");
groupList.add(groupValue);
Log.d(TAG, String.valueOf(groupList));
}
} else {
Log.w(TAG, "Error getting documents.", task.getException());
}
}
});
}
The reason you're adding an OnCompleteListener is that get() starts an asynchronous Task, which will call the onComplete() method when the query is done.
The get() method returns immediately, which means the query isn't done yet, and hence the onCreate() method won't see any data.
Any code that needs the data should be execute in/from the onComplete() method.
I think crush with ImageView happens because "this" is OnCompleteListener class in onComplete method.
I want to get data from my Firebase Firestore database. I have a collection called user and every user has collection of some objects of the same type (My Java custom object). I want to fill my ArrayList with these objects when my Activity is created.
private static ArrayList<Type> mArrayList = new ArrayList<>();;
In onCreate():
getListItems();
Log.d(TAG, "onCreate: LIST IN ONCREATE = " + mArrayList);
*// it logs empty list here
Method called to get items to list:
private void getListItems() {
mFirebaseFirestore.collection("some collection").get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot documentSnapshots) {
if (documentSnapshots.isEmpty()) {
Log.d(TAG, "onSuccess: LIST EMPTY");
return;
} else {
for (DocumentSnapshot documentSnapshot : documentSnapshots) {
if (documentSnapshot.exists()) {
Log.d(TAG, "onSuccess: DOCUMENT" + documentSnapshot.getId() + " ; " + documentSnapshot.getData());
DocumentReference documentReference1 = FirebaseFirestore.getInstance().document("some path");
documentReference1.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
Type type= documentSnapshot.toObject(Type.class);
Log.d(TAG, "onSuccess: " + type.toString());
mArrayList.add(type);
Log.d(TAG, "onSuccess: " + mArrayList);
/* these logs here display correct data but when
I log it in onCreate() method it's empty*/
}
});
}
}
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(), "Error getting data!!!", Toast.LENGTH_LONG).show();
}
});
}
The get() operation returns a Task<> which means it is an asynchronous operation. Calling getListItems() only starts the operation, it does not wait for it to complete, that's why you have to add success and failure listeners.
Although there's not much you can do about the async nature of the operation, you can simplify your code as follows:
private void getListItems() {
mFirebaseFirestore.collection("some collection").get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot documentSnapshots) {
if (documentSnapshots.isEmpty()) {
Log.d(TAG, "onSuccess: LIST EMPTY");
return;
} else {
// Convert the whole Query Snapshot to a list
// of objects directly! No need to fetch each
// document.
List<Type> types = documentSnapshots.toObjects(Type.class);
// Add all to your list
mArrayList.addAll(types);
Log.d(TAG, "onSuccess: " + mArrayList);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(), "Error getting data!!!", Toast.LENGTH_LONG).show();
}
});
}
Try this..Working fine.Below function will get Realtime Updates from firebse as well..
db = FirebaseFirestore.getInstance();
db.collection("dynamic_menu").addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
if (e !=null)
{
}
for (DocumentChange documentChange : documentSnapshots.getDocumentChanges())
{
String isAttendance = documentChange.getDocument().getData().get("Attendance").toString();
String isCalender = documentChange.getDocument().getData().get("Calender").toString();
String isEnablelocation = documentChange.getDocument().getData().get("Enable Location").toString();
}
}
});
More reference
:https://firebase.google.com/docs/firestore/query-data/listen
If You do not want realtime updates refer Below Document
https://firebase.google.com/docs/firestore/query-data/get-data
Here is a simplified example:
Create a collection "DownloadInfo" in Firebase.
And add a few documents with these fields inside it:
file_name (string),
id (string),
size (number)
Create your class:
public class DownloadInfo {
public String file_name;
public String id;
public Integer size;
}
Code to get list of objects:
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("DownloadInfo")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
if (task.getResult() != null) {
List<DownloadInfo> downloadInfoList = task.getResult().toObjects(DownloadInfo.class);
for (DownloadInfo downloadInfo : downloadInfoList) {
doSomething(downloadInfo.file_name, downloadInfo.id, downloadInfo.size);
}
}
}
} else {
Log.w(TAG, "Error getting documents.", task.getException());
}
}
});
db.collection("users").get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
console.log(`${doc.id} => ${doc.data()}`);
});
source:-
https://firebase.google.com/docs/firestore/quickstart
This is the code to get the list.
Since this is an async task, it takes time that's why the list size shows empty at first.
But including the source for the cache data will enable the previous list(and also its size) to be in memory until next task is performed.
Source source = Source.CACHE;
firebaseFirestore
.collection("collectionname")
.get(source)
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot documentSnapshots) {
if (documentSnapshots.isEmpty()) {
return;
} else {
// Convert the whole Query Snapshot to a list
// of objects directly! No need to fetch each
// document.
List<ModelClass> types = documentSnapshots.toObjects(ModelClass.class);
// Add all to your list
mArrayList.addAll(types);
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});