How to get document id Firestore? - java

I was trying to get document id for updating a data, but instead it create a new document id. How to get document id Firestore?
Code :
final String getID = firebaseFirestore.collection("Users").document(currentUser.getUid()).collection("Documents").document().getId();
buttonUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String inspectorName = editInspector.getText().toString().trim();
final String marketLocation = editLocation.getText().toString().trim();
progressUpdated.show();
firebaseFirestore.collection("Users").document(currentUser.getUid()).collection("Documents").document(getID).update("inspectorName", inspectorName, "marketLocation", marketLocation).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(StartCounting.this, "Document updated", Toast.LENGTH_SHORT).show();
progressUpdated.dismiss();
dialogUpdate.dismiss();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(StartCounting.this, "Error : " + e.toString(), Toast.LENGTH_LONG).show();
progressUpdated.dismiss();
}
});
}
});

It is not updating because :
The following code of line generates new id when you call the getID each time you call it and store in String.
String getID = firebaseFirestore.collection("Users").document(currentUser.getUid()).collection("Documents").document().getId();
So i suggest you to store the id which you get from getID store under each user document. Something like when you create / generate document just add the String value of id under the userid field.

Related

Link two tables in firebase using Id in android studio using Java

have a problem, I'm working on a university project, I have two tables in firebase, the gallery table that contains the photos of the itinerary and the itinerary table that contains the various itineraries of the users now I have to make sure that the id of the itinerary and the ID of the image so as to have a photo corresponding to each itinerary ì, also created by the same user. I did so:
public void addImageItinerary() {
storageReference = FirebaseStorage.getInstance().getReference();
referenceDb = FirebaseDatabase.getInstance().getReference();
firestore = FirebaseFirestore.getInstance();
auth = FirebaseAuth.getInstance();
if (images != null) {
StorageReference itineraryRef = storageReference.child("itinerary_image/" + FirebaseAuth.getInstance().getCurrentUser().getUid() + ".jpg");
itineraryRef.putFile(images).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
itineraryRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String itineraryId = referenceDb.child("Itinerary").push().getKey();
Log.i("itineraryId", itineraryId);
HashMap<String, Object> map = new HashMap<>();
map.put("image", uri.toString());
referenceDb.child("Gallery").child(FirebaseAuth.getInstance().getCurrentUser().getUid()+ "/" + itineraryId).setValue(map).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
// APRO SCHERMATA MAPPA
// openMapFragment();
Toast.makeText(insertImage_fragment.getActivity(), "ok", Toast.LENGTH_SHORT).show();
} else {
//ERRORE
Toast.makeText(insertImage_fragment.getActivity(), "Operation failed. Please try again", Toast.LENGTH_SHORT).show();
}
}
});
}
});
} else {
Toast.makeText(insertImage_fragment.getActivity(), task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});
} else{
Toast.makeText(insertImage_fragment.getActivity(),"Please add image", Toast.LENGTH_SHORT).show();
}
}
enter image description here

Store subcollection data in Firestore

I have a problem on to add a subcollection "Diary" under collection "Users". How to make it so that one user can have several diary?
Here's Java codes:
check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseUser user = fAuth.getCurrentUser();
String uid = user.getUid();
DocumentReference df = fStore.collection("Diary").document(user.getUid());
Map<String, Object> diaryInfo = new HashMap<>();
diaryInfo.put("Symptom", symptom.getEditText().getText().toString());
diaryInfo.put("UID", uid);
diaryInfo.put("Note", note.getEditText().getText().toString());
diaryInfo.put("Date", dateButton.getText().toString());
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();
}
});
}
});
Database structure:
You should place your subcollection inside the corresponding document of your parent collection:
// Create a reference to a new 'Diary' document at Users/user_id/Diary/doc_id
// with an auto-generated document id
DocumentReference df = fStore.collection("Users").document(user.getUid()).collection("Diary").document();
When you need to retrieve the diaries, query the individual user's Diary collection:
fStore.collection("Users").document(user.getUid()).collection("Diary")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
// Do something with your retrieved documents
}
}
}

how to delete the auto generated item from push method from Firebase Real-time database

I am new to Firebase and I am facing a problem in delete an item from the recycler view I created. but I am unable to understand how to delete items using an auto-generated key. This is how I added item into the database:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("categories");
String key = reference.push().getKey();
reference.child(key).setValue(categoryData).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(add_category.this, "Category added", Toast.LENGTH_SHORT).show();
finish();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(add_category.this, "Failed to add", Toast.LENGTH_SHORT).show();
}
});
As in your comment, if you want to delete, for example, the second item, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference secondChildRef = rootRef.child("categories").child("-M1qUEGi0u4rX5Ju59r4");
secondChildRef.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d("TAG", "Second item deleted!");
}
}
});
So to delete a particular item, you to know its ID so you can add it to the reference.

Get all fields in a document in a list - Firestore Java

I am trying to get all fields from a document to a ListView. I have tried foreach loop but it is not working.
dbRef.collection("Shopkeeper Own Shops").document("Shopkeeper#gmail.com")
.get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
// Get all fields to a list
}
});
To add all the value of all properties within a document to a list, please use the followig lines of code:
dbRef.collection("Shopkeeper Own Shops").document("Shopkeeper#gmail.com").get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
List<String> list = new ArrayList<>();
Map<String, Object> map = document.getData();
if (map != null) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
list.add(entry.getValue().toString());
}
}
//So what you need to do with your list
for (String s : list) {
Log.d("TAG", s);
}
}
}
}
});
To get the fields use the following:
DocumentReference docRef = db.collection("Shopkeeper Own Shops").document("Shopkeeper#gmail.com");
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());
Log.d(TAG,"String value: " + document.getString("names"));
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
public Map<String, Object> getData ()
Returns the fields of the document as a Map or null if the document doesn't exist. Field values will be converted to their native Java representation.
Or you can use getString()
Try This
List<Type> types = documentSnapshots.toObjects(Type.class);
For your example will be like this
dbRef.collection("Shopkeeper Own Shops").document("Shopkeeper#gmail.com")
.get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if(documentSnapshots.isEmpty()){
Log.d("MyLogger", "Empty Document!");
}else{
// Get all fields to a list
List<MyModel> types = documentSnapshots.toObjects(MyModel.class);
}
}
});
public class MyModel{
// Define fields
private String id;
private String name; // ...etc
// GETTER/SETTER,
}
Try this,
Make sure you have internet permission in manifest,
And your project is connected to firebase.
private static final String KEY_NAME = "name";
public void loadName() {
db.collection("users").document()
.get()
.addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
String name = document.getString(KEY_NAME);
} else {
Toast.makeText(activity_home.this, "Error", Toast.LENGTH_LONG).show();
}
}
});
}

Firebase Firestore get data from collection

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) {
}
});

Categories