Firebase Retrieving data always null - android

I am using this method to retrieve data on Android, and it always returns null. Inside the ondatachange the listFinalBus is not null, but when the return comes, I get a null value.
Here is my code:
public List<Bus> findAllBus() {
// Read from the database
myRef.child("Bus").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG, "onDataChange: " + dataSnapshot.toString());
for (DataSnapshot userDataSnapshot : dataSnapshot.getChildren()) {
Bus bus = userDataSnapshot.getValue(Bus.class);
Log.d(TAG, "onDataChange: after get value " + bus.getId().toString()+" nom "+bus.getNom().toString());
listFinalBus.add(bus);
Log.d(TAG, "onDataChange: list before return not null her" + listFinalBus.size());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Log.d(TAG, "onDataChange: list firas return" + listFinalBus.size());
//return is null
return listFinalBus;
}

Your .addValueEventListener(listener) works async. So you will return your field fisrt which is null and after the call is done, your listener get called. But your field is already returned.
So to fix this, whether you write your own listener like:
interface MyCallback{
void onSuccess(List<Bus> bus)
}
and your code could be like:
public void findAllBus(MyCallback callback) {
// Read from the database
myRef.child("Bus").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG, "onDataChange: " + dataSnapshot.toString());
for (DataSnapshot userDataSnapshot : dataSnapshot.getChildren()) {
Bus bus = userDataSnapshot.getValue(Bus.class);
Log.d(TAG, "onDataChange: after get value " + bus.getId().toString()+" nom "+bus.getNom().toString());
listFinalBus.add(bus);
Log.d(TAG, "onDataChange: list before return not null her" + listFinalBus.size());
}
callback.onSuccess(List<Bus> bus);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
So you can get your List no matter where you like.And just implements the Callback and pass it to your repository.
Or if you familiar with RxJava. You can pass an Observable which gonna like
public Observable<Bus> findAllBus(){
return Observable.create(new ObservableOnSubscribe<Bus>() {
#Override
public void subscribe(ObservableEmitter<Bus> e) throws Exception {
myRef.child("Bus").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG, "onDataChange: " + dataSnapshot.toString());
for (DataSnapshot userDataSnapshot : dataSnapshot.getChildren()) {
Bus bus = userDataSnapshot.getValue(Bus.class);
Log.d(TAG, "onDataChange: after get value " + bus.getId().toString()+" nom "+bus.getNom().toString());
e.onNext(bus);
Log.d(TAG, "onDataChange: list before return not null her" + listFinalBus.size());
}
e.onComplete();
}
#Override
public void onCancelled(DatabaseError databaseError) {
e.onError(error);
}
}
});
}

Related

how to fix dataSnapshot.getValue() retrieves null?

