Firebase-Android function should work but isn't [duplicate] - java

This question already has answers here:
How to return DataSnapshot value as a result of a method?
(6 answers)
getContactsFromFirebase() method return an empty list
(1 answer)
Closed 7 months ago.
For some reason, the following function always returns 0. Does someone know why?
public int GetOnlineFriendsNum(){
OnlineFriendsCounter = 0;
database.getReference().child("users").child(mAuth.getCurrentUser().getPhoneNumber()).child("Friends").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot snap : snapshot.getChildren()) {
String friend = snap.getValue().toString();
database.getReference().child("users").child(friend).child("IsHome").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapboolean) {
if((boolean)snapboolean.getValue()){
OnlineFriendsCounter++;
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
});
return OnlineFriendsCounter;
}
I added a firebase tree image^^

No need for another value change event,
You can convert it to your model directly or parse using map.
for (DataSnapshot snap : snapshot.getChildren()) {
HasMap<String,Object> friends = snap.getValue();
for (String mobileNumber : friends .keySet())
{
HasMap<Strin,Object> friend = friends.get(mobileNumber);
if(friend.get("IsHome").toString().equals("true"))
{
OnlineFriendsCounter++;
}
}
}

Related

How can I get to the end of a specific child which has different edited key

Example Data Model:
I am trying to get the position of the child so that every time I click the items, I can edit the data. I am using a Recycler Adapter by the way.
How can I get to the end of a specific child which has different edited key?
mDatabaseReferenceAttendance = FirebaseDatabase.getInstance().getReference("Attendance").child("Record");
mDatabaseReferenceAttendance.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
for(DataSnapshot dataSnapshot : snapshot.getChildren()){
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Your code reads all data under Attendance/Record. If you want to show the data for John-Smith on April 10, 2022-test (and similar nodes), you can loop over the extra levels in your JSON with:
mDatabaseReferenceAttendance = FirebaseDatabase.getInstance().getReference("Attendance").child("Record");
mDatabaseReferenceAttendance.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for(DataSnapshot dateSnapshot : snapshot.getChildren()){
for(DataSnapshot userSnapshot : dateSnapshot.getChildren()){
System.out.println(userSnapshot.getKey()); // "John-Smith"
System.out.println(userSnapshot.child("description").getValue(String.class)); // "test"
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // never ignore errors
}
});

Unable to set an ArrayList's value when populated from a database

