I am currently working on a chat app using Firebase and am looking for some help or clarification. So my Database is structured below. Under the ChatID node are random push IDs that each contain some information which get made everytime a message is sent. Is it possible to get the last push ID automatically so I can obtain only the information stored in that push key? I have seen using orderbykey but not sure if that would work.
Database Structure
Chat
-ChatID
-LIYv8kWHEZ7udgM048U
-LIYv9t5jNmR8RXPht-p
-LIYxzbhbfkItT3FAsWB
createdByUser: "T3Wb0pHSfCTaIA2ofQSxc915wK83"
text: "Hey"
timestamp: "Aug 19"
-LIaJaAGG-jwD0i_bAqL
createdByUser: "T3Wb0pHSfCTaIA2ofQSxc915wK83"
text: "Yoooo"
timestamp: "Aug 20"
you can do the following
chatRef.orderByChild("ChatID").limitToLast(1).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String key = dataSnapshot.getKey();
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
Where chatRef
DatabaseReference mDatabase,chatRef;
mDatabase = FirebaseDatabase.getInstance().getReference();
chatRef = mDatabase.child("Chat");
I was able to solve using this
final DatabaseReference ChatDB = mDatabaseChat.child("ChatID");
final Query lastQuery = ChatDB.orderByKey().limitToLast(1);
ChatDB.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
lastQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot child: dataSnapshot.getChildren()){
String key = child.child("text").getValue().toString();
Related
How do I get the push id of the value where child("topic_name").getValue() = "algebre" ?
FirebaseDatabase Structure:
I have already tried push().getKey(); but it returns another key to me.
Try this:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child(TOP_NODE_NAME).orderByChild("topic_name").equalTo("algebre");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
String key = child.getKey();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Now key has the Key of the node where topic_name=algebra
I have a Firebase database of the following:
Root Node
User node
an automatically generated key generated by ref.push()
attributes
I am trying to retrieve only one of the attributes of a single child under the user. Here is a screenshot of my database:
Screenshot of my database
If you check the screenshot, i only want to retrieve email (assume i have no other way of getting it). However, in the code, I wouldn't know the child of User that contains the email I want. This is what i am currently doing but it is very inefficient (this code checks if my current user exists, if not, it adds his/her data to the database):
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("User");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> children = dataSnapshot.getChildren();
for (DataSnapshot child:children) {
User user1 = child.getValue(User.class);
Log.d("kharas email",user1.getEmail()+"");
if(!user1.getEmail().equals(firebaseAuth.getCurrentUser().getEmail())){
GraphRequest.newMeRequest(token, new GraphRequest.GraphJSONObjectCallback() {
String birthday = "Not Available";
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
User userInfo = new User();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("User");
birthday = object.has("email")+"";
userInfo.setBirthday(birthday);
userInfo.setEmail(firebaseAuth.getCurrentUser().getEmail());
ref.push().setValue(userInfo);
}
}).executeAsync();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I tried to set the child under User to the email but firebase wouldnt let me use some special characters in the key. Any suggestions to make the code more efficient would be appreciated. Or any key suggestions that would make querying easier would be great.
Thanks in advance
Instead of putting random value or auto generated key you can add user's id which is received from fire base
firebaseAuth.getCurrentUser().getUid()
This will be more easy to access and will be more efficient because whenever you get will logged in, you will have this user_id and corresponding to user_id you can get email instead of checking all values in database
The only way to retrieve email if you dont know the random key is this:
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("User");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){ for (DataSnapshot child:children) {
String email=datas.child("email").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Or you can use firebase authentication and add the userid under Users instead of push() then retrieve the userid :
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
String userid=user.getUid();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("User");
ref.child(userid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String email=dataSnapshot.child("email").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
That way you do not have to loop.
I want to get the pushed key by the help of its child value
Say you have the agency name, then you can create a Firebase Database query to find the matching child nodes with that agency name:
DatabaseReference ref = FirebaseDatabase.getInstance();
Query query = ref.orderByChild("agencyname").equalTo("Babaji");
query.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey()+" "+ dataSnapshot.getChild("agencyname").getValue());
}
...
The onChildAdded method above will be called for every node with agencyname equal to Babaji.
I recommend spending some more time in the Firebase documentation, specifically the sections on dealing with lists of data and on querying.
You can use this also
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
Query query = mDatabase.child("suppliersdata");
query.orderByChild("agencyname").equalTo("Babaji").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
Log.i("db", "onDataChange: Key : " + childSnapshot.getKey());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // never ignore errors
}
});
I have integrated Google sign-in in my app and i am pushing some data in to fire base including user U-id.I had researched a lot and didn't get anything the problem i am facing that i want to fetch Particular data for eg If User A sign-in and push 5 data and Then User B sign-in and push 3 data.I want a query like if User A sing-in Again it will get his 5 data only and not the data which is pushed by User B.Thanks in Advance :)
By using this it fetch all the data from firebase:
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
FirebaseModel firebasemodel =
data.getValue(FirebaseModel.class);
firebasemodels.add(firebasemodel);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I have tried all that .child .orderby and .equalTo but did'nt work
My Structure is Like:
My FireBase Structure
You also need a reference to the data, which isn't included in your code block. So something along the lines of (this should be before this):
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("notepad-secure/notepad");
Firstly add a user_id key in your child data, it will look like below :
id:"",
note:"",
title:"",
user:""
user_id:"{id from which user have you uploaded data}"
And than you can call below function with specific user data like
below Note : "user_id" = id from which user have you uploaded data
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("notepad").orderByChild("id").equalTo("user_id");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// dataSnapshot is the "notepad" node with all children with id
for (DataSnapshot notepad: dataSnapshot.getChildren()) {
// do something with the individual "notepad_data"
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
To Fetch Particular values from the firebase,try this code
FirebaseDatabase database;
database.getReference().child("notepad-secure").orderByChild("id").equalTo(user).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
User userdet =childSnapshot.getValue(yourclass.class);
String note=userdet.note;
//Here you will get the string values what you want to fetch
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
First U have to differentiate.U have to implement Firebase Authentication the u can get Firebase UID of every USER.
String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
Then store seperatly in new node.
i.e Take Firebase Database Instance and
databaserefernace.child("Data").Child("userID);
When your add a user data to Firebase database, you can add it using the specific uid provided by the FirebaseAuth object like this:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
Assuming you that your database strucure look like this: Firebase root -> notepad-secure -> notepad, to retrieve data, you can use this code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference notepadRef = rootRef.child("notepad-secure").child("notepad").child(uid);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String id = dataSnapshot.child("id").getValue(String.class);
String note = dataSnapshot.child("note").getValue(String.class);
String title = dataSnapshot.child("title").getValue(String.class);
String user = dataSnapshot.child("user").getValue(String.class);
Log.d("TAG", id + " / " + note + " / " + title + " / " + user);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
notepadRef.addListenerForSingleValueEvent(eventListener);
I am new to Firebase and Android. I have stored user authentication details (name, profile image other than email ID) in my Firebase account. I want to retrieve those data (such as names etc.,) to the other part of my app. How can I retrieve my realtime database child values?
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("userID").child("displayName");
// Attach a listener to read the data at our posts reference
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String displayName = dataSnapshot.getValue().toString();
System.out.println(displayName );
}
For more:
Read and Write Data on Android - Firebase Documentation
If you want to get the names of all the users, then you can do it like this
DatabaseReference mRef = FirebaseDatabase.getInstance().getReference();
mRef.child("users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot: dataSnapshot.getChildren()){
Log.v("user_name", snapshot.getValue(String.class));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});