fetching all uid from firebase database - java

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()"

Related

How to retrieve the push id value

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)?

Insert into firebase real-time database with getuid instead of getkey

I am inserting data into the firebase real-time database and then getting the data and displaying it on a graph but when i insert into the database now i am using the unique getkey() method to insert the values but i would like to use the getuid() method as the user is already authenticated in the app. I'd like to know how I can change the getkey() to use the getuid().
This is my current code: The getkey() method is in the setListneners() method
FirebaseDatabase database;
DatabaseReference reference;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/mm/yyyy");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weight);
Btn_Display = findViewById(R.id.btn_display);
graphView = findViewById(R.id.weight_graph);
series = new LineGraphSeries();
graphView.addSeries(series);
database = FirebaseDatabase.getInstance();
reference = database.getReference("WeightGraph");
setListeners();
}
private void setListeners() {
Btn_Display.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String id = reference.push().getKey();
long x = new Date().getTime();
int y = Integer.parseInt(weight.getText().toString());
PointValue pointValue = new PointValue(x, y);
reference.child(id).setValue(pointValue);
}
});
graphView.getGridLabelRenderer().setNumHorizontalLabels(2);
graphView.getGridLabelRenderer().setNumVerticalLabels(2);
graphView.getGridLabelRenderer().setLabelFormatter(new DefaultLabelFormatter(){
#Override
public String formatLabel(double value, boolean isValueX) {
if(isValueX){
return simpleDateFormat.format(new Date((long) value));
}else{
return super.formatLabel(value, isValueX);
}
}
});
}
#Override
protected void onStart() {
super.onStart();
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
DataPoint[] dataPoints = new DataPoint[(int) snapshot.getChildrenCount()];
int index = 0;
for(DataSnapshot dataSnapshot : snapshot.getChildren()){
PointValue pointValue = dataSnapshot.getValue(PointValue.class);
dataPoints[index] = new DataPoint(pointValue.getxValue(), pointValue.getyValue());
series.resetData(dataPoints);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser mAuth = FirebaseAuth.getInstance().getCurrentUser()
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
DataPoint[] dataPoints = new DataPoint[(int) snapshot.getChildrenCount()];
int index = 0;
for(DataSnapshot dataSnapshot : snapshot.getChildren()){
PointValue pointValue = dataSnapshot.getValue(PointValue.class);
dataPoints[index] = new DataPoint(pointValue.getxValue(), pointValue.getyValue());
series.resetData(dataPoints);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
Then you can get Uid
mAuth.getUid()
If you want to write the data under the user's UID instead of the key generated by push(), you'd do something like this:
String id = FirebaseAuth.getInstance().getCurrentUser().getUid();
long x = new Date().getTime();
int y = Integer.parseInt(weight.getText().toString());
PointValue pointValue = new PointValue(x, y);
reference.child(id).setValue(pointValue);
If you want to store a list of points for each user, you'd change that last line to:
reference.child(id).push().setValue(pointValue);
So this way you get a list of auto-generated (push) IDs under each UID.

read a realtime database node

hi guys I would like as a title to read a single node created previously in my realtime firebase database, the database is thus created:
Users
---- UID1
---- Email:
---- Fullname:
---- Phone:
---- Coins:
---- UID2
---- Email:
---- Fullname:
---- Phone:
---- Coins:
so my database has a structure like the one shown and I need to read in onDataChange and then write the data in a TextView.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page_coins_);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Utenti");
myRef.child("Rapp Coins %").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String coinsRapp = dataSnapshot.getValue(String.class);
mCoins.setText(coinsRapp);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
this method I used doesn't work as I can't get it to take the data I need.
I need to take the Coins value: within each different logged user, so each logged in user reads his data.
I the UID value that identifies each user, I created it based on his mobile number, so each user has his own mobile number that identifies him as UID.
this is all my code, as you can see the data that saves the UID is contained in mPhone, which was saved and then brought into this activity through the SharedPreferences.
public class PageCoins_Activity extends AppCompatActivity implements RewardedVideoAdListener {
private static final String TAG = MainActivity.class.getName();
private FirebaseAuth mAuth;
private AdView mBannerTop;
private AdView mBannerBot;
private RewardedVideoAd mRewardedVideoAd;
public double Coins;
double coinsOp = 0.00;
double coinsCl = 0.00;
double coinssum = 0.00;
Button mButton;
Button mPhonebtn;
TextView mCoinscounter;
TextView mCoins;
FirebaseDatabase mDatabase;
EditText mPhoneEdt;
TextView mPhone;
#Override
protected void onStart(){
super.onStart();
updateUI();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page_coins_);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Utenti");
myRef.child("Rapp Coins %").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String coinsRapp = dataSnapshot.getValue(String.class);
mCoins.setText(coinsRapp);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
mAuth = FirebaseAuth.getInstance();
initFirebase();
//counter CRD
mCoinscounter = (TextView)findViewById(R.id.Textcoins);
mButton = (Button)findViewById(R.id.btn2);
mPhoneEdt = (EditText)findViewById(R.id.NumberPhEdt);
mPhone = (TextView) findViewById(R.id.NumberPhTxt);
mCoins = (TextView)findViewById(R.id.txtGen);
mPhonebtn = (Button)findViewById(R.id.buttonPhone);
//mPhoneEdt.setVisibility(View.GONE);
//mPhone.setVisibility(View.VISIBLE);
findViewById(R.id.btn2).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
}
// Write a message to the database
DatabaseReference myRef = mDatabase.getReference();
myRef.child("Utenti").child(mPhone.getText().toString()).child("Rapp Coins Day %").setValue(mCoinscounter.getText().toString());
}
});
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
mRewardedVideoAd.setRewardedVideoAdListener(this);
//Set Orientation Portrait
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Banner Top View Coins
mBannerTop = (AdView) findViewById(R.id.adViewTopcoins);
AdRequest adRequest = new AdRequest.Builder().setRequestAgent("android_studio:ad_template").build();
mBannerTop.loadAd(adRequest);
// Banner Bot View Coins
mBannerBot = (AdView) findViewById(R.id.adViewBotcoins);
AdRequest adRequest1 = new AdRequest.Builder().setRequestAgent("android_studio:ad_template").build();
mBannerBot.loadAd(adRequest1);
getnumberprefs();
//ADMob Video
loadRewardedVideoAd();
}
private void getnumberprefs() {
SharedPreferences numb = getSharedPreferences(Register_Activity.NUMB, MODE_PRIVATE);
String numberphn = numb.getString(Register_Activity.KEY_NUMB,null);
mPhone.setText(numberphn);
}
//boolean changepgcoins = true;
public void changeNumber(View view) {
/*if (changepgcoins == true){
mPhoneEdt.setVisibility(View.GONE);
mPhone.setVisibility(View.VISIBLE);
changepgcoins = false;
}else{
mPhoneEdt.setVisibility(View.VISIBLE);
mPhone.setVisibility(View.GONE);
changepgcoins = true;
}*/
}
private void initFirebase() {
mDatabase = FirebaseDatabase.getInstance();
}
public void HomeClick(View view){
Intent intenthome = new Intent(this, MainActivity.class);
finish();
startActivity(intenthome);
}
public void displayCrd (double amount){
mCoinscounter.setText(String.format("%.2f", amount));
}
private void loadRewardedVideoAd() {
mRewardedVideoAd.loadAd("ca-app-pub-3940256099942544/5224354917",
new AdRequest.Builder().build());
}
public void logout(View view) {
mAuth.signOut();
updateUI();
}
private void updateUI() {
FirebaseUser currentuser = mAuth.getCurrentUser();
if(currentuser == null){
Intent intTologin = new Intent(this, Login_Activity.class);
finish();
startActivity(intTologin);
}
}
#Override
public void onRewardedVideoAdLoaded() {
Log.d(TAG, "Video Caricato");
}
#Override
public void onRewardedVideoAdOpened() {
}
#Override
public void onRewardedVideoStarted() {
}
#Override
public void onRewardedVideoAdClosed() {
loadRewardedVideoAd();
}
#Override
public void onRewarded(RewardItem rewardItem) {
Toast.makeText(this, " RAPp " + " COINS " + " : " + rewardItem.getAmount(), Toast.LENGTH_LONG).show();
Coins += rewardItem.getAmount();
displayCrd(Coins/40200*100);
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
Log.d(TAG, "Caricamento Fallito");
}
#Override
public void onRewardedVideoCompleted() {
loadRewardedVideoAd();
}
#Override
protected void onDestroy() {
if (!isEmpty(mCoins)){
String coinsopen = mCoins.getText().toString();
String coinscounter = mCoinscounter.getText().toString();
coinsOp = Double.parseDouble(String.format(coinsopen.replace(',', '.'), "%.2f"));
coinsCl = Double.parseDouble(String.format(coinscounter.replace(',', '.'), "%.2f"));
coinssum = (coinsOp + coinsCl);
mCoinscounter.setText(String.valueOf(coinssum));
// Write a message to the database
DatabaseReference myRef = mDatabase.getReference();
myRef.child("Utenti").child(mPhone.getText().toString()).child("Rapp Coins %").setValue(mCoinscounter.getText().toString());
}else{
// Write a message to the database
DatabaseReference myRef = mDatabase.getReference();
myRef.child("Utenti").child(mPhone.getText().toString()).child("Rapp Coins %").setValue(mCoinscounter.getText().toString());
}
super.onDestroy();
}
private boolean isEmpty(TextView mCoins) {
String input = mCoins.getText().toString();
return input.length() == 0.00;
}
}
I really ask for help on the solution of this thing because it's the last thing I need to finish and I can't thank you.
{
"Utenti" : {
"3********4" : {
"E-Mail" : "",
"Full Name" : "",
"Phone" : "",
"Rapp Coins %" : "",
"Rapp Coins Day %" : ""
},
"3********1" : {
"E-Mail" : "",
"Full Name" : "",
"Phone" : "",
"Rapp Coins %" : "",
"Rapp Coins Day %" : ""
},
}
}
this is my database so composed.

Getting different String from snapshot.getKey(); and mAuth.getUid(); Without .push();

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()

How to retrieve all data from Android Firebase database databaseRef->userID->uniqueKey

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) {
}
});
}
}
}
}
}
}
}

Categories