Okay so I am trying to pull from my database the email of a single user under the userID, and it retrieves null.
The userUID is authUID.
My Database structure
When I change the line to :
String value = dataSnapshot.child("email").getKey();
it retrieves the right key so I am standing on the right position of the database as far as I understand.
myDatabaseRef.child(userUID).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
try{
String value = dataSnapshot.child("email").getValue(String.class);
//String value = dataSnapshot.child("email").getKey(); gets email
Log.d("TAG", "onDataChange: " + value);
}
catch (Exception ex){
Log.d("PROBLEM",ex.toString());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
The error that I get:
2019-07-30 10:42:29.566 14673-14673/com.example.h210.housecommitteemanage D/TAG: onDataChange: null
Try this, below code will fetch emails of all the users :
FirebaseDatabase.getInstance().getReference("DataUsers").child("Users").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
try{
Iterable<DataSnapshot> snapshotIterable = dataSnapshot.getChildren();
for (DataSnapshot aSnapshotIterable : snapshotIterable) {
String value = aSnapshotIterable.child("email").getValue(String.class);
Log.e(Constants.TAG, "Users email : " + value);
}
}catch (Exception ex){
Log.e("PROBLEM",ex.toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Android Retrieving Single Value from FireBase-RealTime Database

Answer needed urgently. I'm trying to retrieve a single value school name as marked in the snapshot attached below and populate it to my android spinner from my firebase-database
private class FireBaseConnection{
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference rootRef = database.getReference().child("root");
DatabaseReference reg_schools = rootRef.child("reg_schools");
}
private ArrayList<String> retrieveAllSchools(){
pBar.setMessage("Please Wait..Retrieving Schools...");
pBar.show();
FireBaseConnection fireBaseConnection = new FireBaseConnection();
String key = fireBaseConnection.reg_schools.push().getKey();
fireBaseConnection.reg_schools.child(key).child("school_name").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
resultProcessorObject = snapshot.getValue(SchoolObject.class);
schools_retrieved = resultProcessorObject.getSchool_name();
schools.add( schools_retrieved);
//schools = (ArrayList<Object>) snapshot.getValue();
// Toast.makeText(Main2Activity.this, "Schools are : " + schools, Toast.LENGTH_SHORT).show();
}
Toast.makeText(Main2Activity.this, "Schools are : " + schools, Toast.LENGTH_SHORT).show();
pBar.dismiss();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return schools;
}
So I want to answer my question..I made it work with the help of #Alex Mamo video
so everything remained unchanged..all i did was tweak my code a bit
Instead of
fireBaseConnection.reg_schools.child(key).child("school_name").addValueEventListener(){
//Then my codes here
}
Instead i did
fireBaseConnection.reg_schools.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
resultProcessorObject = snapshot.child("school_name").getValue(String.class);
//schools_retreived = resultProcessorObject.getSchool_name();
schools.add(resultProcessorObject);
count = dataSnapshot.getChildrenCount();
Toast.makeText(Main2Activity.this, "Total number of " + count + " schools were retreived ", Toast.LENGTH_SHORT).show();
// schools = (ArrayList<Object>) snapshot.getValue();
// Toast.makeText(Main2Activity.this, "Schools are : " + schools, Toast.LENGTH_SHORT).show();
}
Toast.makeText(Main2Activity.this, "Schools are : " + schools, Toast.LENGTH_SHORT).show();
pBar.dismiss();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
So Basically i used the snapshot to reference the node "school_name" i'm looking for in the onDataChange Method

How to show an error message when email val is not available in firebase database

My Firebase Database is look like as bellow:
I want to show an error message when email val is not available in firebase database.
And my code is
mRef.orderByChild("email").equalTo(val).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
User user = dataSnapshot.getValue(User.class);
textView.setText("Welcome " + user.name );
System.out.println(user.name + "\n" + user.email + "\n" + user.tell);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
User user = dataSnapshot.getValue(User.class);
textView.setText("Welcome " + user.name );
System.out.println(user.name + "\n" + user.email + "\n" + user.tell);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
A ChildEventListener can only detect the presence of a certain child node or when a child node is changed/removed. It cannot detect the absence of a child. To detect that there is no value, you need a ValueEventListener:
mRef.orderByChild("email").equalTo(val).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getChildrenCount() == 0) {
System.out.println("No user with email "+val);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
throw firebaseError.toException(); // don't ignore onCancelled!
}
});
mQuery = databaseReference.limitToLast(1).orderByChild("email").equalTo(category);
mQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i(TAG, "onDataChange: "+dataSnapshot.toString());
GenericTypeIndicator<Map<String,UserModel>> t=new GenericTypeIndicator<Map<String,UserModel>>(){};
try{
Map<String,UserModel> userList=dataSnapshot.getValue(t);
}catch(Exception exception){
//Error UserInfo not present in firebase
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
//Error wile accessing database
}
});

How to get nested Child from Firebase Database Using Android?

I want to get list of all Allowed child from this type of JSON Tree:
databaseRef.child('Users').child('Allowded').addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange (DataSnapshot dataSnapshot) {
//
}
}
#Override
public void onCancelled (DatabaseError databaseError) {
} };);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference userRef = database.getReference("users").child(key).child("Alloweded");
ValueEventListener postListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User userObj = dataSnapshot.getValue(User.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// ...
}
};userRef.addValueEventListener(postListener);
User is your Model class which have lat, lng, name,no., profileUrl etc
Try this I hope it works fine.
Firebase listeners fire for both the initial data and any changes.
If you're looking to synchronize the data in a collection, use ChildEventListener. If you're looking to synchronize a single object, use ValueEventListener. Note that in both cases you're not "getting" the data. You're synchronizing it, which means that the callback may be invoked multiple times: for the initial data and whenever the data gets updated.
FirebaseRef.child("message").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
System.out.println(snapshot.getValue()); //prints "Do you have data? You'll
love Firebase."
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
databaseRef.child('Users').child('Allowded').addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange (DataSnapshot dataSnapshot) {
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
Log.d(TAG, "onDataChange: 1 " + childDataSnapshot.getKey());
for (DataSnapshot childDataSnapshot2 : childDataSnapshot.getChildren()){
Log.d(TAG, "onDataChange: 2 " + childDataSnapshot2.getKey());
}
}
}
}
#Override
public void onCancelled (DatabaseError databaseError) {
} };);

How to check if firebase query is empty

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();
}
});

Categories

Resources