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");
Related
Recently, I'm working on an app which is used to set alarm to other users who are logged in to the app, But problem is how can I set alarm to other user when the data is changed in the real-time database of firebase. Is there is any way that if I update the data of other user and It should to retrieved and updated in other users application and alarm should set when data is received.
DatabaseReference duser = FirebaseDatabase.getInstance().getReference("Alarm");
duser.keepSynced(true);
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
duser.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String ids = snapshot.child(id).getKey();
Log.d("ID : ", ids+"");
String hour = snapshot.child(id).child("hour").toString();
Log.d("HOUR : ", hour+"");
String minute = snapshot.child(id).child("minute").toString();
}
Database
This is my database.
If yes please explain me, how to do.
What does Query#addListenerForSingleValueEvent(ValueEventListener listener) method it:
Add a listener for a single change in the data at this location.
This means that you'll get the data only once, without future updates. If you want a persistent listener to listen for real-time changes, then you use Query#addValueEventListener(ValueEventListener listener) that:
Add a listener for changes in the data at this location.
So each time something is added, changed, or deleted you're notified almost instantly. If you want, you can also use a library for that, which is called Firebase-UI.
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?
I keep having this issue in my code.
From the code below, I think I already checked if the load() value is null. If it's null, the code should never reach Picasso.
My app allows users to give comments or upload photos to a dish (like yelp). However, they're not required to post both. So there could be data have only comment or photo.
So, I'm not sure if that's something that causes the problem.
This is the database where I wanna retrieve from:
https://ibb.co/ZNTSFb0
To explain my code a little:
Check if the dataSnapshot1 has image value;
if yes, then check if the dishName matches this dish;
if yes, then put the photo on the imageView.
Code:
mdatabaseReferece1 = FirebaseDatabase.getInstance().getReference("Post");
mdatabaseReferece1.addValueEventListener(new ValueEventListener() {
#Override
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()){
if (dataSnapshot1.child("image").getValue()!=null){
if (dataSnapshot1.child("dishName").getValue().toString().equals(newDish)) {
ImageView imageView = findViewById(R.id.gallery_photo);
Picasso.get().load(dataSnapshot1.child("image").getValue().toString()).into(imageView);
gallery.addView(view);}
}
}
}
I don't have to use Picasso if there's any other easier way. All I want to have on my app is a list of matched photos retrieved from the firebase.
Change the following:
if(dataSnapshot1.child("image").getValue()!=null)
Into this:
if(dataSnapshot1.hasChild("image")){ /* code */ }
From the docs:
hasChild(String path)
Can be used to determine if this DataSnapshot has data at a particular location
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.
This question already has answers here:
Firebase Offline Capabilities and addListenerForSingleValueEvent
(4 answers)
Closed 4 years ago.
I'm trying to make a search query using firebase and it works really well.
Query searchQuery = usersRef.orderByChild(child).startAt(text).endAt(text + "\uf8ff").limitToFirst(limit);
searchQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//search result logic
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
I have enabled offline capabilities because in need them in my app and here is my problem: this ValueEventListener keep listening on the local stored datas while I need to keep it always updated... it's a search query.
I don't think keepSynced(true) applied to the users reference would be a nice idea because this reference is huge and this will cause lot of internet and memory waste.
I've red on web that using addValueEventListener instead of addListenerForSingleValueEvent query will always receive updated answers from the server, without look in local stored data.
This could be a way to solve my problem but I need to listen data ONCE and this will keep listen for datas so should I stop this listener if I decide to use it?
Please help me with some ideas and sorry for my scholastic English.
If you have enabled offline capabilities, it means that you'll be able to use your app even if it temporarily loses its network connection. So the ValueEventListener will keep listening on the local stored datas as long as you are offline. If you want the results to be updated, then you need to go online.
If you want to listen to data only once, then you need to use: addListenerForSingleValueEvent(). If you want to use addValueEventListener, just don't forget to remove the listener according to the life-cycle of your activity as I have already answered here.
Well you could hold a reference to your event listener and remove it from the reference when you dont need it.
myEventListener = ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//happy place
}
#Override
public void onCancelled(DatabaseError databaseError) {
//error
}
});
Somewhere else:
ref.removeEventListener(myEventListener);