Retrieve multiple datab by synchronization from Firebase Android - android

I am trying send my contacts to firebase one by one and checking if the user is present or not but due to the asynchronous behavior of firebase some information is showing twice.
I want to synchronize this method like this:
loop send one number to firebase, firebase response, save, and continue
for (int i=0 ; i< list.size();i++) {
Check_Contact(list.get(i));
}
public void Check_Contact(String number)
{
DatabaseReference myRef = database.getReference("user").child(number);
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() == null) {
}
else {
UserProfile row = dataSnapshot.getValue(UserProfile.class);
ls.add(row);
Adapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Can somebody tell me how to synchronize this method?
Firebase Structure
output coming

It is not the firebase async behaviour. You may have duplicate contents in your database. Please check ur database and update a screenshot of your database in your question.
It will be more helpful to understand your question.

Related

variable keeps being 0

I am using firebase database and I am trying to create some sort of an index for each one of my childs -
the index itself does update but under the posts section it keeps being 0, this is the code that is responsible for updating the index
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
DatabaseReference indexReference =ref.child("postNum");
indexReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.getValue()==null){
tempIndex = 0;
}
else {
tempIndex =(Long) snapshot.getValue();
Log.d("read", String.valueOf(tempIndex));
}
snapshot.getRef().setValue(tempIndex+1);
Log.d("temp", String.valueOf(tempIndex));
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
this is the code i use to upload new posts to firebase
Post post =new Post(etProductName.getText().toString(), date,btChooseLocation.getText().toString(),etProductPrice.getText().toString(),etProductDescription.getText().toString(),uuidImage,uid, tempIndex);
FirebaseDatabase.getInstance().getReference("Posts").child(uuidPost).setValue(post);
The problem is that your reference to postNum inside Posts table is wrong. You need to change it to ref.child("Posts").child(PostID).child("postNum");
The below solution might help you
Post post =new Post(etProductName.getText().toString(),date ,btChooseLocation.getText().toString(), etProductPrice.getText().toString(), etProductDescription.getText().toString(), uuidImage, uid, tempIndex);
//Before setting, check your POST object by printing it
//ref.child("Posts").child(yourPostID).setValue(post);
ref.child("Posts").child("a1d03799-6146-4776-9d69-73b8d9d7ae61").setValue(post);

How to compare value with child of Firebase Realtime Database?

