-1

I have this problem, that I cannot get single value from my firebase json and check it if it is null or not.

Here is my json file:

{ "117500978158564407389": 
   {
    "uid" : "117500978158564407389",
    "cat_list" : {
    "category_list" : [ {
      "cat_name" : "Work"
    }, {
      "cat_name" : "Health"
    }, {
      "cat_name" : "Food"
    }, {
      "cat_name" : "Spare time"
    }, {
      "cat_name" : "Travel"
    } ]
    }
    }
    }

Here is my code in Presenter of MVP where i try to get value of my "uid" in json. But it always shows a null.

@Override
public String getId(String id) {     
    reference = FirebaseDatabase.getInstance().getReferenceFromUrl("https://talisproject-89e62.firebaseio.com/userData/");
    reference.child("117500978158564407389").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            CategoryList categoryList = dataSnapshot.getValue(CategoryList.class);
            ID = categoryList.getUid();

        }
        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    return ID;
}
}

Here is my POJO class

public class CategoryList implements Serializable {
public List<Category> categoryList;


public List<Category> getCategoryList() {
    return categoryList;
}

public void setCategoryList(List<Category> categoryList) {
    this.categoryList = categoryList;
}

public CategoryList catList;
public String uid;

public String getUid() {
    return uid;
}

public void setUid(String uid) {
    this.uid = uid;
}

public CategoryList(CategoryList catList, String uid) {

    this.catList = catList;
    this.uid = uid;
}

}

And Here where I call my Presenter function, it always shows a null. Does anyone knows, why it always shows a null and how can I get this value?

ID = interPresenter.getId(uid);
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 4
    *Does anyone knows, why it always shows a null* ... I know ... firebase is async http://ideone.com/PPHi95 ... obviously `return ID;` appear before listener hits `onDataChange` – Selvin Dec 01 '16 at 11:15

1 Answers1

2

Firebase doesn't get the data immediately, obviously... It needs to download data.

onDataChange is called when the data is downloaded. When you did return ID, ID is null since onDataChange hasn't been called yet. It's simply logic.

See How to return the value from inner class to outer class?

Community
  • 1
  • 1
Ali Bdeir
  • 4,151
  • 10
  • 57
  • 117