Firebase Multi Location Updates - Setting Children With Empty Values - java

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".

Related

Firebase for android studio reading not working

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.

How to get nested push key from Firebase database Android

I have my DB structure like this:
When someone follows someone else or likes a picture or something, the notification goes into the Notifications table followed by the users id(who sent the notif) followed by a unique id to separate the notifications. If I don't add that unique id(push()) only one notification is added and when a new one is supposed to be added only the time and text of the notification changes.
This is how I add the notification:
private void addNotifications(String userid, String postid) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Notifications").child(userid);
String notificationid = reference.getKey();
mGroupId = reference.push().getKey();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("dateAdded", System.currentTimeMillis());
hashMap.put("date_time", getTimeDate());
hashMap.put("notificationid", notificationid);
hashMap.put("userid", firebaseUser.getUid());
hashMap.put("text", "liked your post");
hashMap.put("postid", postid);
hashMap.put("ispost", true);
reference.child(mGroupId).setValue(hashMap);
Log.d("Post Key", mGroupId);
}
This shows me in the logcat the correct push key that was just added Log.d("Post Key", mGroupId);.
I am trying to delete anything older than a day in my notifications table. When I try to access mGroupId in the notifications fragment I get this error java.lang.NullPointerException: Can't pass null for argument 'pathString' in child().
I have been checking answers and comments for days now from experts like Frank Van P. and Alex Mamo and from regular people. I tried downvoted answers and comments and still nothing. I asked this before but the question keeps getting closed as a duplicate even though none of the duplicates help. How can I proceed?
How I try to delete the notifications older than a day:
private void lessThanADayNotification() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Notifications").child(firebaseUser.getUid());
DatabaseReference freezerItemsRef = reference.child(PostAdapter.mGroupId);
//Log.i("uid", uid);
long cutoff = new Date().getTime() - TimeUnit.MILLISECONDS.convert(12, TimeUnit.SECONDS);
Query oldBug = reference.child("Notifications").orderByChild("dateAdded").endAt(cutoff);
oldBug.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
Notification notification = new Notification();
freezerItemsRef.child(notification.getNotificationid()).removeValue();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
I've said this before on the question that you since deleted: there is no way to query on your dateAdded property from the Notifications node.
Firebase queries operate on a flat list of the child nodes directly on the node where you query. So in your data model you can query notifications for a specific user, but you can't query notifications across all users.
If you want to query across the notifications of all users, you will need to store them as a flat list, with the UID in that case stored as a property of each notification node.
See:
Firebase Query Double Nested
Firebase query if child of child contains a value

Firebase authentication - Display user info

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

How to insert and retrieve Android code on this Firebase structure?

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

How to fetch data on Firebase from time to time?

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

Categories

Resources