ccontacts = new ArrayList<>();
DatabaseReference dbGelenler = db.getReference("Filmler");
dbGelenler.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot gelenler:dataSnapshot.getChildren()){
ccontacts.add(new Data(gelenler.getValue(Film.class).getAciklama(),gelenler.getValue(Film.class).getBen(),gelenler.getValue(Film.class).getImdb(),gelenler.getValue(Film.class).getIsim(),gelenler.getValue(Film.class).getIzlemeLinki(),gelenler.getValue(Film.class).getKategori(),gelenler.getValue(Film.class).getNe(),gelenler.getValue(Film.class).getService(),gelenler.getValue(Film.class).getTrailer(),gelenler.getValue(Film.class).getUrl(),gelenler.getValue(Film.class).getWhat(),gelenler.getValue(Film.class).getYear()));
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
for (Data d:ccontacts){
b.setText(d.getIsim());
}
When I directly set the text via gelenler.getValue() it works, however when I want to populate an ArrayList with this information it fails and receives null. Any help would be appreciated.

I want to get data object from firebase databse but the dbReference.addValueEventListener won`t execute [duplicate]

This question already has an answer here:
getContactsFromFirebase() method return an empty list
(1 answer)
Closed 3 years ago.
private Firebase_Database DbOnline;
ArrayList<ClassModel> clsList;
clsList = DbOnline.getClassesList();//return arraylist containing objects ...
//Implementation of getClassesList() in Firebase_Database CLASS..
public ArrayList<ClassModel> getClassesList(){//upto to this every thing execute but from here the //execution jumps to if(condition) line below...and I get null arraylist in return
FbDb.child("Classes").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds: dataSnapshot.getChildren())
{
ClassModel classModel = ds.getValue(ClassModel.class);
classModels.add(classModel);
Log.i("Tag", "Msg");
}
Log.i("Tag", String.valueOf(classModels.size()));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
if (classModels==null){
Log.i("TAG","Null NO DATA IN DATABASE");
}
return classModels;
}
Operation to firebase is asynchronous. so you have to wait to get data. You can use LiveData and observe it to get updated content. Check below:
private MutableLiveData<ArrayList<ClassModel>> mutableClassModels = new MutableLiveData<>();
private ArrayList<ClassModel> classModels = new ArrayList<>();
public MutableLiveData<ArrayList<ClassModel>> getClassesList(){//upto to this every thing execute but from here the //execution jumps to if(condition) line below...and I get null arraylist in return
FbDb.child("Classes").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds: dataSnapshot.getChildren())
{
ClassModel classModel = ds.getValue(ClassModel.class);
classModels.add(classModel);
Log.i("Tag", "Msg");
}
mutableClassModels.postValue(classModels);
Log.i("Tag", String.valueOf(classModels.size()));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return mutableClassModels;
}
And then observe it like below:
DbOnline.getClassesList().observe(this, new Observer<ArrayList<ClassModel>>() {
#Override
public void onChanged(ArrayList<ClassModel> classModels) {
// Do your operation here
}
});
Update:
Update your adapter like below:
//Initialize it, as it causing NullPointerException
ArrayList<ClassModel> clsList = new ArrayList<>();
public Adapter(Context context, String name) {
...
DbOnline=new Firebase_Database();
if (fragName.equals(listForClasses)) {
DbOnline.getClassesList().observe((LifecycleOwner) context, new Observer<ArrayList<ClassModel>>() {
#Override
public void onChanged(ArrayList<ClassModel> classModels) {
clsList =classModels;
clsList.size();
//Notify to refresh the items
notifyDataSetChanged();
}
});
} else {
sList = null;//DbOffline.getStudentsList("");
}
}

How to check if a value exists in firebase [duplicate]

This question already has answers here:
How to return DataSnapshot value as a result of a method?
(6 answers)
Closed 4 years ago.
before reading I'm a newbie trying to learn android development so don't go hard on me, please.
I have this Realtime database firebase :
I'm trying to check if the entered email exists , i've tried a method but it did not work out for me.
I tried this method :
private boolean checkIfExistes() {
reference.child("Users").orderByChild("email").equalTo(Email.getText().toString()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
CheckExists =true;
else
CheckExists =false;
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
if (CheckExists)
return true;
else
return false;
}
it always returns false though even if the email exists. Help please.
Try this:
boolean CheckExists =false; //declare and assign default value in global scope
reference.child("Users").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> userChildren = dataSnapshot.getChildren();
for (DataSnapshot user: userChildren) {
User u = user.getValue(User.class); //make a model User with necessary fields
if(u.email.equalsIgnoreCase(Email.getText().toString())){
CheckExists =true;
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
private DatabaseReference rootRef,userRef;
get the initialize firebase in oncreare method
rootRef = FirebaseDatabase.getInstance().getReference();
userRef = rootRef.child("Users");
here the code for checking email exist or not
userRef.orderByChild("email").equalTo(emailEdt.getText().toString())
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
hideProgress();
if (dataSnapshot.exists()){
Toast.makeText(LoginActivity.this,"User already exists",Toast.LENGTH_SHORT).show();
}else {
UserLogin user = new UserLogin(emailEdt.getText().toString(),profilePath);
DatabaseReference db = userRef.push();
db.setValue(user);
//Log.d(TAG,"user key is::: "+db.getKey());
prefs.savEmail(emailEdt.getText().toString());
prefs.savProfileUrl(profilePath);
prefs.savKey(db.getKey());
openMainActivity();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
hideProgress();
Toast.makeText(LoginActivity.this,databaseError.getMessage(),Toast.LENGTH_SHORT).show();
}
});

Check firebase database data is retrieved [duplicate]

This question already has an answer here:
Determining if Firebase didn't download data with startAt and endAT
(1 answer)
Closed 4 years ago.
I wanna know if Firebase data is retrieved.
For example:
database.child("name").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String name = dataSnapshot.getValue().toString();
//if(data.isdownloaded){Send data to another fragment via bundle}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Is there any complete listener for this?
you can add a if statement inside the onDataChange() if you data is retrieved that true will be pass to if as code below
database.child("name").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChildren()) // add this if statement
{
............ rest of the code
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Hope this is helping

Categories

Resources