I would to compare a value with a child of my Firebase Realtime Database but I don't know how to do. The structure of my database is:
This is the code that I wrote:
email = loadPreferences();
mAuth = FirebaseAuth.getInstance();
FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference myRef = database.getReference().child("users");
myRef.orderByChild("email").equalTo(email).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.getValue() != null) {
//loop through the keys
for(DataSnapshot datasnap : snapshot.getChildren()) {
if(!email.equalsIgnoreCase("")) {
myRef.child("users").child("email").child("address").setValue(getAddress());
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
I tried with debugger but when it arrived at "orderByChild()" it skip all and jumps to end. Anyone can help me? Thanks in advance
Data is loaded from Firebase asynchronously, because it needs to be loaded from the cloud. Instead of blocking the app for your users, Firebase instead loads the data in the background and lets your main code continue, which is what you see happening when you step through the code.
Instead of stepping through the code, place a breakpoint on the first line inside onDataChange, and allow the code to run. Then when the data is available, the debugger will hit your breakpoint and you can continue debugging.
You should also implement onCancelled, as you're now ignoring possible problems. At its minimum, this method should be:
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException();
}

How do I check if specific child value exists in FireBase (Android)

I have some trouble trying to check if user information is stored already in the FireBase database.
Basically I'm trying to do something stupid like this:
"select user_name from user where user_id="+userID+"
And if the nickname exists it should make the boolean var isFirstTime = false and if it doesn't it should stay true. And after that it should show register box or not.
This is my db:
Firebase
And this is my code in onCreate method:
databaseReference = FirebaseDatabase.getInstance().getReference();
DatabaseReference dbRefFirstTimeCheck = databaseReference.child("User").child(user.getUid()).child("Nickname");
isFirstTime = true;
dbRefFirstTimeCheck.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.getValue() != null) {
isFirstTime=false;
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
if(isFirstTime) {
showNewUserBox();
}
else {
}
No matter what I do, the methor showNewUserBox() is being called. How do I get the data i need and check if it's there?
As others have commented, data is loaded from Firebase asynchronously. By the time you check isFirstTime, the data hasn't been loaded yet, onDataChange hasn't been run yet, so ifFirstTime will have its default value (false for a boolean).
All code that requires data from the database should be inside onDataChange (or invoked from within there). The simplest fix for your code is:
databaseReference = FirebaseDatabase.getInstance().getReference();
DatabaseReference dbRefFirstTimeCheck = databaseReference.child("User").child(user.getUid()).child("Nickname");
dbRefFirstTimeCheck.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
showNewUserBox();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
Also see some of the many questions about asynchronous loading from Firebase, such as getContactsFromFirebase() method return an empty list (or this quite old classic: Setting Singleton property value in Firebase Listener).

Android Firebase read data issue

I'm creating an Android app for the first time, I've got a simple Realtime Firebase Database with a couple of records in it. I have the following code;
public void onStart() {
super.onStart();
// Read from the database
databaseMatches.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot matchSnapshot : dataSnapshot.getChildren()) {
matches match = matchSnapshot.getValue(matches.class);
matchesList.add(match);
}
matchList adapter = new matchList (getActivity(), matchesList);
listViewMatch.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
If I put a breakpoint on the databaseMatches.addValueEventListener(new ValueEventListener() { it shows me that the database connection has been set and is returning the correct object (In my view).
The challenge I have is the part after, the break points for public void onDataChange nor onCancelled ever get hit. I'm lost here and not sure what might be the next step as it appears to be connecting, but I am not able to retrieve records.
I'm doing this in a fragment instead of a activity. Any help is appreciated.
Detecting Connection State
it is useful for your app to know when it is online or offline. Firebase Realtime Database provides a special location at /.info/connected which is updated every time the Firebase Realtime Database client's connection state changes. Here is an example: If you are not sure.
https://firebase.google.com/docs/database/android/offline-capabilities#section-connection-state
DatabaseReference connectedRef =
FirebaseDatabase.getInstance().getReference(".info/connected");
connectedRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
boolean connected = snapshot.getValue(Boolean.class);
if (connected) {
System.out.println("connected");
} else {
System.out.println("not connected");
}
}
#Override
public void onCancelled(DatabaseError error) {
System.err.println("Listener was cancelled");
}
Firebase also loads and synchronizes data asynchronously
see Setting Singleton property value in Firebase Listener
Thanks.
There must have been some strange caching issue as the following morning when I ran the exact same code, no problem. And I've not had a problem since.

Firebase addValueEventListener excute later in loop

I am using Firebase addValueEventListener to fetch the data from firebase database, below is my code.
DatabaseReference chatMessagesDb = FirebaseDatabase.getInstance().getReference("ChatRooms");
DatabaseReference usersDb = FirebaseDatabase.getInstance().getReference("users");
chatMessagesDb.child(chatRoomId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot messages : dataSnapshot.getChildren()) {
Message message = messages.getValue(Message.class); // Message is a data Model for chatMessages.
userDb.child(message.getCreatorId()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I am applying addValueEventListener on chatMessagesDb and providing a key chatRoomId, so it will fetch all the messages from database of the chatRoom with id equals to chatRoomId. Now, for each message I want to fetch the creator of the Message, so I am adding a addValueEventListener on users database to fetch the details of the creator of a Message.
It should work like, for 1st loop of Message it should call the addValueEventListener on users db for the creator of that message, but it doesn't work like this. First, it loop through all the messages, then it starts calling addValueEventListener on users db.
How can I solve it? Please let me know if anyone have idea about this, this would be a great help.
Thanks a lot in advanced.
I think it's little late to answer, but I think other guys who are learning can be helpful. In case of message from db, use ChildValueEventListener. It returns 4 methods to implement, so any change in the db of a particular node will be listened and return that value.

Categories

Resources