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

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.

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.

How to retrieve data from firebase realtime database and display it in profile dashboard

So I'm trying to display the data related to the user that has logged in but the data related to it is returning me null I've tried multiple solutions but it didn't work
public class HomeViewModel extends ViewModel {
private MutableLiveData<String> mText;
DatabaseReference userdata;
String namedata;
public HomeViewModel() {
userdata = FirebaseDatabase.getInstance().getReference();
userdata.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snap : dataSnapshot.getChildren()){
User user = snap.getValue(User.class);
namedata = user.getUserId();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
mText = new MutableLiveData<>();
mText.setValue("Welcome back! " +namedata);
}
public LiveData<String> getText() {
return mText;
}}`
here is the User.class I want to get those data and display it in the views
public class User {
String userId;
String userPhone;
String userGender;
public User() {
}
public User(String userId, String userPhone, String userGender) {
this.userId = userId;
this.userPhone = userPhone;
this.userGender = userGender;
}
public String getUserId() {
return userId;
}
public String getUserPhone() {
return userPhone;
}
public String getUserGender() {
return userGender;
}}
You have to call the "userId"
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snap : dataSnapshot.getChildren()){
HashMap<String, String> map = (HashMap<String, String>) snap.getValue();
if (map.containsKey("userId")) {
if (map.get("userId").equals("william henry")) {
String userGender = map.get("userGender");
}
}
}
}
or
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snap : dataSnapshot.getChildren()){
HashMap<String, String> map = (HashMap<String, String>) snap.getValue();
if (map.containsKey("userId")) {
String userGender = map.get("userId");
}
}
}
You are getting null because you are not fetching value from correct node. There are child of users and you want to get values of child of user.
userdata = FirebaseDatabase.getInstance().getReference().child("User");
userdata.addOnChildEventListener( new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot snap, String previousChildName) {
//get value here.
User user = snap.getValue(User.class);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
}
#Override
public void onCancelled(DatabaseError error) {
}
});
You want to get single user data then
userdata = FirebaseDatabase.getInstance().getReference().child("User").child(userIdOfthatuser);
userdata.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snap) {
User user = snap.getValue(User.class);
namedata = user.getUserId();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
first FirebaseDatabase.getInstance().getReference() point to your root ( which is the link above your database).so you need to point to what you want to get ( which is User tree).
Second of all,you must set your data inside onDataChange cause it not synchonize function ( mean your name data is always not follow the data return from onDataChange)
FirebaseDatabase.getInstance().getReference().child("User").orderByChild("userId").equalTo(*your_logged_in_user_id*).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Iterator iterator = dataSnapshot.getChildren().iterator()
if(iterator.hasNext()){
User user = iterator.next().getValue(User.class)
}
name = user.getName();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});

How to check if value exists in firebase databse

I have this Database:
I want to find out if a Email (value in database) already exists. So I have to iterate through each child of "email" and check if the value equals to the String inputMail.
I tried the following Code, but It doesn´t work, can anybody help me please? Thank u
final String input_mail = et_email.getText().toString();
DatabaseReference email = FirebaseDatabase.getInstance().getReference().child("email");
email.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String emailVal = ds.getValue(String.class);
if (emailVal.equals(input_mail)) {
//Toast exists
}
else {
//Toast not exists
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
In conclusion if I enter person1#m.de it should give out a toast that it exist
Here is a very easy way . Make your email as child . You have to replace the dot from the email and set it as child. (you can't use the email directly to a child)
static String encodeUserEmail(String userEmail) {
return userEmail.replace(".", ",");
}
static String decodeUserEmail(String userEmail) {
return userEmail.replace(",", ".");
}
Then you can easily match it like this :
final String input_mail = et_email.getText().toString();
DatabaseReference email = FirebaseDatabase.getInstance().getReference().child("email");
email.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(datasnapshot.child(input_mail).exits){
//Toast exists
}else {
//Toast not exists
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});

Get data from firebase from a specific position

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++;
}
}

how to get specific nodes under unique keys in firebase realtime database android

I am trying to get data from nested nodes under unique keys. Each key is identical. It's difficult for me to deal with such problem help please.
I have tried ChildEventListener on database reference but not succeeded.
here is the code i am using to retreive data
InfoFragment.java
auth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance().getReference("Seller").getRef().child("ImpInfo");
mFirebaseDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postDataSnapshot : dataSnapshot.getChildren()) {
ShopSellerInfo shopSellerInfo = postDataSnapshot.getValue(ShopSellerInfo.class);
mShopSellerInfo.add(shopSellerInfo);
}
mNearBySellerAdapter = new NearBySellerAdapter(getContext(), mShopSellerInfo);
mRecyclerView.setAdapter(mNearBySellerAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return rootView;`
ShopSellerInfo.java
public ShopSellerInfo(String shopAddress, String shopPhoneNo, String
shopImageUrl, String shopName) {
this.shopAddress = shopAddress;
this.shopPhoneNo = shopPhoneNo;
this.shopImageUrl = shopImageUrl;
this.shopName = shopName;
}
public ShopSellerInfo() {
}
public String getShopAddress() {
return shopAddress;
}
public String getShopPhoneNo() {
return shopPhoneNo;
}
public String getShopImageUrl() {
return shopImageUrl;
}
public String getShopName() {
return shopName;
}
public void setUserAddress(String shopAddress) {
this.shopAddress = shopAddress;
}
public void setUserPhoneNo(String shopPhoneNo) {
this.shopPhoneNo = shopPhoneNo;
}
public void setImageUrl(String shopImageUrl) {
this.shopImageUrl = shopImageUrl;
}
public void setShopName(String shopName) {
this.shopName = shopName;
}
}
This is the structure of my Database
I have a specific node in each unique key the contain data. I want to retrieve that data form every child node and show on single activity.
You're not too far off, just a few mistakes. The following is closer to what you need:
mFirebaseDatabase = FirebaseDatabase.getInstance().getReference("Seller");
mFirebaseDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot sellerSnapshot : dataSnapshot.getChildren()) {
DataSnapshot impInfoSnapshot = sellerSnapshot.child("ImpInfo");
ShopSellerInfo shopSellerInfo = impInfoSnapshot.getValue(ShopSellerInfo.class);
mShopSellerInfo.add(shopSellerInfo);
mNearBySellerAdapter = new NearBySellerAdapter(getContext(), mShopSellerInfo);
mRecyclerView.setAdapter(mNearBySellerAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
Changes:
Removed the call to .getRef(), which is not needed and in general an anti-pattern.
Removed the call to .child("ImpInfo") from the DatabaseReference, since there is no /Seller/ImpInfo.
Added .child("ImpInfo") in the loop, since you want the ImpInfo child of each snapshot.
Raise an error if onCancelled triggers, since it's a bad practice to ignore errors.

Categories