I want to make an Android chat application. So I want to know how to get data from Firebase Firestore automatically, when new document create? Actually I do not wanna use add snapshot listener because of its give real-time data changes of a single document but want to find out real time updated Firebase Firestore document. Please suggest me.
I don't know if you can do this without a snapshot listener.
Check this code, if it is what you want.
private void addRealtimeUpdate() {
DocumentReference contactListener=db.collection("PhoneBook").document("Contacts");
contactListener.addSnapshotListener(new EventListener < DocumentSnapshot > () {
#Override
public void onEvent(DocumentSnapshot documentSnapshot,
FirebaseFirestoreException e) {
if (e != null) {
Log.d("ERROR", e.getMessage());
return;
}
if (documentSnapshot != null && documentSnapshot.exists()) {
Toast.makeText(MainActivity.this, "Current data:" +
documentSnapshot.getData(), Toast.LENGTH_SHORT).show();
}
}
});
}
To solve this, I recommend you to use CollectionReference's get() method. This is the correspondent addListenerForSingleValueEvent() method from Firebase real-time database.
Executes the query and returns the results as a QuerySnapshot.
If you want to use Firebase-UI library, this is a recommended way in which you can retrieve data from a Cloud Firestore database and display it in a RecyclerView using FirestoreRecyclerAdapter.
I don't know if you can do it with firestore but with realtime database you can use the .on(). If the rest of your app is using firestore, each project can use both a cloud firestore and a realtime database. The docs are really simple.
Related
I'm trying to update the user profile image in the Firebase Realtime Database on my application but I'm unable to get the reference of the current user as I declare it in another activity.
My code and database structure is as follows:
profile image
as in this current picture and the code, I'm writing manually the id of the child node (gli) because it is the user_name of the current user in the firebase, please help me how can I give it a path through coding.
code:
private void profileImage(){
pImageRef = FirebaseDatabase.getInstance().getReference("doctors/doctors_registration/gli/pimage"); 👈👈
pImageRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String imageurl= String.valueOf(dataSnapshot.getValue()) ;
Toast.makeText(HomeActivity.this, "link:"+imageurl, Toast.LENGTH_SHORT).show();
Picasso.get()
.load(imageurl)
.into(profileimg);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Please see the screenshot of the database structure and help me how I can get the current user profile image?
First of all, stop ignoring errors. At a minimum, please add inside the onCancelled method:
Log.d(TAG, error.getMessage());
Please also note that Picasso is a library that can help you download images and not update them in the Realtime Database. If you want to update the image at an existing location, remember that there is no need to read it first. To solve this, please use the following line of code:
pImageRef.updateChildren("yourNewUrl");
You can also use in this case addOnCompleteListener() to see if something goes wrong.
If you however need to update the image right after you read it, then inside the onDataChange() method, use the following line of code:
dataSnapshot.getRef().updateChildren("yourNewUrl");
So I'm making a wallpaper app that has various categories but I want to display all images from all nodes in Firebase in one fragment called Random, I also want the Images to shuffle images from each parent node
The following is my Firebase structure :
There are also child nodes in them :
The following is my java code from my Random fragment :
private void getWallpapers() {
progressBar.setVisibility(View.VISIBLE);
myRef = database.getReference().child("Wallpaper").child("Random");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
collectionsArray.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
wallpaper z = postSnapshot.getValue(wallpaper.class);
collectionsArray.add(z);
}
Collections.reverse(collectionsArray);
progressBar.setVisibility(View.GONE);
mAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
System.out.println("Error Reading from DB");
}
});
There is no built-in query that can get elements across different nodes in the database. Seeing that you have different structures for each category, the best option I can think of is to duplicate the data. This practice is called denormalization and is a common practice when it comes to Firebase. For a better understanding, I recommend you see this video, Denormalization is normal with the Firebase Database.
So you should create another node that will hold all images you have in the database, no matter from which category belongs. To select a random wallpaper, please check my answer from the following post:
How to get unique random product in node Firebase?
Also remember, when you are duplicating data, there is one thing that you need to keep in mind. In the same way, you are adding data, you need to maintain it. In other words, if you want to update/delete a wallpaper, you need to do it in every place that it exists.
If you might also be interested in:
What is denormalization in Firebase Cloud Firestore?
Does using SnapshotParser while querying Firestore an expensive operation in terms of read operation?
We are building query in our app like this:
options = new FirestoreRecyclerOptions.Builder<Item>()
.setQuery(query, new SnapshotParser<Item>() {
#NonNull
#Override
public Item parseSnapshot(#NonNull DocumentSnapshot snapshot) {
Item item = snapshot.toObject(Item.class);
item.setId(snapshot.getId());
return item;
}
})
.setLifecycleOwner(this)
So while reading data from server, does SnapshotParser will make extra read operation (or hit server again) or it will parse using already read data?
Would it be the same operation(in terms of server hit) with or without SnapshotParser?
Please explain, if anything is missed, please let me know? Sorry for bad english.
From the official documentation of Firebsase-UI library:
If you need to customize how your model class is parsed, you can use a custom SnapshotParser.
So if you need to customize your model class it doesn't mean that you are creating extra read operations. The parseSnapshot() method uses as an argument a DocumentSnapshot object which contains the data set that you are getting from the database for which you are already charged in terms of read operations. This is happening if the the query return data. If your query does not return any data, you are still charged but only with a single read operation.
So I started learning Android, a coworker -who is a fresh grad- at where I'm interning adviced me to learn Firebase since it is free and easy to use. I'm trying to do the most basic Read and Write operations, but for some reason I cant do it. I searched many different articles but i couldn't find why. Even said coworker tried to help me but still...
I connected to Firebase, gave needed permissions etc. and Firebase statics shows one app connected to it.
I'm following Firebase's own documents but its own code doesn't work on my app.
Said code:
// Read from the database
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
String value = dataSnapshot.getValue(String.class);
Log.d(TAG, "Value is: " + value);// "TAG" shows red
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
The thing I'm missing might be really simple. But like I said I looked into alot of articles. For start i just want to write something on database and read a string from it and print it on screen.
Edit: Compiler error I'm getting is : https://prnt.sc/kb7kcu (Too long to paste as text)
As if code not working, Firebase docs I'm following gives compiler error. And other codes from articles i tried doesn't update the database or read from it.
Hint -> paste this code and look closer how data is structured as a map of key value pairs.
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG, "dataSnapshot: " + String.valueOf(dataSnapshot));
for (DataSnapshot dataSnapshotItem : dataSnapshot.getChildren()) {
Log.d(TAG, "Inside: " + String.valueOf(dataSnapshotItem));
}
}
I this you was not define a rule in firebase console, so you have not access to read and write permission, for permission do follow steps :
Go to firebase console
select Database and click on realtime databse
in a tab manu you can see Rules tab, in the rules tab set rules like follow
{
"rules": {
".read": "auth == null",
".write": "auth == null"
}
}
check insertion or retrieve operation its work.
I have a collection who contains items of a restaurant menu, i want to know when a new item is added or have a change(price, name, description), because i want to notify this to the app and download this changes in a internal database.
I was trying to create a firebase function to modify a field called version and this way campare version in the app vs firebase version of the collection but i really dont know how to work with firebase functions.
can someone give a recomendation?
Cloud Firestore is a flexible, scalable database which keeps your data in sync across client apps through realtime listeners and offers offline support for mobile and web applications.
So in order to know if something has been changed in your database, you need to attach a listner on a particular location. Assuming you have a collection named cities and a document named SF, plase use the following code. It's a straight forward example.
DocumentReference docRef = db.collection("cities").document("SF");
docRef.addSnapshotListener(new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot snapshot, #Nullable FirebaseFirestoreException e) {
// see which fields changed
}
});
Unlike Firebase Realtime database, Cloud Firestore has data persistence enabled by default. So there is no need to keep your data also in a internal database.