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);
Related
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();
}
I'm building an app which will show Posts stored on firebase. The list of Post needs to be paginated fetching most recent 10 posts at a time.
Here is the methode to load post:
private void readsposts(){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts");
reference.keepSynced(true);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
postList.clear();
for(DataSnapshot snapshot:dataSnapshot.getChildren()){
Post post = snapshot.getValue(Post.class);
for(String id:followingList){
if(post.getPublisher()!=null && post.getPublisher().equals(id)){
postList.add(post);
indication.stopShimmer();
indication.setVisibility(View.GONE);
}
}
if(post.getPublisher()!=null && post.getPublisher().equals(firebaseUser.getUid())){
postList.add(post);
//stop shimmer
indication.setVisibility(View.GONE);
indication.stopShimmer();
}
}
postAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
But above code retrieves entire list of posts instead of limited posts. How can pagination be implemented?
when you fetch data at a location in your database, you also retrieve all of its child nodes.
(because you read "Posts")
so if you Advance record your post key ,otherwise you will download data
so you can new a table of Contents to stockpile your post key
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.
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).
From the firebase example, I need to find out the if there are any dinosaurs of age=25, which can be done as below. But say if there are no dinosaurs of that age, how can I find out that the query is finished and there are 0 dinosaurs of age=25. because my Android UI depends on this, to proceed to the next step.
Firebase ref = new Firebase("https://dinosaur-facts.firebaseio.com/dinosaurs");
Query queryRef = ref.orderByChild("height").equalTo(25);
queryRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot snapshot, String previousChild) {
System.out.println(snapshot.getKey());
}
// ....
});
EDIT
Some solutions provided are suggesting to use ValueEventListener. But the problem is even if you use valueEventListener, in the above case, it still does not work,as there are 0 rows. The onDataChange does not fire.
Firebase ref = new Firebase("https://dinosaur-facts.firebaseio.com/dinosaurs");
Query queryRef = ref.orderByChild("height").equalTo(25);
queryRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChanged(DataSnapshot snapshot) {
System.out.println(snapshot.getKey());
}
// ....
});
ANSWER
#Override
public void onDataChange(DataSnapshot snapshot) {
//DinosaurFacts facts = snapshot.getValue(DinosaurFacts.class);
//Log.d("hz-dino", facts.toString());
if(snapshot.getValue() != null)
{
Log.d("hz-dino", snapshot.getKey());
Log.d("hz-dino", String.valueOf(snapshot.getValue()));
}
else
{
Log.d("hz-dino", "there are exactly 0 rows!");
}
}
To test for data:
snapshot.getValue() != null
When using
ref.addValueEventListener
If no data exists at the location, the snapshot will return null.