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
}
});
Related
My insert() function:
public void insert(RSSModel rssModel, String TABLE_NAME) {
database.getReference()
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(TABLE_NAME)
.child(rssModel.getTitle())
.setValue(rssModel);
Log.d("alo " + rssModel.getTitle(), "alo");
}
I want to get all RSSModel from TABLE_NAME but it's always return null
public List<RSSModel> getAll(String TABLE_NAME) {
List<RSSModel> rssModelList = new ArrayList<>();
DatabaseReference databaseReference = database.getReference(TABLE_NAME);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot: snapshot.getChildren()) {
Log.d("alo " + dataSnapshot.getValue(), "alo");
rssModelList.add(dataSnapshot.getValue(RSSModel.class));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
return rssModelList;
}
Hope that you can help me with this. Thank in advance!
You're writing to a structure:
/$uid/TABLE_NAME/rssTitle
And then you're reading from: database.getReference(TABLE_NAME)
There is no node /TABLE_NAME, so this read will indeed lead to a non-existing snapshot.
If you want to read the data for a specific user, you will need to specify their UID similar to how you do when writing.
If you want to read the data for all users, you'll need to read from the root (database.getReference()) and then loop over snapshot.getChildren() for the user, and then read the TABLE_NAME (dataSnapshot.child(TABLE_NAME)).
I'm new to Firebase I wanted to know is there a way to only get the value of first child and insert it into my spinner in android. Ex:
Just like the image shown I wanted to retrieve only the name "slot x" instead of getting all the values of it. Is it possible to do so?
Sure thing, you can order and limit the number of child nodes retrieved with something like this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference myRef = rootRef.child("path to your parent node");
Query query = myRef.orderByKey().limiToFirst(1);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
String key = childSnapshot.getKey(); // "slot 1"
String status = childSnapshot.child("status").getValue(String.class); // "occupied"
...
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
The comment section of my application is not working properly, the childs are mixing up by their names and the timestamp, the content inside of them it is in correct order, here are all of my code inside Pastebin links (if necessary to see the whole code), also I provided the chunks I think that the problem is in.
1) CommentAdapter.java Activity (https://pastebin.com/m7LHDUDF)
Take note of this block of code:
private void getHandleName(final ViewHolder viewHolder) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Log.d(TAG, "getHandleName: checking comment userID" + viewHolder.comment.getUser_id());
Query query;
query = reference
.child("data")
.child("-Kxzyb5JsUPhsMQAb84X")
.child("users")
.orderByChild("user_id")
.equalTo(viewHolder.comment.getUser_id());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()) {
viewHolder.handleName.setText(singleSnapshot.getValue(User.class).getHandlename());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
2) CommentRecylerViewAdapter (https://pastebin.com/Tb7L9EVD)
private void getHandleName(final CommentViewHolder viewHolder, Comment comment) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Log.d(TAG, "getHandleName: checking comment userID" + comment.getUser_id());
Query query = reference
.child("data")
.child("-Kxzyb5JsUPhsMQAb84X")
.child("users")
.orderByChild("user_id")
.equalTo(comment.getUser_id());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()) {
viewHolder.handleName.setText(singleSnapshot.getValue(User.class).getHandlename());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
3)Chunk of code for adding the comment:
` private void addComment() {
if (commentText.getText().toString().isEmpty()) {
Toast.makeText(ViewPostActivity.this, "Please enter your comment", Toast.LENGTH_SHORT).show();
} else {
String currentUserID = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
String commentID = reference.push().getKey();
Comment comment = new Comment();
comment.setCaption(commentText.getText().toString());
comment.setDate_created(System.currentTimeMillis());
comment.setUser_id(currentUserID);
reference.child("data").child("-Kxzyb5JsUPhsMQAb84X").child("comments").child(postID).child(commentID).setValue(comment);
setNumComment();
setNumPointCurrentUser();
setNumPointUser();
setNumPointPost();
}
}`
4) **And Finally, the comment model Activity** which I think is ok(https://pastebin.com/VaYV3Gv3)
Here is a screenshot of my database:
-Kxzyb5JsUPhsMQAb84X is the root of my database
comments is where all the comments are store per post
-LSv6lXZml-Cf0GX3i5q randomly generated child that stores the other content such as Timestamps,user id and content
Here is the screenshot of my phone showing the incorrect order of the comments:
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 want to get item in the last node added in firebase database from my Android. You can see on the image below i'm not sure how to get the specific node, because unique key is created by Firebase. How to reference to auto-created node and child inside? Thanks a lot
The last node
Try this:
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
Query lastQuery = databaseReference.child("mp").orderByKey().limitToLast(1);
lastQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String message = dataSnapshot.child("message").getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Handle possible errors.
}
});
Hope this helps!
This might work:
DatabaseReference db = FirebaseDatabase.getInstance().getReference().child("mp");
Query query = db.orderByKey().limitToLast(1);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
Log.d("User key", child.getKey());
Log.d("User val", child.child("message").getValue().toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// TODO: Handle errors.
}
});
I prefer to write and retrieve data through objects.
MyObject is POJO.
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
MyObject myObject = data.getValue(MyObject.class);
Log.i(TAG, data.getKey() + " = " + myObject.toString());
}
}
console.log('last messages', messages[messages.length-1]);