I just started to learn Android Studio, and I am trying to make a search activity that can search for a data from my firebase database. But whenever I try to search no result shows up on the screen and does not retrieve any data from the database. Can anyone solve the problem? Thanks.
private void searchForMatch(final String keyword) {
Log.d(TAG, "searchForMatch: searching for a match: " + keyword);
imageDTOs.clear();
if(keyword.length() == 0) {
} else {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("books").orderByChild("title").equalTo(keyword);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()) {
Log.d(TAG, "onDataChange: found book:" + singleSnapshot.getValue(ImageDTO.class).toString());
imageDTOs.add(singleSnapshot.getValue(ImageDTO.class));
}
searchAdapter = new SearchAdapter(SearchActivity.this, R.layout.item_library, imageDTOs);
listView.setAdapter(searchAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
Related
I am developing an android application and now I am stuck in retrieving data from particular nodes like I want to retrieve only one value from each nodes. The database structure shows below.
How can I retrieve the second unique id that created by Firebase database?
First create a POJO class to get the values you want, it should be writen the same way as you have them in Firebase.
public class AppointmentsPojo {
private String appointmentStuts;
public AppointmentsPojo(){
}
public String getAppointmentStuts() {
return appointmentStuts;
}
public void setAppointmentStuts(String appointmentStuts) {
this.appointmentStuts = appointmentStuts;
}
}
Then just loop inside Appointments to get each appointmentStuts
mDatabase.child("Appointments").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Looping inside Appointments to get each appointmentsStuts
for(DataSnapshot snapshot: dataSnapshot.getChildren()){
AppointmentsPojo ap = snapshot.getValue(AppointmentsPojo.class);
//Getting each appointmentStuts
String appointmentStuts = ap.getAppointmentStuts();
//To get each father of those appointments
String key = snapshot.getKey();
Log.e("Data: " , "" + appointmentStuts );
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
Where mDatabase is
DatabaseReference mDatabase;
mDatabase = FirebaseDatabase.getInstance().getReference();
To get the value of appointmentStuts only from the first object, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("Appointments").child(PostKey).limitToFirst(1);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String appointmentStuts = ds.child("appointmentStuts").getValue(String.class);
Log.d(TAG, appointmentStuts);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
};
query.addListenerForSingleValueEvent(valueEventListener);
This question already has an answer here:
Order by date in negative timestamp is not working in Firebase
(1 answer)
Closed 4 years ago.
I am doing everything as per documentation but don't know why I am not getting ordered data
My Query
typeRef = myRef.child("DiscussionRooms").orderByChild("order");
valueEventListener = typeRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
Log.d(TAG, "Get Data" + dataSnapshot.getValue().toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
My Database
My Database Rules
Response Logs
To display the data ordered according to the order property, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference discussionRoomsRef = rootRef.child("DiscussionRooms");
Query orderQuery = discussionRoomsRef.orderByChild("order");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.child("name").getValue(String.class);
Log.d("TAG", name);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
}
};
orderQuery.addListenerForSingleValueEvent(valueEventListener);
I'm building a social app. I need to display friends posts in the main feed with firebase recycler adapter. I've tried many options but I'm not been able to do this, with the code below I'm only able to load posts of the current user. I'm pasting the code here please guide me in this regard.
I'm using 2 queries one for friends and other for posts
The two database references are as follows
mUsersPostsDatabase = FirebaseDatabase.getInstance().getReference().child("posts");
mFriendsDatabase= FirebaseDatabase.getInstance().getReference().child("Friends").child(current_user_id);
The method is as follows
#Override
protected void onStart() {
super.onStart();
Query posts = mUsersPostsDatabase
.orderByChild("user_id")
.equalTo(mFriendsDatabase.getKey());
FirebaseRecyclerAdapter<CurrentUserPosts, UsersViewHolder> firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter<CurrentUserPosts, UsersViewHolder>(
CurrentUserPosts.class,
R.layout.view_user_post_layout,
UsersViewHolder.class,
posts
) {
#Override
protected void populateViewHolder(UsersViewHolder usersViewHolder, CurrentUserPosts model, int position) {
usersViewHolder.setImage_url(model.getImage_url(), getApplicationContext());
usersViewHolder.setUser_image(model.getUser_image(), getApplicationContext());
usersViewHolder.setUser_name(model.getUser_name());
usersViewHolder.setDate_time(model.getDate_time());
usersViewHolder.setDescription(model.getDescription());
}
};
mUsersList.setAdapter(firebaseRecyclerAdapter);
}
The database node are like the following
Friends ---> current_user_id ----> friend_id
Posts ----> post_id ----> date, user_id, image_url, descp......
Query friends = FirebaseDatabase.getInstance().getReference().child("Friends").child(mAuth.getCurrentUser().getUid());
friends.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String friendID = ds.getRef().getKey().toString();
Query posts = FirebaseDatabase.getInstance().getReference()
.child("posts").orderByChild("user_id").equalTo(friendID);
posts.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()) {
CurrentUserPosts newPost = new CurrentUserPosts();
newPost.setImage_url(singleSnapshot.child("image_url").getValue(String.class));
mPosts.add(newPost);
}
Collections.reverse(mPosts);
mUsersList.setAdapter(new UsersPostsThumbAdapter(mPosts));
}
#Override
public void onCancelled(DatabaseError databaseError) {
String errormsg = databaseError.toString();
Toast.makeText(getApplicationContext(), errormsg, Toast.LENGTH_SHORT).show();
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
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]);
I want to delete the data from Firebase before unauthorizing. The problem is that mFirebaseRef.unauth() works only if query is not empty. But I need it to work even if query is empty.
final Firebase pushNotificationRef = new Firebase(Constant.FIREBASE_URL_PUSHNOTIFICATIONS);
final Query queryRef = pushNotificationRef.orderByChild("deviceToken").equalTo(token);
queryRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot.exists()) {
Log.e("MyTag", dataSnapshot.getKey());
pushNotificationRef.child(dataSnapshot.getKey()).removeValue();
}
mFirebaseRef.unauth();
}
use this...
if (dataSnapshot.exists())
// user found
else
// user not found
demo example
Query query = dbstud.child("users").orderByChild("name").equalTo("XYZ");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Toast.makeText(getApplicationContext(), "id = " + snapshot.getKey(), Toast.LENGTH_LONG).show();
}
}
else {
Toast.makeText(getApplicationContext(), "User Not found ", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});