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();
}
Related
I know there are lot similar questions but nothing works for me. I tried so many ways. Here are my code.
so Basically If the current user uid is equals to child of joined_users I want to show text "Joined"
Query ref = FirebaseDatabase.getInstance().getReference().child("joined_users").orderByChild("uid").equalTo(myUid);
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
holder.tag_room.setText("Joined");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
This code:FirebaseDatabase.getInstance().getReference().child("joined_users") looks at the node joind_users directly under the root of your database. That is not where the data in your screenshot is, which explains why the query finds no matching nodes.
If you want to read the data in your screenshot, you'll need to start with FirebaseDatabase.getInstance().getReference().child("/Rooms//51008/joined_users").
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.
There is the performance issue when i request the Firebase again and again.grid view update very slowly. so what should i do in this case i am thinking to store the path of the posts in the database. is this good idea or to store in the internal storage.(Caching)
private void setuptempGrid(View view){
setupImageGrid(ProfileActivity.images,view);
FirebaseDatabase.getInstance().getReference()
.child(getString(R.string.db_user_posts))
.child(application.getUser().getUserId()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot d:dataSnapshot.getChildren() ) {
FirebaseDatabase.getInstance().getReference()
.child(getString(R.string.db_posts)).child(getString(R.string.db_public))
.child(d.getKey()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
gridImageAdapter.add(dataSnapshot.getValue(Posts.class).getProfilePic());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
I have this code this take to much time to get the images and every time it loads when my fragment is created.
Use
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
Acc. to docs
By enabling persistence, any data that the Firebase Realtime Database client would sync while online persists to disk and is available offline, even when the user or operating system restarts the app. This means your app works as it would online by using the local data stored in the cache.
and also do -
DatabaseReference db = FirebaseDatabase.getInstance().getReference()
.child(getString(R.string.db_user_posts))
.child(application.getUser().getUserId());
db.keepSynced(true);
Use Guava caches as they are optimized and also easy to implement. And before hitting firebase check if you have the data required for the specified node or not.
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).
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.