In this code I need to save the data in firebase database as (Registration Data1 then UID then push id)
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
String uid = firebaseUser.getUid();
databaseReference = FirebaseDatabase.getInstance().getReference().child("Registration
Data1").child(uid).push();
String sp1 = spinner.getSelectedItem().toString();
String sp2 = spinner2.getSelectedItem().toString();
String sp3 = spinner3.getSelectedItem().toString();
Data DBdata = new Data(sp1,sp2,sp3,uid);
databaseReference.setValue(DBdata);
//Toast.makeText(this,"Data Added",Toast.LENGTH_SHORT).show();'''
And in this code I need to retrieve the data in recyclerview
databaseReference = FirebaseDatabase.getInstance().getReference().child("Registration Data1");
mDBListener = databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot teacherSnapshot : dataSnapshot.getChildren()) {
Data DB = teacherSnapshot.getValue(Data.class);
DB.setKey(teacherSnapshot.getKey());
mTeachers.add(DB);
}
mAdapter.notifyDataSetChanged();
mProgressBar.setVisibility(View.GONE);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(Public.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
mProgressBar.setVisibility(View.INVISIBLE);
}
});
The question is how to retrieve the data under push id without make .child(UID)?
Related
I faced a problem with showing data. Before I used current users UID as a key but now I'm using the custom key and I don't know how to call this key as a string in my code.
My code this part ( child(user.getUid() )
FirebaseUser userUID;
userUID = FirebaseAuth.getInstance().getCurrentUser();
final DatabaseReference NameRef = database.getReference().child("No server").child(userUID.getUid()).child("name");
final DatabaseReference LastNameRef = database.getReference().child("No server").child(userUID.getUid()).child("lastName");
final DatabaseReference EmailRef = database.getReference().child("No server").child(userUID.getUid()).child("email");
What changed
I want make user a string "dan ned".
Edit:
FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference NameRef = database.getReference().child("No server").child(user.getUid()).child("name");
final DatabaseReference LastNameRef = database.getReference().child("No server").child(user.getUid()).child("lastName");
final DatabaseReference EmailRef = database.getReference().child("No server").child(user.getUid()).child("email");
NameRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
final String strName = dataSnapshot.getValue(String.class);
textName.setText(strName);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
LastNameRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
final String strLastName = dataSnapshot.getValue(String.class);
textLastName.setText(strLastName);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
EmailRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
final String strEmail = dataSnapshot.getValue(String.class);
textEmail.setText(strEmail);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
There is no need to attach three listeners in order to read those three values. You can use only one, as you can see in the following lines of code:
String name = FirebaseAuth.getInstance().getCurrentUser().getDisplayName();
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference nameRef = db.child("No server").child(name);
nameRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
DataSnapshot snapshot = task.getResult();
String key = snapshot.getKey();
Log.d("TAG", key); //It will print "dan ned"
String email = snapshot.child("email").getValue(String.class);
Log.d("TAG", email); //It will print "DanilNed#gmail.com"
String lastName = snapshot.child("lastName").getValue(String.class);
Log.d("TAG", lastName); //It will print "Ned"
String name = snapshot.child("name").getValue(String.class);
Log.d("TAG", name); //It will print "Dan"
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
I am trying to get Data and comparing it to the input data but it doesn't do anything. Pls Help me!`btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("Routes").child("route1").child("Students").child("driver");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String phoneNumber = et_phone.getText().toString();
String password = et_password.getText().toString();
String phone = dataSnapshot.child("Phone_No").getValue().toString();
String pass = dataSnapshot.child("Password").getValue().toString();
if(phone.equals(phoneNumber)){
if(pass.equals(password)){
startActivity(new Intent(Authentication.this, Home.class));
}else{
Toast.makeText(Authentication.this, "Worng Password!!!", Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(Authentication.this, "Invalid PhoneNumber![enter image description here][1]", Toast.LENGTH_LONG).show();
}*/
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});`
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 fetch the data of current user with PhoneNumber from firebase database but i am not able to fetch the data
My Application is PhoneAuthtication and i have qiven the number as a child and reference path is User What should i do to fetch the data
reference = FirebaseDatabase.getInstance().getReference("Users");
reference.child(user.getPhoneNumber()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String A = String.valueOf(snapshot.child("fullName").getValue());
String B = String.valueOf(snapshot.child("phone1").getValue());
String C = String.valueOf(snapshot.child("phone2").getValue());
String D = String.valueOf(snapshot.child("message").getValue());
Name.setText(A);
Phone1.setText(B);
Phone2.setText(C);
Message.setText(D);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ProfileActivity.this,HomeActivity.class);
startActivity(intent);
finish();
}
});
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) {
}
});
}
}
}
}
}
}
}