FirebaseDatabase fb = FirebaseDatabase.getInstance();
DatabaseReference IDrefs = fb.getReference("ID_Numbers");
IDrefs.addListenerForSingleValueEvent(new ValueEventListener(){
String name;
#Override
public void onDataChange(#NotNull DataSnapshot shot){
Toast toasty = Toast.makeText(getApplicationContext(),"name",Toast.LENGTH_LONG);
toasty.show();
for(DataSnapshot ds : shot.getChildren()) {
name = ds.child("First_Name").getValue(String.class);
}
TextView txtName = findViewById(R.id.lblName);
txtName.setText(name);
}
#Override
public void onCancelled(#NotNull DatabaseError err){
throw err.toException();
}
});
Hi so I am new to firebase in general. I am trying to read data from the real time database when the application loads in. This code works sometimes. For some reason the ValueEventListener does not run and the results come out as blank. What I want it to do is extract the First_Name fields value from my database to display it in my application. There are no errors provided it just doesn't seem to work.
Image of my firebase database
EDIT:
So its working now turns out I was using the wrong event listener
I was using addListenerForSingleValueEvent not addValueEventListener. The former calls the values from the devices local cache instead of going straight to the database (At least that is what I can understand from the documentation) while the latter goes straight to firebase to get the data. It works now consistently. With no issues from what I can see.
Related
I'm currently building a to-do app on Android Studio. I'm facing an issue with my Firebase database. What I'm trying to do is, each user to have a unique id based on their google sign in, in order to see only their own data. Currently, on my app, everyone can see anyone's' tasks. On Firebase I'm using the Realtime Database, specifying it by one child of "Users" and another one of Task + a random number. Also, I've already added the google sign in button on the launch of my app.
Current Database:
enter image description here
Example of how my hierarchy wants to be:
enter image description here
According to your comments, to get only the Task objects the correspond to a particular user, please use the following lines of code:
String userId = "User-13294";
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference tasksRef = rootRef.child("Users").child(userId).child("Tasks");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot taskSnapshot : dataSnapshot.getChildren()) {
String title = taskSnapshot.child("title").getValue(String.class);
Log.d("TAG", title);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
tasksRef.addListenerForSingleValueEvent(valueEventListener);
Because User-13294 has only one Task, the result in the logcat will be only one title:
Swimming
I use the firebase realtime database to store user information.
Here is a picture of the database:
screenshot of the database
For example, how can I get the value "nombre_dons" according to the connected user to display it in the application ? I use android studio in java.
Thank you in advance for your help
Those parent strings of the user data in Users node in your database look like the uids. If they indeed are, then all you need to do is to retrieve data from those uids for the particular user.
What I am saying looks something like this in code:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users");
FirebaseAuth mAuth = FirebaseAuth.getInstance();
ref.child(mAuth.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String data = dataSnapshot.child("nombre_dons").getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "onCancelled", databaseError.toException());
}
});
One flaw I can see in your database image is that nombre_dons child in second user in your Users node has capital N, which would be a problem, because Firebase is case sensitive. I'd advise you to keep it same as others.
Assuming the keys inside 'Users' in your database are Firebase Authentication UserId(s), you can follow these steps-
1. Get UID of the current user.
2. Fetch data for the same.
Using Javascript -
var uid = firebase.auth().currentUser.uid;
firebase.database().ref('/Users/' + uid).once('value').then(function(snapshot){
var nombre_dons = snapshot.val().nombre_dons;
});
I am from PHP and MySQL background and I haven't worked with JSON based DB like Firebase.
I am looking for sample code to insert data in firebase "Realtime database". I am already done with authentication stage.
To insert some data in your Firebase Database, you have to set the reference to the node you want to insert the data to and then use setValue() method.
Suppose you want to change age of the admins node, in your database in the question.
In code it looks something like this:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users").child("admins");
ref.child("age").setValue(76);
The above code will replace 42 with 76, in your admins node's age child.
Read more about this here.
Getting data from Firebase Database is a bit more work, as you have to use listeners for that. There are 3 different event listeners at your disposal, that are valueEventListener childEventListener and singleValueEventListener.
These three eventListeners have different properties and you can use them as you like.
Suppose you want to retrieve age of your admins node from your database, then you may use a code like this to help. Note ref in this code is same as in above code.
ref.addSingleValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int age = dataSnapshot.child("age").getValue(String.class);
// this will store value of age from database to the variable age
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.d("TAG:", "Couldn't read data ", error.toException());
}
});
Read more about this here.
Refer to this link, https://firebase.google.com/docs/database/android/start/
Write a message to the database
// Write a message to the database
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("message");
myRef.setValue("Hello, World!");
Read a message from the database
// 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);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
I am trying to use multi-location updates in order to change values in the Realtime Database and have one listener to follow all of the changes at once.
This is what I have tried to do:
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
Map data = new HashMap();
data.put("Users/"+senderEmail+"/friends_requests_sent/"+receiverEmail,"");
data.put("Users/"+receiverEmail+"/friends_requests_received/"+senderEmail,"");
mDatabase.updateChildren(data, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError!=null)
showConnectionErrorToast();
else{
Context context=getContext();
Toast.makeText(context,
context.getString(R.string.friend_request_was_sent), Toast.LENGTH_SHORT).show();
}
}
});
The children are being added just fine (receiverEmail and senderEmail), but it forces me to put values in them, although I don't want to. I want that the email will be the key of this children, without a value.
Is this possible in this way?
If it's not, what will be the best alternative?
There is no way to store a key without a value in the Firebase Database. In cases where you really don't have a value to store, consider using a marker value like true or "TBD".
I am fetching data on Firebase from time to time because I am tracking someone's GPS. That someone is saving his location in an interval of 5 minutes so that I can track his GPS. But my problem is how do I fetch data from Firebase with an interval of 5 minutes too?
Or is there any possible way other than this?
Thanks in advance. :)
So if someone is updating his/her location in every five minutes, then you really don't have to run a CounterDownTimer in your side to track the location in every five minutes. So I think you just need to add a listener to that node at Firebase that you want to track.
So here's a simple implementation for you. Copied from Firebase Tutorial
Firebase ref = new Firebase("https://docs-examples.firebaseio.com/web/saving-data/fireblog/posts");
// Attach an listener to read the data at our posts reference
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
System.out.println(snapshot.getValue());
}
#Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
I'm copying quotes from there too. So that you know it serves your purpose.
This method will be called anytime new data is added to our Firebase
reference, and we don't need to write any extra code to make this
happen.
So each time the person you want to track will update his/her location, you'll get a callback in the method stated above and will take necessary action. You really don't have to implement a polling mechanism to do the tracking. That's the way Firebase works actually.
No Needs to put any kind of service of Scheduler to retrieve data from firebase.
As Firebase provide realtime database .. whenever you push your data on Firebase Database the listener will trigger and you can retrieve your data..
Implement following Listener, using this you can retrieve your data whenever database get update.
DatabaseReference mDatabase =FirebaseDatabase.getInstance().getReference();
ValueEventListener yourModelListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get YOURMODEL object and use the values to update the UI
YourModel mModel = dataSnapshot.getValue(YourModel.class);
Log.e("Data : ",""+mModel);
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
}
};
mDatabase.addValueEventListener(yourModelListener);
For More Info about Listeners .. https://firebase.google.com/docs/database/android/retrieve-data