How to get all field and immediately assign it? - android

How i can get all the field and immediately assign it to some variable
I tried this
db= FirebaseFirestore.getInstance();
db.collection("Users")
.whereEqualTo("email", email)
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
}
});
I dont know if it the correct way and i dont know how to complete it.

I think it will easy for you to use Firestore.
With Firestore you can easily get the records with like "where" conditions.
Please check this example mentioned in the Firestore documentation (https://firebase.google.com/docs/firestore/query-data/get-data).
db.collection("cities")
.whereEqualTo("capital", true)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData());
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});

Related

How to iterate a Firestore collection on Android?

I have a Firestore collection like this:
Take a look at kost collection. There are 4 docouments in it, and each document has the following fields: fasilitas, gender, harga, etc
For each document, I want to retrieve all the fields.
Now I have this:
FirebaseFirestore firestore = FirebaseFirestore.getInstance();
DocumentReference docRef = firestore.collection("kost").document();
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()){
for (DocumentSnapshot ds:task.getResult()){
}
}
}
});
It's not even a correct code, task.getResult() is underlined:
foreach not applicable to type
'com.google.firebase.firestore.DocumentSnapshot
What's the correct way, then?
Your problems is in this code:
DocumentReference docRef = firestore.collection("kost").document();
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
Your docRef points to a new, empty document. What you want instead is to point to the entire collection as shown in the documentation on reading all documents in a collection:
db.collection("kost")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData());
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});

Android Firestore get field values by document id

I have a Firebase Firestore database in which I have to get all the field's inside a document by document id.
How to get the all the field values (inside Green Box) by document id (Red box)
If you want to get that specific document you can try this
DocumentReference docRef = db.collection("projects").document("YOURDOCIDHERE");
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Log.d(TAG, "DocumentSnapshot data: " + document.getData());
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
If you want get all documents by key order then you can try making a query like this.
docRef.orderByKey()
Check firebase documention for more info.

How to fetch data just one time from firebase and don't listen to any data change

I'm new to firebase and recently started working on this. Every tutorial I saw, is about how to listen to data change in cloud firestore. What if I want to fetch teh data just once and don't wanna set anyy listener on them. Example scenario is, just fetching the data user last login time or profile data of any user
The documentation has a dedicated section about getting data a single time for a query. Just use the get() method on the query you build:
db.collection("cities")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData());
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
Or, for a single document:
DocumentReference docRef = db.collection("cities").document("SF");
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Log.d(TAG, "DocumentSnapshot data: " + document.getData());
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});

Android Sequence (Skipping method)

i have some problem understanding whats wrong with android code about calling function
as show below, I have 2 private void
cekSaved(place.getName());
addUserInfo(place.getName(),"");
i expect the android run ceksaved method first then addUserInfo but android running adduser first then run ceksaved function
i need help understanding this
code is :
private void cekSaved(String param1){
FirebaseFirestore db = FirebaseFirestore.getInstance();
DocumentReference newUserInfo = db.collection("trip").document();
String userID = FirebaseAuth.getInstance().getCurrentUser().getUid();
db.collection("trip")
.whereEqualTo("user_id", userID )
.whereEqualTo("city", param1)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful())
{
for (QueryDocumentSnapshot document : task.getResult()) {
status = "ada";
Log.i(TAG, "onComplete: "+status);
}
}
else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
}
private void addUserInfo(String city, String tittle){
FirebaseFirestore db = FirebaseFirestore.getInstance();
DocumentReference newUserInfo = db.collection("trip").document();
place_id = newUserInfo.getId();
Log.i(TAG, "addUserInfo: "+status);
if(!status.equals("ada")) {
String userID = FirebaseAuth.getInstance().getCurrentUser().getUid();
userTrip usertrip = new userTrip();
usertrip.setCity(city);
usertrip.setTittle("My Trip To " + city);
usertrip.setTrip_id(newUserInfo.getId());
usertrip.setUser_id(userID);
Log.i(TAG, "addUserInfo: trip baru telah di buat");
newUserInfo.set(usertrip).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
ToastMessage("OK");
} else {
ToastMessage("fail to register");
}
}
});
}else{ToastMessage("sudah ada");}
}
You're getting values from Firebase, it's an async call, so you don't really know which one will be completed first. You can see that either calls have an onCompleteListener, if you want to run addUserInfo after cekSaved you have to call addUserInfo inside onCompleteListener of cekSaved method.

how to search at firestore document's field

How to search at firestore documents? if firestore collection contains certain document and if there has a string field at document named 'title'. How can i search specific title using firebase android api.
It is documented in the Docs here, in the last section of the page, titled Get multiple documents from a collection.
Firestore provides a whereEqualTo function to query your data.
Example code (from Docs):
db.collection("cities")
.whereEqualTo("capital", true) // <-- This line
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData());
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
I have use MutableLiveData for search the specific user's name .where i pass the user's name and check whether it is available in Firestore or not
Here is my code:-
public MutableLiveData<UsersModel> getSpecificUser(final String name) {
final MutableLiveData<UsersModel> usersData = new MutableLiveData<>();
db.collection("users")
.whereEqualTo("name", name)
.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot snapshot, #Nullable FirebaseFirestoreException e) {
if(e!=null || snapshot.size()==0){
Toast.makeText(activity, "User not found", Toast.LENGTH_SHORT).show();
}
for (DocumentChange userDoc : snapshot.getDocumentChanges()) {
UsersModel user = userDoc.getDocument().toObject(UsersModel.class);
if (user.name != null) {
if (userDoc.getType() == DocumentChange.Type.ADDED || userDoc.getType() == DocumentChange.Type.MODIFIED) {
usersData.setValue(user);
}
}
}
}
});
return usersData;
}

Categories

Resources