I'm new to Firebase. I want to add Firebase specific data to my spinner. I view this content This help content, but I don't get it
i would like to fetch the username into my spinner.
My code
private void showdata()
{
spinnerRef.child("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for(DataSnapshot item:snapshot.getChildren())
{
spinnerList.add((item.child("username").getValue()).toString());
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
Related
I'm trying to get the count of "msanID" but it always returns the number as '0'. I'm using a separate class (ManageNodeName) to record the data and retrieving them back at list view.
I suspect the error is in the method of getting the String MSAN_NAMESP.
Any lead may help. Thanks!
List View
databaseNodes = FirebaseDatabase.getInstance().getReference("MSAN List");
#Override
protected void onStart() {
super.onStart();
databaseNodes.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
manageNodeList.clear();
for(DataSnapshot nodesnapshot: dataSnapshot.getChildren()){
progressDialog.dismiss();
ManageNodeName manageNodeName = nodesnapshot.getValue(ManageNodeName.class);
manageNodeList.add(manageNodeName);
MSAN_NAMESP = manageNodeName.getNodeID();
}
ManageNodeList adapter = new ManageNodeList(ManageSelectMSAN.this, manageNodeList);
manageListViewMSANs.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
query = FirebaseDatabase.getInstance().getReference("MSAN MTCE")
.orderByChild("msanID")
.equalTo(MSAN_NAMESP);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
int size = (int) dataSnapshot.getChildrenCount();
ManageNodeName.setCount(size);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
Data is loaded from Firebase (and most cloud APIs) asynchronously. While the data is being loaded, your main code continues to run, so that the user can continue to use the app. Then when the data is available, your onDataChange is called with that data.
This means that all code that needs the data, needs to either be inside onDataChange or be called from there.
So:
databaseNodes.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
manageNodeList.clear();
for(DataSnapshot nodesnapshot: dataSnapshot.getChildren()){
progressDialog.dismiss();
ManageNodeName manageNodeName = nodesnapshot.getValue(ManageNodeName.class);
manageNodeList.add(manageNodeName);
MSAN_NAMESP = manageNodeName.getNodeID();
query = FirebaseDatabase.getInstance().getReference("MSAN MTCE")
.orderByChild("msanID")
.equalTo(MSAN_NAMESP);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
int size = (int) dataSnapshot.getChildrenCount();
ManageNodeName.setCount(size);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException(); // never ignore errors
}
});
}
ManageNodeList adapter = new ManageNodeList(ManageSelectMSAN.this, manageNodeList);
manageListViewMSANs.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException(); // never ignore errors
}
});
Also see: getContactsFromFirebase() method return an empty list for a longer example, and alternative approaches.
I am creating an android app using firebase. My firebase database structure is as follow-
Users:{
uid:{
name:Bruno,
age: 22,
email: bruno#gmail.com,
address:...
}
},
Level_info:{
uid:{
score:70,
level:5
}
}
Before Rxjava, I retrieve all users like this-
userRef.addValueEventListener(new ValueEventListerner(){
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(Datasnapshot snapshot:dataSnapshot.getChildren())
{
User user = snapshot.getValue(User.class);
userList.add(user);
//to get score and levels
/*I can't add nested value event listener directly because of Asynchronous behavior */
userId.add(user.getId());
}
getLevels(userId);
}
#Override
public void onCancelled(DatabaseError error) {
//handle errors
}
});
void getLevels(final ArrayList<String> userid){
levelRef.addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(String id:userid)
{
Level level = dataSnapshot.child(id).getValue(Level.class);
levelList.add(level);
}
/** Attch both "userList" and "levelList" to RecyclerView */
}
#Override
public void onCancelled(DatabaseError error) {
//handle errors
}
});
}
It goes fine.But if there are many nested Listeners, It will hard to read.So I tried to change to RxJava and RxAndroid. Like this-
public Observable<ArrayList<User>> userOb(){
return Observable.create(new
ObservableOnSubscribe<ArrayList<User>>() {
#Override
public void subscribe(final
ObservableEmitter<ArrayList<User>> emitter)
throws Exception {
FirebaseDatabase.getInstance().getReference("Users")
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
ArrayList<UserModel> listUsers;
for(DataSnapshot snapshot: dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
listUsers= new ArrayList<>();
listUsers.add(user);
emitter.onNext(listUsers);
}
emitter.onComplete();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
}
Here I don't know how to zip with LevelObservable because levelObservable need UserId from UserObservable to get data from Levels/(uid)/"level_info" .May be this is stupid question but I am new to RxJava. I want to get Corresponding userId from UserObservable to LevelObservable. So how can I do that?
Sorry for my bad English Writing skill.
Edit: Is there some ways to implement like this (because may be I miss some easy ways to implement).
Hello all i have a my fire-base structure like this
Firebase Database
I have an array list inside an node in fire-base , I need to loop through this list and jump to each ID to get information i need like the database photo shows.
what I've tried so far
public static void checkIfCurrentUserLiked(final HomeFragment.PostsViewHolder postsViewHolder, String postKey) {
userID = Objects.requireNonNull(FirebaseAuth.getInstance().getCurrentUser()).getUid();
likesRef = FirebaseDatabase.getInstance().getReference().child("likes");
postsRef = FirebaseDatabase.getInstance().getReference().child(postKey);
postsRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("likes")) {
for (DataSnapshot ds : dataSnapshot.child("likes").getChildren()) {
likesRef.child(Objects.requireNonNull(ds.getValue()).toString())
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
Like like = snapshot.getValue(Like.class);
if (like != null && like.getLikedUserID().equals(userID)) {
postsViewHolder.likesImage.setImageResource
(R.drawable.ic_item_home_post_like_filled);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) { }
});
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) { }
});
}
i have no error , just nothing happens , data are not fetched as expected
Change this:
postsRef = FirebaseDatabase.getInstance().getReference().child(postKey);
into this:
postsRef = FirebaseDatabase.getInstance().getReference().child("posts").child(postKey);
According to your database, you have node posts before the postKey, therefore you need to add it when referencing to a location.
I fetched data from firebase database, inside OnDataChange method I want to perform another query based on the data I fetched previously. Before going to another activity I fetched all my data using a callback function MyCallback. Here listAllRequest contains expected data but userMap contains null. How can I ensure userMap contains data before going to another activity?
public void readRequestData(final Outgoing.MyCallback myCallback) {
groupDatabase = FirebaseDatabase.getInstance().getReference("Users").child(user.getUid()).child("outgoing");
userInfoRef= FirebaseDatabase.getInstance().getReference("UserInfo");
groupDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
listAllRequest.clear();
for(DataSnapshot childSnapshot: dataSnapshot.getChildren())
{
final BookRequestData bookRequestData = childSnapshot.getValue(BookRequestData.class);
listAllRequest.add(bookRequestData);
userInfoRef.child(bookRequestData.getOwnerId()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user=dataSnapshot.getValue(User.class);
userMap.put(bookRequestData.getReqId(),user);
Log.e("outgoing",user.getName());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
myCallback.onCallback(listAllRequest);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {}
});
}
I want to read data offline for my users, but Persistance mode will make OnDataChange in ValueEventListener call twice. how can I prevent it. I need to use ValueEvent for my own purpose. someone help me please.
Update : I am making a friend suggestions list for users in my app, the suggested user must dont have any relationship with the current user. and this is my code ( I use Persistance for offline data as Firebase's suggestion)
valueEventListener_check_relationship=new ValueEventListener() {
#Override
public void onDataChange(#NonNull final DataSnapshot dataSnapshot_root) {
num_fiend_req=0;
num_sent_req=0;
update_badges(num_sent_req,tv_badges_sent_req);
update_badges(num_fiend_req,tv_badges_friend_req);
arrayList_suggestions.clear();
adapter_suggestions.notifyDataSetChanged();
GlobalConstants.ROOT_REF.child(GlobalConstants.CHILD_USERS)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot:dataSnapshot.getChildren()){
Object_User user_suggested=snapshot.getValue(Object_User.class);
if(!user_suggested.user_id.equals(GlobalConstants.getMyUID())){
if(!dataSnapshot_root.hasChild(user_suggested.user_id))
addToList(user_suggested);
else {
RemoveUserFromlist(user_suggested);
if (dataSnapshot_root.child(user_suggested.user_id)
.hasChild(GlobalConstants.CHILD_REQUESTING)){
String values=dataSnapshot_root.child(user_suggested.user_id)
.child(GlobalConstants.CHILD_REQUESTING)
.getValue().toString();
if (values.equalsIgnoreCase(GlobalConstants.VALUE_REQUESTING_SENDER))
num_sent_req++;
else num_fiend_req++;
}
update_badges(num_sent_req,tv_badges_sent_req);
update_badges(num_fiend_req,tv_badges_friend_req);
adapter_suggestions.notifyDataSetChanged();
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
GlobalConstants.ROOT_REF.child(GlobalConstants.CHILD_RELATIONSHIP)
.child(GlobalConstants.getMyUID()).keepSynced(true);
GlobalConstants.ROOT_REF.child(GlobalConstants.CHILD_RELATIONSHIP)
.child(GlobalConstants.getMyUID())
.addValueEventListener(valueEventListener_check_relationship);