String I am getting from snapshot.getKey(); is different from any other String, although I am not doing push() if i virtually compare the values of my mAuth.getUid(); string and snapshot.getKey(); they both are same, but programmatically it is not showing.
I tried concatinating my snapshot.getKey(); string in textView.setText(snapshot.getKey();); also but nothing is shown in the screen.
Please note I am not posting my whole Fragment code.
In the code below the if statement is not getting true value.
FirebaseUser mAuth = FirebaseAuth.getInstance().getCurrentUser();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference databaseReference = database.getReference();
DatabaseReference userref = databaseReference.child("Votes").child("Chat");
final HashMap<String, String> hash = new HashMap<>();
likeButton = (ImageView) view.findViewById(R.id.heartImage);
likeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hash.put("chatVoteLike", "Yes, I would like it");
userref.child(mAuth.getUid()).setValue(hash);
likeButton.setImageResource(R.drawable.red_heart);
}
});
userref.orderByKey().addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
String uID = snapshot.getKey();
Log.i("uId from", "firebase ---" + uID);
if (uID == mAuth.getUid()){
likeButton.setImageResource(R.drawable.red_heart);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The problem is Solved using using uID.equals(mAuth.getUid()) instead of uID == mAuth.getUid()
Related
I want to get a specific data value (it is circled in green) that was previously pushed. But when I run this code it also displays the key.
This is the Structure
The class in which I push the data:
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String uid = user.getEmail();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.child(user.getUid()).child("Distance").push().setValue(LastValueRounded);
reference.child(user.getUid()).child("Speed").push().setValue(averagespeed);
reference.child(user.getUid()).child("Time").push().setValue(getTimerText());
The class where I'm supposed to read the data:
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
String uid = user.getEmail();
DatabaseReference reference =
FirebaseDatabase.getInstance()
.getReference("Users");
reference.orderByChild("email")
.equalTo(uid)
.addValueEventListener(
new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
if (snapshot.child("Distance").getValue() != null) {
String distance1 = snapshot.child("Distance").getValue().toString();
String speed1 = snapshot.child("Speed").getValue().toString();
String time1 = snapshot.child("Time").getValue().toString();
distance.setText(distance1);
speed.setText(speed1);
time.setText(time1);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.w("ERROR", "onCancelled", databaseError.toException());
}
});
The displayed data
I suspect your "getValue()" returns a Map object. You may want to try:
String distance1 = (String)(snapshot.child("Distance").getValue().get("MJw...9") );
When you are using the following reference:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.orderByChild("email")
.equalTo(uid)
.addValueEventListener(/* ... /*);
It means that you are trying to get all children under the "Users" node where the "email" field holds the value of the UID of the authenticated users, but this is not correct since under the "Users" node there are no such children. To be able to get only the values that correspond to those pushed elements, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Users").child(uid);
uidRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
DataSnapshot snapshot = task.getResult();
for (DataSnapshot distanceSnapshot : snapshot.child("Distance").getChildren()) {
distance.setText(distanceSnapshot.getValue(String.class));
}
for (DataSnapshot speedSnapshot : snapshot.child("Speed").getChildren()) {
speed.setText(speedSnapshot.getValue(String.class));
}
for (DataSnapshot timeSnapshot : snapshot.child("Time").getChildren()) {
time.setText(timeSnapshot.getValue(String.class));
}
} else {
Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
}
}
});
i am trying to fetch all uid from database and put in a loop to compare all uid Reservations with the reservations that i am making. the point is to compare all time and parking with the new one i am booking so there will no be conflict in reservation.
the firebase strcuture:
the code
public class MainActivity5 extends AppCompatActivity {
private Button btnMove;
Button b;
RadioGroup radioGroup;
RadioButton selectedRadioButton;
FirebaseDatabase rootnode, rootnode2;
DatabaseReference reference, reference2;
ReservationClass reservationClass;
String str, TimeGroup;
FirebaseAuth auth;
String currentuser = FirebaseAuth.getInstance().getCurrentUser().getUid();
String allUsers = (String) FirebaseAuth.getInstance().getUid();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main5);
btnMove = findViewById(R.id.ConfirmBooking);
radioGroup = (RadioGroup) findViewById(R.id.ParkingSpace);
TimeGroup = getIntent().getExtras().getString("Selected Time : ");
btnMove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// moveToActivity6();
selectedRadioButton = (RadioButton) findViewById(radioGroup.getCheckedRadioButtonId());
//get RadioButton text
String parkingSpace = selectedRadioButton.getText().toString();
final String time3 = TimeGroup;
final String parking = parkingSpace;
String id = FirebaseAuth.getInstance().getCurrentUser().getUid();
/*Intent i = new Intent(MainActivity5.this, MainActivity6.class);
i.putExtra("Selected Parking space is: ", parkingSpace);
startActivity(i);*/
reference2 = FirebaseDatabase.getInstance().getReference("Reservation").child(id);
reference2.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (!snapshot.exists()) {
rootnode = FirebaseDatabase.getInstance();
reference = rootnode.getReference("Reservation");
ReservationClass reservationClass = new ReservationClass(time3, parking);
reference.child(currentuser).setValue(reservationClass);
Toast.makeText(MainActivity5.this, "Booking successful", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity5.this, MainActivity6.class);
startActivity(intent);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
/* final FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference myRef = database.getReference("Reservation");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.getValue() != null) {
for (DataSnapshot ds : snapshot.getChildren()) {
String uid = "" + snapshot.getValue();
String allUsers = uid;
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});*/
Query query = FirebaseDatabase.getInstance().getReference("Reservation").child(allUsers);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
selectedRadioButton = (RadioButton) findViewById(radioGroup.getCheckedRadioButtonId());
final String parkingSpace = selectedRadioButton.getText().toString();
final String time1 = TimeGroup;
final String parking = parkingSpace;
final String id = FirebaseAuth.getInstance().getCurrentUser().getUid();
for (DataSnapshot snapShot : snapshot.getChildren()) {
//Toast.makeText(MainActivity5.this, time1, Toast.LENGTH_SHORT).show();
String type = snapshot.child("time").getValue().toString();
String type2 = snapshot.child("parking").getValue().toString();
if (type.equals(time1) && type2.equals(parking)) {
Toast.makeText(MainActivity5.this, allUsers, Toast.LENGTH_SHORT).show();
}
if (!type.equals(time1) || !type2.equals(parking)) {
Toast.makeText(MainActivity5.this, type, Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity5.this, type2, Toast.LENGTH_SHORT).show();
rootnode = FirebaseDatabase.getInstance();
reference = rootnode.getReference("Reservation");
ReservationClass reservationClass = new ReservationClass(time1, parking);
reference.child(id).setValue(reservationClass);
Intent intent = new Intent(MainActivity5.this, MainActivity6.class);
startActivity(intent);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
In your current data structure this requires that you load all reservations and check them individually, meaning the performance linearly depends on the number of reservations in the system.
I highly recommend modifying your (or creating a dedicated) data structure for this, which makes what you want a direct lookup.
Reservations: {
"A1_0800-0900am": "Q1zT9iCw...OHI1",
"A4_0800-0900am": "3ReGkVGF...4Cm2",
}
So the keys here are based on the parking spot and time slot, each combination mapping to a idempotent, unique key.
With the above data structure it becomes impossible to add the new reservation for:
"A1_0800-0900am": "TDBZigbk...7Bs1",
As a reservation for that key already exists.
In fact, it is easy to enforce that existing reservations can't be overwritten in security rules with:
".write": "!data.exists()"
I am trying to read data from Firebase but it is not read by android studio although I am using the tutorial
I tried to copy the link that is sent by Android Studio to Firebase:
DatabaseReference myRef = database.getReference("USERS").child(uID).child("DeviceID");
textview.setText(myRef.toString());
and past the result in the browser and it shows me the result in firebase but when I try to use it to get data it is not retrieving anything.
here is how I am trying to read it by calling a function:
textview.setText(ReadDeviceId);
''''''''''''''''''''''''''''''''''''
private String ReadDeviceId(){
FBUser = FirebaseAuth.getInstance().getCurrentUser();
uID = FBUser.getUid();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("USERS").child(uID).child("DeviceID");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
r_deviceID = dataSnapshot.getValue(String.class);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
r_deviceID = "no userID";
}
});
return r_deviceID;
}
'''''''''''''''''''''''''''''''''''''''''''
Knowing that my firebase database security rule is:
'''''''''''''''''''''''''''''''''
{
"rules": {
".write": "auth != null",
".read": true
}
}
'''''''''''''''''''
but nothing is displayed
you can try this code
private String ReadDeviceId(){
FBUser = FirebaseAuth.getInstance().getCurrentUser();
uID = FBUser.getUid();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef =
database.getReference("USERS").child(uID).child("DeviceID");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(Datasnapshot snapshot : dataSnapshot.getChildren)
{
//try to map it with your on model class and replace the String with your model class
r_deviceID = snapshot.getValue(String.class)
}
//r_deviceID = dataSnapshot.getValue(String.class);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
r_deviceID = "no userID";
}
});
return r_deviceID;
}
In your ReadDeviceId() function, you are returning the value of r_deviceID before it is set (event listeners are not synchronous). Therefore, your textview.setText(ReadDeviceId()); will always be textview.setText(null);, which will show nothing.
For your use case, you should change addValueEventListener to addListenerForSingleValueEvent and set the textview's value from within the handler itself like this:
private String ReadDeviceId(){
FBUser = FirebaseAuth.getInstance().getCurrentUser();
uID = FBUser.getUid();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("USERS").child(uID).child("DeviceID");
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
textview.setText(dataSnapshot.getValue(String.class));
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
textview.setText("no userID");
}
});
}
This is the Firebase database:
ExchangeItemsData: -> reference
lhmuj6n3g6Su1rv7XJLq5tV62yr2 -> userId
-LQQ7scByWcswW2VIPM5 -> UniqueKey inserted by .push().getKey();
// below is the data under the uniquekey
exchangeProductName:
"Pen"
imageUrl:
"https://firebasestoragse.googleapdfis.codfm/v04df/b/dbin..."
phoneNo:
5465464
productDesc:
"Used"
productName:
"GelPen"
userID:
"lhmuj6n3g6Su1rv7XJLq5tV62yr2"
I need to show all data of every user in this ExchangeItemsData reference. I've tried many ways but i failed. If anyone can help me out here it would be so nice of you.
Thanks in advance.
To get all those values that belong to all users, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child("ExchangeItemsData");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
for(DataSnapshot ds : dSnapshot.getChildren()) {
String imageUrl = ds.child("imageUrl").getValue(String.class);
String phoneNo = ds.child("phoneNo").getValue(String.class);
String productDesc = ds.child("productDesc").getValue(String.class);
String productName = ds.child("productName").getValue(String.class);
String userID = ds.child("userID").getValue(String.class);
Log.d(TAG, productName);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
};
ref.addListenerForSingleValueEvent(valueEventListener);
The output in the logcat will be all the product names of all products of all users.
Try this code to retrieve values from your database
public class Demo extends Activity{
FirebaseAuth mAuth;
String currentUId;
DatabaseReference usersDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
mAuth=FirebaseAuth.getInstance();
currentUId=mAuth.getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("ExchangeItemsData");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists() && dataSnapshot.hasChildren()){
for (DataSnapshot userId : dataSnapshot.getChildren()) {
if(!userId.getKey().equals(currentUId)) {
usersDb.child(userId).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot1) {
if(dataSnapshot1.hasChildren()){
for (DataSnapshot userKey : dataSnapshot1.getChildren()) {
String exchangeProductName = dataSnapshot1.child(userKey).child("exchangeProductName").getValue().toString();
String imageUrl = dataSnapshot1.child(userKey).child("imageUrl").getValue().toString();
String phoneNo = dataSnapshot1.child(userKey).child("phoneNo").getValue().toString();
String productDesc = dataSnapshot1.child(userKey).child("productDesc").getValue().toString();
String productName = dataSnapshot1.child(userKey).child("productName").getValue().toString();
String userID = dataSnapshot1.child(userKey).child("userID").getValue().toString();
//From here do whatever you want to do with those values
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
}
}
}
}
}
Here is the following structure of database in firebase
Code
I am getting the current user and then checking the whether the id is null or not and get reference of child and getting key of child. Further more i am getting null in string variable where i tried to get values.
private void Check_data() {
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user.getUid() != null) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("user_info");
DatabaseReference myRef1=myRef.child(user.getUid());
myRef1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//GenericTypeIndicator<Map<String, String>> genericTypeIndicator = new GenericTypeIndicator<Map<String, String>>() {};
// Map<String, String> map = dataSnapshot.getValue(genericTypeIndicator);
String name = dataSnapshot.child("name").getValue(String.class);
String email = dataSnapshot.child("email").getValue(String.class);
Name.setText(name);
email_txt.setText(email);
/* if (image != null) {
Glide.with(MainActivity.this)
.load(image)
.centerCrop()
.into(photo_url);
}*/
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
In your database, you have random ids that are generated using push()
You should first when adding data to the database use the userid:
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
String userid=user.getUid();
the userid is unique for each user.
then to retrieve the data inside the userid:
DatabaseReference myRef = database.getReference("user_info");
DatabaseReference myRef1=myRef.child(userid);
myRef1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("name").getValue(String.class);
String email = dataSnapshot.child("email").getValue(String.class)
}
});
When the id has - at the beginning it means its a random id.