DatabaseReference newReferance = database.getReference().child("Users");
Query query = newReferance.orderByChild("timestamp");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
chatMessages.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
HashMap<String, String> hashMap = (HashMap<String, String>) dataSnapshot1.getValue();
//String userMail = hashMap.get("useremail");
String userMessage = hashMap.get("usermessage");
String userCt = hashMap.get("usershow");
chatMessages.add(userCt + ": " + userMessage);
if (chatMessages.size() >= 10){
for (int i= 0; i < 5; i++){
//HOW ????
}
}
recyclerAdapter.notifyDataSetChanged();
}
}
Hi Dear guys. How do I select and delete the first 5 data in a real-time database? When the ArrayList reaches a certain limit, I want to delete the first 5 data from the database. I'd appreciate it if you could help with the problem.
How do I select and delete the first 5 data in a real-time database?
You can achieve this using Firebase Query's limitToFirst(int limit):
Create a query with limit and anchor it to the start of the window
And in code should look like this:
Query query = newReferance.orderByChild("timestamp").limitToFirst(5);
See I have used this limitToFirst() method that can help you find the first 5 items. To delete them, just attach a listener and inside the onDataChange() method use the following line of code:
dataSnapshot.getRef().removeValue();
final DatabaseReference newReferance = database.getReference().child("Users");
final Query query = newReferance.orderByChild("timestamp");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
chatMessages.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
HashMap<String, String> hashMap = (HashMap<String, String>) dataSnapshot1.getValue();
//String userMail = hashMap.get("useremail");
String userMessage = hashMap.get("usermessage");
String userCt = hashMap.get("usershow");
chatMessages.add(userCt + ": " + userMessage);
if (chatMessages.size() >= 10){
Query query1 = newReferance.limitToFirst(5);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
database.getReference().child("Users").setValue(null);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
recyclerAdapter.notifyDataSetChanged();
}
}
Although I'm set, it's all deleted. I can't erase the items I want. All cleared.
rootRef is the firebase database reference. whose instance we have to gained before trying to delete any value. you can see the code given below.
count = 0;
rootRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
CommonLocationClass user = postSnapshot.getValue(CommonLocationClass.class);
if (count < 5) {
rootRef.child(user.getPhNo).removeValue();
count++;
}
}
}
}
#Override
public void onCancelled (DatabaseError firebaseError){
}
});
the CommonLocationClass is a getter setter model class i have made to make the fire-base implementation easy
you can try this it works for me
public void getDataFirebase() {
/*if (chatMessages.size() == MAX_MSJ_LIMIT){
database.getReference().child("Users").removeValue();
}*/
final DatabaseReference newRefere = database.getReference().child("Users");
Query query = newRefere.orderByChild("timestamp");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
chatMessages.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
HashMap<String, String> hashMap = (HashMap<String, String>) dataSnapshot1.getValue();
//String userMail = hashMap.get("useremail");
String userMessage = hashMap.get("usermessage");
String userCt = hashMap.get("usershow");
chatMessages.add(userCt + ": " + userMessage);
recyclerAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
if (chatMessages.size() >= 10) {
Query query1 = newRefere.orderByChild("timestamp").limitToFirst(5);
query1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
dataSnapshot.getRef().removeValue();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
It didn't just erase the first 5 data.
if (chatMessages.size() >= 10) {
Query query1 = newRefere.orderByChild("timestamp").limitToFirst(5);
query1.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()){
ds.getRef().removeValue();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I solved the problem. With this code
Related
I am trying to query my Messages table for three things. The first is any messages with that involve the current user logged in. Then, I want to get the user id of the person the current user has a coversation with. And finally, I want to check if any of the messages were seen. But right now my query only runs the first and last queries and not the second one. But I don't know why.
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userMessageKeyRef = dbRef.child("Messages").child(firebaseUser.getUid());
userMessageKeyRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot snapshot1 : snapshot.getChildren()) {
String messageToID = snapshot1.getKey();
DatabaseReference messageRef = dbRef.child("Messages").child(firebaseUser.getUid()).child(messageToID);
Query query = messageRef.orderByChild("to").equalTo(firebaseUser.getUid());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
long count = dataSnapshot.getChildrenCount();
if (dataSnapshot.exists()) {
DatabaseReference messageKeyRef = dbRef.child("Messages").child(firebaseUser.getUid()).child(messageToID);
Query query2 = messageKeyRef.orderByChild("isSeen").equalTo(false);
query2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataShot) {
if (dataShot.exists() && count > 0) {
//Log.d("TAG2", "count if: " + count2);
messages_text.setText("" + Math.toIntExact(count));
messages_text.setVisibility(View.VISIBLE);
} else {
messages_text.setVisibility(View.GONE);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
} else {
messages_text.setVisibility(View.GONE);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
//Log.d("TAG1", "User to: " + messageToID);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Your first addValueEventListener already loads all data for the current user, so there is no need to go back to the database to load that data again. Instead you should check the properties of each message in your application code with something like:
DatabaseReference userMessageKeyRef = dbRef.child("Messages").child(firebaseUser.getUid());
userMessageKeyRef.addValueEventListener(new ValueEventListener() {
for (DataSnapshot parentSnapshot : snapshot.getChildren()) {
for (DataSnapshot messageSnapshot : addValueEventListener.getChildren()) {
String messageToID = messageSnapshot.getKey();
String toValue = messageSnapshot.child("to").getValue(String.class);
Boolean isSeenValue = messageSnapshot.child("isSeen").getValue(Boolean.class);
if (toValue.equals(firebaseUser.getUid()) && isSeenValue == true) {
...
}
}
}
});
I'm using Firebase realtime database. Below is the structure
Problem Statement: Over a list of "Users", I need to delete child who's having coins = 0
So far I'm stuck here
DatabaseReference deleteRef = dbref.child("Users").child("coins");
Query deleteQuery = deleteRef.orderByValue().equalTo("0");
deleteQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
child.getRef().setValue(null);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
Any help will be appreciated :)
You need to order the list by the child coins like here:
DatabaseReference deleteRef = dbref.child("Users");
Query deleteQuery = deleteRef.orderByChild("coins").equalTo("0");
deleteQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
child.getRef().setValue(null);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
I want to read some specific child from the parent-child, by getchild() function but this will not work properly.
FirebaseUser FUser = mAuth.getCurrentUser();
String userid = FUser.getUid();
DatabaseReference DR;
DR = FirebaseDatabase.getInstance().getReference().child("HistoryTable").child(userid);
DR.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// Iterable<DataSnapshot> root = dataSnapshot.getChildren();
// Toast.makeText(getApplicationContext(), "ds "+dataSnapshot.getChildren(),Toast.LENGTH_LONG).show();
for (DataSnapshot ds: dataSnapshot.getChildren()) {
// Toast.makeText(getApplicationContext(), "ds "+ds,Toast.LENGTH_LONG).show();
for (DataSnapshot d: ds.getChildren()) {
String Height = d.getKey() + d.getValue() + "\n".toString();
String ch = d.child("1Height:").getValue(String.class);
// tv.append(Height);
tv.append(ch);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I want to get this four child from every key.
you have to add your push id in reference :-
DR = FirebaseDatabase.getInstance().getReference().child("HistoryTable").child(userid).child("push id");
DR.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// Iterable<DataSnapshot> root = dataSnapshot.getChildren();
// Toast.makeText(getApplicationContext(), "ds "+dataSnapshot.getChildren(),Toast.LENGTH_LONG).show();
for (DataSnapshot ds: dataSnapshot.getChildren()) {
// Toast.makeText(getApplicationContext(), "ds "+ds,Toast.LENGTH_LONG).show();
for (DataSnapshot d: ds.getChildren()) {
String Height = d.getKey() + d.getValue() + "\n".toString();
String ch = d.child("1Height:").getValue(String.class);
// tv.append(Height);
tv.append(ch);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Try like this if you just want to read the value. if you want to read data only once use addListenerForSingleValueEvent()
*Try to read values by object stucture https://firebase.google.com/docs/database/android/read-and-write#basic_write
DR.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot d: ds.getChildren()) {
//below line may cause null pointer Exception
String Height = d.getKey() + d.getValue() + "\n".toString();
if(d.child("1Height:").getValue()!=null){
String ch = d.child("1Height:").getValue(String.class);
//tv.append(Height);
tv.append(ch);}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
To get the value of your 4UserId property, simply use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("HistoryTable").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String userId = ds.child("4UserId").getValue(String.class);
Log.d(TAG, userId);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
The result in your logcat will be:
2Wwrjx...P2obFO83
The structure looks like this:
users
|----username1
|----uid:value
username2
|----uid:value
I'm trying to find the best way to get the username value based of the value of it's uid,
This need to be in Java code (Android), So far I found the following code:
Query uid = reference.child("users").orderByChild("uid").equalTo(uid);
uid.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String keys=datas.getKey();
if (keys.equals(uid)) {
// uid found
} else {
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Try this code and create a model class to fetch value of Uid
DatabaseReference users= FirebaseDatabase.getInstance().getReference().child("users");
users.orderByChild("uid").equalTo(uid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot post:dataSnapshot.getChildren()){
//Use a model class to fetch user id like below
UIDDetails u=post.getValue(UIDDetails.class);
String user_id=u.getUid();
//Here all values will be equal to youy required uid if exists more than one
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Please add below code into your file:
DatabaseReference users= FirebaseDatabase.getInstance().getReference().child("users");
final Query userQuery = users.orderByChild("uid");
userQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
map.clear();
if(child.getkey().toString().equalsIgnoreCase(uid)){
//Get the node from the datasnapshot
String myParentNode = dataSnapshot.getKey();
for (DataSnapshot child: dataSnapshot.getChildren())
{
String key = child.getKey().toString();
String value = child.getValue().toString();
map.put(key,value);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
databaseError.toException();
}
});
This is my firebase keyvalue image
This is my code:
Query query = myFirebaseRef.orderByChild("age");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot get1) {
for(DataSnapshot get2 : get1.getChildren()) {
User user = get2.getValue(User.class);
Log.d("FireBaseTraining", "age =" + user.getAge());
}
In short form:
I want to addition all age value
like this
20+18+19+20+70+....=Sum_age
How to revise the code?
Thanks for helping me.
Just get all the ages for user by loop, and sum all the ages.
FirebaseDatabase.getInstance().child("username").orderByChild("age").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int sum = 0;
for(DataSnapshot data : dataSnapshot.getChildren()){
User user = data.getValue(User.class);
sum = sum + user.getAge();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});