Get data from firebase from a specific position - java

Hy, I'm writing an application that has to get specific data from firebase using the position of the item in the listView. My problem is that I have no idea how to take it this item on firebase.
For all child of Torneo I have to control all the nameCreator.
I have tried this:
public Boolean RegisterUser(Data data, final int position, final Context c){
boolean registration;
final ArrayList<String> Creator = new ArrayList<>();
databaseReference.orderByChild("Tornei").equalTo(Integer.toString(position)).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
Creator.add(data.child("nameCreator").getValue().toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
if(Creator.equals(data.getNameCreator())){
registration = false;
}else{
registration = true;
}
return registration;
}
Data is a class with some getter and setter that I have created.
position is the position of the element on the list view.
Thanks for answers.

Change the following:
databaseReference.orderByChild("Tornei").equalTo(Integer.toString(position)).addListenerForSingleValueEvent(new ValueEventListener() {
into this:
databaseReference.child("Tornei").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
Creator.add(datas.child("nameCreator").getValue().toString());
if(Creator.equals(data.getNameCreator())){
registration = false;
}else{
registration = true;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Then you will be able to loop and retrieve the value of nameCreator

It's easy.
【Step 1 | Get Snapshot Data and Save in Global Variable】
DatabaseReference rootReference = FirebaseDatabase.getInstance().getReference();
DatabaseReference fruitsReference = rootReference.child("fruits");
DataSnapshot fruitsData;
#Override
protected void onStart() {
super.onStart();
fruitsReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshots) {
fruitsData = dataSnapshots;
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
【Step 2 | Find Your Target Position through the Loop】
public void onClick(View view) {
int index = 0;
for (DataSnapshot childSnapshot : fruitsData.getChildren()) {
if (index == 1) { //your target position
DatabaseReference currentFruitReference = childSnapshot.getRef();
currentFruitReference.setValue("peach"); //do whatever you want
}
index++;
}
}

Related

How can I change the value of child in Firebase database?

I want to change the value of child "toggleStatus" under Reference "BetSlip" as shown below. The already set value is "on" so I want such that when I click the button the value of "toggleStatus" is changed to "off"
BetSlipActivity.toggleCollapse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String timeStamp = betSlip.get(position).getTimeStamp();
String toggleStatus = betSlip.get(position).getToggleStatus();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("BetSlip");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot ds: snapshot.getChildren()) {
String timestamp = ""+ ds.child("timeStamp").getValue();
String toggleStatus = ""+ ds.child("toggleStatus").getValue();
if (timeStamp.equals(timestamp) && toggleStatus.equals("on")) {
//set value to off
}
if (timeStamp.equals(timestamp) && toggleStatus.equals("off")) {
//set value to on
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
If you've got the DataSnapshot for a path in the database, it's easy to get the DatabaseReference that you need to update it:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("BetSlip");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot ds: snapshot.getChildren()) {
String timestamp = ""+ ds.child("timeStamp").getValue();
String toggleStatus = ""+ ds.child("toggleStatus").getValue();
if (timeStamp.equals(timestamp) && toggleStatus.equals("on")) {
ds.child("toggleStatus").getRef().setValue("off");
}
if (timeStamp.equals(timestamp) && toggleStatus.equals("off")) {
ds.child("toggleStatus").getRef().setValue("on");
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // never ignore errors
}
});
Since you're updating the node based on its existing value, strictly speaking you might need to use a transaction for it.

Why am I receiving empty strings after receiving valid data from Firebase?

Using Firebase, I'm trying to display to the user people they have matched with. I already have valid data for testing this and I have already run tests with sample data to see if everything else works.
Now, when I use real data from Firebase, problems occur.
This is what I have for code:
public String username = "";
public String profileImage = "";
public String discussion = "";
private void FetchMatchInformation(final String key, final String choice) {
DatabaseReference matchDb = FirebaseDatabase.getInstance().getReference().child("answers").child(key);
matchDb.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
String opposite = postSnapshot.getValue(String.class);
if(opposite.equals("agree") && choice.equals("disagree")) {
DatabaseReference found = FirebaseDatabase.getInstance().getReference().child("users").child(postSnapshot.getKey());
found.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
if(postSnapshot.getKey().equals("username")) {
username = postSnapshot.getValue(String.class);
}
if(postSnapshot.getKey().equals("providerId")) {
String provider = postSnapshot.getValue(String.class);
if(provider.equals("google.com")) {
Uri photoUrl = FirebaseAuth.getInstance().getCurrentUser().getPhotoUrl();
String originalPieceOfUrl = "s96-c/photo.jpg";
String newPieceOfUrlToAdd = "s400-c/photo.jpg";
String photoPath = photoUrl.toString();
String newString = photoPath.replace(originalPieceOfUrl, newPieceOfUrlToAdd);
profileImage = newString;
} else if(provider.equals("facebook.com")) {
profileImage = FirebaseAuth.getInstance().getCurrentUser().getPhotoUrl().toString() + "?type=large";
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
FirebaseDatabase.getInstance().getReference().child("debates").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
if(postSnapshot.getKey().equals(key)) {
discussion = postSnapshot.getValue(String.class);
break;
}
break;
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
MessagesObject objDisc = new MessagesObject(username, discussion, profileImage);
resultsMessages.add(objDisc);
mMessagesAdapter.notifyDataSetChanged();
} else if(opposite.equals("disagree") && choice.equals("agree")) {
DatabaseReference found = FirebaseDatabase.getInstance().getReference().child("users").child(postSnapshot.getKey());
found.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
if(postSnapshot.getKey().equals("username")) {
username = postSnapshot.getValue(String.class);
}
if(postSnapshot.getKey().equals("providerId")) {
String provider = postSnapshot.getValue(String.class);
if(provider.equals("google.com")) {
Uri photoUrl = FirebaseAuth.getInstance().getCurrentUser().getPhotoUrl();
String originalPieceOfUrl = "s96-c/photo.jpg";
String newPieceOfUrlToAdd = "s400-c/photo.jpg";
String photoPath = photoUrl.toString();
String newString = photoPath.replace(originalPieceOfUrl, newPieceOfUrlToAdd);
profileImage = newString;
} else if(provider.equals("facebook.com")) {
profileImage = FirebaseAuth.getInstance().getCurrentUser().getPhotoUrl().toString() + "?type=large";
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
FirebaseDatabase.getInstance().getReference().child("debates").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
if(postSnapshot.getKey().equals(key)) {
discussion = postSnapshot.getValue(String.class);
break;
}
break;
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
MessagesObject objDisc = new MessagesObject(username, discussion, profileImage);
resultsMessages.add(objDisc);
mMessagesAdapter.notifyDataSetChanged();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
So what's happening is I'm getting the user's username, their profile image, and figuring out the value, which I called discussion after determining the valid key. These values are all being accessed from different tree structures from the same real-time database.
Now, at the end of the if or else-if statement, I create and instantiate the MessagesObject by passing in the username, profile image, and discussion variables. I then add this object to the List<MessagesObject> called resultMessages. I then notify my custom adapter mMessagesAdapter that the data has changed.
Like I said, all the other pieces of code work perfectly fine. It's just when I pass username, discussion, and profileImage it always passes an empty string. I know this from using the debugger.
Why is that? It should not be doing that.

How to retrieve the values of "Total"

This is my firebase database structure.
I want to fetch the values of "Total" of all children of "Bill". I have tried to fetch the data but my code is not working. Here is my code.
DatabaseReference billReference = FirebaseDatabase.getInstance().getReference().child("Bill");
billReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int i = 0;
for (DataSnapshot ds : dataSnapshot.getChildren()) {
fetchCount++;
Toast.makeText(getApplicationContext(),""+keys[i],Toast.LENGTH_LONG).show();
String temp = ds.child(keys[i]).child("Breakfast").child("11-2018").child("Total").getValue().toString();
breakfastBills.add(names[i] + " : " + temp);
i++;
}
if (fetchCount == 4) {
AlertDialog.Builder builder = new AlertDialog.Builder(bill_details_manager.this);
builder.setTitle("Bill Details for Breakfast");
builder.setItems(breakfastBills.toArray(new String[breakfastBills.size()]), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
progressDialog.dismiss();
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
What is wrong with this code ?
DatabaseReference billRef = FirebaseDatabase.getInstance().getReference();
billRef.child("Bill").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot allValueSnap) {
for (DataSnapshot snapshot: allValueSnap.getChildren()){
String key = snapshot.getKey();
if (key != null) {
billRef.child("Bill").child(key).child("Breakfast").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot keySnapshot) {
for (DataSnapshot dateSnapshot:keySnapshot.getChildren()){
String keyDate = dateSnapshot.getKey();
long totalValue =(long) keySnapshot.child(keyDate).child("Total").getValue();
Log.i("totalBreakFast","STotal: "+String.valueOf(totalValue));
breakfastBills.add(totalValue);
}
if(!keySnapshot.exists()){
Log.i("totalBreakFast","NoData: ");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
This code is getting all values of "Total".

What is the best way to check the existence of every child in one node?

FirebaseDatabase.getInstance().getReference("Block").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snap : dataSnapshot.getChildren()) {
if(snap.getKey().equals(myUID)){
FirebaseDatabase.getInstance().getReference("Block").child(myUID).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snap : dataSnapshot.getChildren()) {
if(snap.getKey().equals(list.get(position).getUid())){
FirebaseDatabase.getInstance().getReference("Block").child(myUID).child(list.get(position).getUid()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snap : dataSnapshot.getChildren()) {
if(snap.getValue().equals("1")){
call_method();
}else{
//code...
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
call_method();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
call_method();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
This code works well, but it is very long so I am asking for the best way to write it ?
I want to check firstly if Block node has child equals to my UID if it is true then I want to check if my UID has child equals to specific UID if it is true then I want to get the value of block which is 0 in this example
How can I do that ? Thank you very much.
Just traverse to the path specified using child. You will get no data if the path doesn't exist.
FirebaseDatabase.getInstance().getReference("Block")
.child("MyUUID")
.child("specificUUID")
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
// ... Do something
} else {
call_method();
}
// ... Other code
}
Try this:
Firebaseuser user=FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Block");
ref.child(user.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exist()){
//checks first uid
if(dataSnapshot.hasChild(seconduid){
//checks if seconduid is there
for(DataSnapshot datas:dataSnapshot.getChildren()){
String blocks=datas.child("block").getValue().toString();
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
This will check the first uid if(dataSnapshot.exist()) after that it will check if that uid node has the second uid that you provide if(dataSnapshot.hasChild(seconduid){ then you will iterate and get the node block

How to find if a child with particular value in its fields exists in Firebase?

I need to find if a child with particular value in one of its fields exists in Firebase.
Below is my database structure:
To check if a field exists,you can do this:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("bdxhATalcDRJCiZZcUFUJo3yrJF2");
ref.addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
//then it exists
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
This will check if
child("bdxhATalcDRJCiZZcUFUJo3yrJF2") exists in the database.
If you do this:
ref=FirebaseDatabase.getInstance().getReference().child("bdxhATalcDRJCiZZcUFUJo3yrJF2").orderByChild("chat_id").equalTo(chatid);
then it will check if that child also exists in the database
In your case you would set up query like this:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.orderByChild("chat_id").equalTo("CHAT_ID_To_COMPARE");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot issue : dataSnapshot.getChildren()) {
// do something with the individual object
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
This would filter your data at server side and no need to filter data at app side.
postRef = FirebaseDatabase.getInstance().getReference().child("bdxhATalcDRJCiZZcUFUJo3yrJF2");
postRef.orderByChild("chat_id").equalTo(chat_id)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
//bus number exists in Database
} else {
//bus number doesn't exists.
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
etEmail is an EditText
I did it for userEmail's value... as I don't have any username other than the email.
for a structure like this...
"users": {
pushId: {
"userEmail": {
}
}
}
onCreate
etEmail.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(final CharSequence s, int start, int before, int count) {
//yourFunction();
DatabaseReference databaseUsers = FirebaseDatabase.getInstance().getReference().child("users");
databaseUsers.orderByChild("userEmail").equalTo(String.valueOf(s))
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot issue : dataSnapshot.getChildren()) {
// do something with the individual object
//User email already exists
//do something
//return; stops the function from executing further
return;
}
} else {
// email doesn't exists.
// do something
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void afterTextChanged(Editable s) {
}
});
When you do the reference and you have your DataSnapshot, you can check it like this:
yourref.child("chat_id").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()) {
//Do something
}
}
exists()
Returns true if the snapshot contains a non-null value.
Also returns true if this DataSnapshot contains any data. It is slightly more efficient than using DataSnapshot.getValue() !== null.

Categories