How to get a specific item inside the key using android - android

How to only retrieve email addresses inside the key, not all the items. I have an items Name and Email, but I only want to retrieve EMAIL.
example:
Email: HOTMAIL
Email: GMAIL

first make database reference as
mReference= FirebaseDatabase.getInstance().getReferenceFromUrl(FIREBASE_URL_USERS);
here FREBASE_URL_USERS is a url of users key you can get it from firebase console.
it is a combination of your unique_fiirebase_root_url / User01
then get snapshot of data as
mDatabseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
dataSnapshot.getValue("Email");
// use log to check whetehr you are getting email or not
#Override
public void onCancelled(DatabaseError databaseError) {
// log error and do something
}
});

Assuming that the user emails are unique, you can query the users records by its email value as follows:
final String email = "hani.mehdi#email.com";
ValueEventListener onFindListener = new ValueEventListener() {
#Override
public void onCancelled(DatabaseError error) {
Log.e(TAG, error.getMessage());
}
#Override
public void onDataChange(DataSnapshot snapshot) {
Map<String, User> result = snapshot.getValue(Map.class);
if (result.contains(email) {
User user = result.get(email);
Log.i(TAG, user.toString());
} else {
Log.d(TAG, "Not found: " + email);
}
}
};
DatabaseReference userReference = database.getReference("users")
.orderByChild("email")
.equalTo(email)
.addListenerForSingleValueEvent(onFindListener);

Related

Retrieving data realtime from firebase that have 2 childs for 2 apps in 1 firebase [Android]

I create 2 android apps, for the user and for admin. The user app can crud the "pelanggaran", the admin app can see all the pelanggaran realtime.
Here, I am stuck in retrieving the data in real time for the admin app. Here's the database hierarchy.
this is the references: pelanggaran and user
each user has pelanggaran. so, the first child of pelanggaran is userID, then the pelanggaranID, then the values
I tried googling, I got it, but it is not real-time. Here's my code
private void refreshList(){
databaseUser = FirebaseDatabase.getInstance().getReference("User");
pelanggaranList = new ArrayList<>();
databaseUser.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
pelanggaranList.clear();
long numberUsers = dataSnapshot.getChildrenCount();
Log.w("total user", "" + numberUsers);
for (DataSnapshot dsUser : dataSnapshot.getChildren()){
User user = dsUser.getValue(User.class);
final String userId = user.getUserId();
Log.w("id user", userId);
databasePelanggaran = FirebaseDatabase.getInstance().getReference("Pelanggaran").child(userId);
databasePelanggaran.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot1) {
for (DataSnapshot dsPelanggaran : dataSnapshot1.getChildren()){
Pelanggaran pelanggaran = dsPelanggaran.getValue(Pelanggaran.class);
Log.w("id pelanggaran", userId + " : " + pelanggaran.getIdPelanggaran());
pelanggaranList.add(pelanggaran);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
PelanggaranAdapter pelanggaranAdapter = new PelanggaranAdapter(MainActivity.this, pelanggaranList);
recyclerView.setAdapter(pelanggaranAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
It can take all the values from each user but it is not real time. And sometimes the data doesn't appears. What should I do to make it realtime?

Check if email is existing on database

I'm trying to check if the user's email is existing in my Firebase Realtime Database. I used Firebase Authenticate to get user's Google Play Email, and if the user's email is not existing on my Firebase, the user will be prompted to another activity. Here's my code:
MainActivity.class
// Let's declare Firebase
private DatabaseReference mDatabase;
private FirebaseAuth mAuth;
private FirebaseUser mUser;
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mUser = mAuth.getInstance().getCurrentUser();
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String dEmail = dataSnapshot.getValue().toString();
String gEmail = mUser.getEmail();
for(DataSnapshot data: dataSnapshot.getChildren()){
if(data.child("email").child(EncodeString(gEmail)).exists()) {
Toast.makeText(getApplicationContext(), "There's one: " + EncodeString(gEmail), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "No email: " + EncodeString(gEmail), Toast.LENGTH_LONG).show();
}
}
/*
if(dEmail == gEmail) {
startActivity(new Intent(getApplicationContext(), RegisterActivity.class));
finish();
} else {
Toast.makeText(getApplicationContext(), "No email", Toast.LENGTH_LONG).show();
}*/
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
public static String EncodeString(String string) {
return string.replace(".", ",");
}
public static String DecodeString(String string) {
return string.replace(",", ".");
}
Here's the structure of my Firebase Realtime Database
UPDATE: The question is how can I check if the email (the email is the one in my google play which is sholomon12#g..) is exisiting in my database. Note: I got the same email inserted, I just replaced the one in database with comma since I can't insert dot in firebase database
There is a workaround here when creating users in a Firebase database. Instead of using that random generated id provided by the push() method, use the email address. Your database structure should look like this:
Firebase-root
|
--- users
|
--- john#email,com
|
--- //user details
Now to check the users for existens, you can use exists() method on DatabaseReference object. So to chieve this, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference yourRef = rootRef.child("users").child("john#email,com");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
//do something
} else {
//do something else
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
yourRef.addListenerForSingleValueEvent(eventListener);

Android Firebase: Checking if the current user id matches a list of user ids?

I'm trying to check if the logged in user id matches the current user id to validate the user type.
I'm using the exists() method but doesn't seem to work. see code:
private String userID = FirebaseAuth.getInstance().getCurrentUser().getUid();
private DatabaseReference database = FirebaseDatabase.getInstance().getReference().child("basenode");
database.child("sand").child("administratorCountry").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(userID).exists()) {
System.out.println("THIS IS THE OUTPUT: "+ "TRUE");
}else{
System.out.println("THIS IS THE OUTPUT: "+ "FALSE");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
See Firebase structure:
I would appreciate any help! Thanks!
UPDATED
Data inside each user ID:
I'd suggest attaching a listener directly to the userID node and then checking that the returned data exists:
private String userID = FirebaseAuth.getInstance().getCurrentUser().getUid();
private DatabaseReference database = FirebaseDatabase.getInstance().getReference();
database.child("sand")
.child("administratorCountry")
.child(userID) // Create a reference to the child node directly
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This callback will fire even if the node doesn't exist, so now check for existence
if (dataSnapshot.exists()) {
System.out.println("The node exists.");
} else {
System.out.println("The node does not exist.");
}
}
#Override
public void onCancelled(DatabaseError databaseError) { }
});
You don't need to specify child("basenode"), as the getReference() method points directly to the root of your database, so you can remove child("basenode") from the database variable.

How to retrieve data and specific user data from the Firebase

I am having problem in retrieving data from firebase. I have one root user's node and then inside that root I have one userID child node. Inside that child node I am storing user information according to its blood group.
Now, what I want is to fetch the name and email according to blood group, say fetch all user data whose blood group is B+.
Also, please tell me on how to fetch all entries in the firebase and show on textView.
//show data on text view
datashow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("inside click", "onClick: ");
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference db = database.getReference();
db.child("users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
if (user == null) {
Log.e(TAG, "User data is null!");
return;
}
Iterable<DataSnapshot > children = dataSnapshot.getChildren();
Log.i("children", "onDataChange: " + children);
for(DataSnapshot child : children)
{
Map<String , String> map = (Map)child.getValue();
Log.i("inside", "onDataChange: " + map);
name = map.get("name");
email = map.get("email");
dateof = map.get("userDob");
showData(name , email , dateof );
Log.i("datasnap", "onDataChange: data snapshot " + name + email + dateof);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
this is my snapshot for Firebase database
enter image description here
db.child("users").orderByChild("userBloodGroup").equalTo("B+").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
List<User> data = new ArrayList<>();
if (dataSnapshot.exists()) {
for (DataSnapshot snapshot :
dataSnapshot.getChildren()) {
User element = snapshot.getValue(User.class);
element.setKey(snapshot.getKey());
data.add(element);
}
for (User user: data){
Log.i(TAG,"user name: " +user.getName());
Log.i(TAG,"user email: " +user.getEmail());
Log.i(TAG,"user dob: " +user.getUserDob());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.i(TAG, "loadPost:onCancelled", databaseError.toException());
}
});
To query for all users with the bloodGroup B+, use a Firebase Query:
firebaseReference("users").orderByChild("userBloodGroup").equalTo("B+")
To get all the data of the users, you could use a Listener to get all of them and put them in whatever TextView you need. You could check the documentation on Firebase on how they read data. https://firebase.google.com/docs/database/android/read-and-write

How can I retrieve some fields from my Firebase database before I push any changes to it?

Currently I create a Listing object and store a bunch of fields in there. Two of the fields I need to store are the current User's email and name. I am trying to get those two fields as follows
dbRef = database.getReference().child("Users").child(emailKey);
dbRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserInfo userIn = dataSnapshot.getValue(UserInfo.class);
email1 = userIn.email;
sellerName = userIn.username;
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
After this bit of code I have the line
DatabaseReference temp = dbRefL.push();
temp.setValue(l);
All of this code is called by me pressing a button. The first time I press the button, the entire Listing object is pushed to Firebase just the way I want it EXCEPT the user email and username aren't there because they're blank. The second time I press the button the Strings are there how I want.
My guess is that this is because OnDataChange only executes after I push the Listing object. Is this true? How can I get OnDataChange to execute before I push the listing object?
The listener onDataChange() callbacks are asynchronous. The reason that your email and username is blank is because onDataChange hasn't been executed yet to make sure you push data after email and username are retrieve, put the code inside onDataChange()
dbRef = database.getReference().child("Users").child(emailKey);
dbRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserInfo userIn = dataSnapshot.getValue(UserInfo.class);
email1 = userIn.email;
sellerName = userIn.username;
//set up your l value
DatabaseReference temp = dbRefL.push();
temp.setValue(l);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Once you press the button above code should be called to obtain email and username then push the data as you want.
User addValueEvenListener like :
DatabaseReference map = database.getReference("field_name");
map.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String data = (String) dataSnapshot.getValue();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
****OR using****
database.getReference("field_name").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.e(TAG, "Field data", dataSnapshot.getValue(String.class));
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Failed to read value
Log.e(TAG, "Failed to read user", databaseError.toException());
}
});

Categories

Resources