im trying to get the count of all childs with a specific value.
users.orderByChild("isOnline").equalTo("1").
addListenerForSingleValueEvent(
new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot p1)
{
t(""+p1.getChildrenCount());
}
#Override
public void onCancelled(DatabaseError p1)
{
}
});
but the problem is there is a unique child among each users and isOnline childs.
The values of your isOnline node are numbers, so you need to compare them to a number foo:
users.orderByChild("isOnline").equalTo(1)...
Related
How to access a child inside real time database array child?
String count = item_count.getText().toString();
firebaseDatabase = FirebaseDatabase.getInstance();
reference = firebaseDatabase.getReference()
reference.child("beverages").child(????)
.child("item_count").setValue(count);
this is my code but I don't know what should I put in the question
marks.
]1
You can get the item_count by using foreach loop inside the onDataChange method.
Lets say this is your model class for your Beverage.
public class Beverage {
private long item_count;
private String item_img;
private String item_name;
public Beverage beverage(long itemCount){
this.item_count = itemCount;
//and do others also...
}
//Here your get set...
}
Here you get the data as arrayList
reference.child("beverages").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
ArrayList<Beverage> beveragesList = new ArrayList<Beverage>();
//Get children
for (DataSnapshot snapShot : dataSnapshot.getChildren()) {
if (snapShot.exists()) {
final Beverage beverage = snapShot.getValue(Beverage.class);
if (beverage != null){
//Her you got the data as array list
beverageList.add(beverage);
}
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.i("???","Db error: " + databaseError.getMessage());
}
});
You need to put child of beverages here like 0,1,2, or 3.
reference.child("beverages").child("3").child("item_count").setValue(count);
I am working on Firebase database. How can I retrieve values from database based on email entered by user in text field. Below is my database structure. Kindly help.
Here is my code:
Ref = database.getReference("Registeration");
Ref.orderByChild("UserRegistration/email").equalTo(emailval).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
user_reg user=dataSnapshot.getValue(user_reg.class);
Toast.makeText(getApplicationContext(), user.toString(), Toast.LENGTH_SHORT).show();
}
You have:
Registration
UserRegistration
12
pushid
key:values
email:emailvalue
To retrieve values always you have to go from top to bottom, so you cannot skip any node.
Only orderByChild(..) query can skip one node (which means you use this query if you want to get children that are not direct children)
Try this:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("Registration").child("UserRegistration").child("12");
ref.orderByChild("email").equalTo(emailenteredbyuser).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot datas : dataSnapshot.getChildren()) {
String email=datas.child("email").getValue().toString();
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
As you can see in the above, the reference passes through every node until node 12.
Then you use this orderByChild("email").equalTo(emailenteredbyuser) to get the email entered by the user.
for (DataSnapshot datas : dataSnapshot.getChildren()) this for loop the datas iterates in inside the direct children of 12 which is the pushid that way you do not need to retrieve the pushid to get the values inside of it.
Try this! here I am running for each loop to get each child.
Ref.child("UserRegistration").child("email").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot:dataSnapshot.getChildren()){
user_reg user=dataSnapshot.getValue(user_reg.class);
System.out.println(user.email);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I have a problem with firebase pagination.
I have table posts and this is an example structure:
and I want to get only 10 post every time, here is my code page is 0:
#NonNull
#CheckResult
public Single<DataSnapshot> getData(#NonNull DatabaseReference ref, int page) {
return Single.create(emitter -> {
ref.orderByChild("timestamp")
.startAt(page * 10)
.limitToFirst(10);
final ValueEventListener listener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!emitter.isDisposed()) {
emitter.onSuccess(dataSnapshot);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
if (!emitter.isDisposed()) {
emitter.onError(databaseError.toException());
}
}
};
ref.addListenerForSingleValueEvent(listener);
});
}
and here is the result
Why I have list size equals 20 not 10? p.s. limit to first or limit to last it's no difference with the result
Calling startAt(), limitToFirst() and similar methods on a DatabaseReference returns a new Query object. You need to keep a reference to that Query and attach your listeners to that:
Query query = ref.orderByChild("timestamp")
.startAt(page * 10)
.limitToFirst(10);
query.addListenerForSingleValueEvent(listener);
The method below is the method I am using to populate my array. However I wish to return a random deals_informationobject from my ArrayList of type Deals_Information but am not quite sure how.
public void populateArray() {
databaseReference.child("FruitDeals").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> children = dataSnapshot.getChildren();
final ArrayList<Deals_Information> myArray = new ArrayList<>();
for (DataSnapshot child : children) {
Deals_Information deals_information = child.getValue(Deals_Information.class);
myArray.add(deals_information);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Use Random to get a random int from the range of 0 and the size-1 of your collection.
Since Java 1.7, the recommended Random implementation is ThreadLocalRandom.
private int randomInt(final int from, final int to) {
return ThreadLocalRandom.current().nextInt(from, to);
}
Because ArrayLists have a get() function, the way to do this is to first generate a random number by using the math.random() function, and then use the get() function of your ArrayList to call the object at that randomly generated index.
I am writing an android app and I want to check if a key exists in order to avoid duplicate values. I´ve been investigating but it looks that all I can add is listeners, when I just want to check if an ID exists or not already.
Taking this SO question as an example, I would like to know if -JlvccKbEAyoLL9dc9_v exists. How can I do this?
Thanks in advance.
The approach will always be similar to what I wrote in this answer about JavaScript: Test if a data exist in Firebase
ref.child("-JlvccKbEAyoLL9dc9_v").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.exists()) {
// TODO: handle the case where the data already exists
}
else {
// TODO: handle the case where the data does not yet exist
}
}
#Override
public void onCancelled(FirebaseError firebaseError) { }
});
But keep in mind that push ids in Firebase exist to prevent having to do this sort of check. When multiple clients generate push ids, they are statistically guaranteed to be unique. So there's no way one of them can create the same key as another.
Any case where you need to check if an item already exists is likely to have race conditions: if two clients perform this check almost at the same time, neither of them will find a value.
RxJava 2 :
public static Observable<Boolean> observeExistsSingle(final DatabaseReference ref) {
return Observable.create(emitter ->
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
emitter.onNext(dataSnapshot.exists());
emitter.onComplete();
}
#Override
public void onCancelled(DatabaseError databaseError) {
emitter.onError(databaseError.toException());
}
}));
}
Usage:
public Observable<Boolean> isYourObjectExists(String uid) {
return observeExistsSingle(databaseReference.child(uid));
}
In your class:
yourRepo.isYourObjectExists("-JlvccKbEAyoLL9dc9_v")
.subscribe(isExists -> {}, Throwable::printStackTrace);
Based on #Frank van Puffelen's answer, here's a few lines to see if a ref - itself - exists before using it.
public void saveIfRefIsAbsent(DatabaseReference firebaseRef) {
DatabaseReference parentRef = firebaseRef.getParent();
String refString = firebaseRef.toString();
int lastSlashIndex = refString.lastIndexOf('/');
String refKey = refString.substring(lastSlashIndex + 1);
parentRef.child(refKey).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.exists()) {
// TODO: handle the case where the data already exists
}
else {
// TODO: handle the case where the data does not yet exist
}
}
#Override
public void onCancelled(FirebaseError firebaseError) { }
});
}
In my case I have a Util to create the schema programmatically. I use this in order to add new data without overwriting existing data.