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
Related
I am creating a phone node and storing user's number in that node at the time of sign up so that app asks him to sign up and does not send him verification code if he tries to sign in before signing up.
I tried firebase query to compare the number user enters with the phone node to check if the number exists or not.
if (v == btn_login) {
Toast.makeText(LoginActivity.this, "In Login Button", Toast.LENGTH_LONG).show();
String number = et_Phone.getText().toString().trim();
if (number.isEmpty() || number.length() < 10) {
et_Phone.setError("Valid number is required");
et_Phone.requestFocus();
return;
}
final String ph = "+92" + number.substring(1);
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("phone");
Query query = ref.orderByChild("phonenumber").equalTo(ph);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Toast.makeText(LoginActivity.this, ph.toString(), Toast.LENGTH_LONG).show();
sendVerificationCode(ph);
L1.setVisibility(View.GONE);
L2.setVisibility(View.VISIBLE);
} else {
et_Phone.setError("Please enter the number again");
et_Phone.setText("");
et_Phone.requestFocus();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
Firebase Query returns null every time
Your phone node has only a single property phonenumber. To find the property with the value you entered, use:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("phone");
Query query = ref.orderByValue().equalTo("+923234022022");
To use orderByChild("phonenumber") the location that you're querying needs to have multiple child nodes, each of which in turn has a phonenumber property. So something like:
users: {
uidOfUser1: {
name: "Sikandar Niaz",
phonenumber: "5557273456"
},
uidOfUser2: {
name: "Frank van Puffelen",
phonenumber: "5554159410"
}
}
Now in the above structure you can use orderByChild() to find the child nodes that have a specific phone number:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("users");
Query query = ref.orderByChild("phonenumber").equalTo("5557273456");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
System.out.println(userSnapshot.getKey())
System.out.println(userSnapshot.child("name").getValue(String.class))
}
}
...
This will print:
uidOfUser1
Sikandar Niaz
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?
I have integrated Google sign-in in my app and i am pushing some data in to fire base including user U-id.I had researched a lot and didn't get anything the problem i am facing that i want to fetch Particular data for eg If User A sign-in and push 5 data and Then User B sign-in and push 3 data.I want a query like if User A sing-in Again it will get his 5 data only and not the data which is pushed by User B.Thanks in Advance :)
By using this it fetch all the data from firebase:
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
FirebaseModel firebasemodel =
data.getValue(FirebaseModel.class);
firebasemodels.add(firebasemodel);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I have tried all that .child .orderby and .equalTo but did'nt work
My Structure is Like:
My FireBase Structure
You also need a reference to the data, which isn't included in your code block. So something along the lines of (this should be before this):
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("notepad-secure/notepad");
Firstly add a user_id key in your child data, it will look like below :
id:"",
note:"",
title:"",
user:""
user_id:"{id from which user have you uploaded data}"
And than you can call below function with specific user data like
below Note : "user_id" = id from which user have you uploaded data
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("notepad").orderByChild("id").equalTo("user_id");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// dataSnapshot is the "notepad" node with all children with id
for (DataSnapshot notepad: dataSnapshot.getChildren()) {
// do something with the individual "notepad_data"
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
To Fetch Particular values from the firebase,try this code
FirebaseDatabase database;
database.getReference().child("notepad-secure").orderByChild("id").equalTo(user).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
User userdet =childSnapshot.getValue(yourclass.class);
String note=userdet.note;
//Here you will get the string values what you want to fetch
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
First U have to differentiate.U have to implement Firebase Authentication the u can get Firebase UID of every USER.
String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
Then store seperatly in new node.
i.e Take Firebase Database Instance and
databaserefernace.child("Data").Child("userID);
When your add a user data to Firebase database, you can add it using the specific uid provided by the FirebaseAuth object like this:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
Assuming you that your database strucure look like this: Firebase root -> notepad-secure -> notepad, to retrieve data, you can use this code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference notepadRef = rootRef.child("notepad-secure").child("notepad").child(uid);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String id = dataSnapshot.child("id").getValue(String.class);
String note = dataSnapshot.child("note").getValue(String.class);
String title = dataSnapshot.child("title").getValue(String.class);
String user = dataSnapshot.child("user").getValue(String.class);
Log.d("TAG", id + " / " + note + " / " + title + " / " + user);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
notepadRef.addListenerForSingleValueEvent(eventListener);
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);
So I have a list of objects stored in firebase and want to query for just one object using child equal to method but I am getting a map with single key value instead.
Code below showing what I want to achieve instead of dealing with hashmaps.
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference coutryRef = database.getReference(FireContract.PATH_COUNTRY);
Query countryQuery = coutryRef.orderByChild(FireContract.CHILD_NAME)
.equalTo(TestUtilities.TEST_COUNTRY_ALGERIA).limitToFirst(1);
countryQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Country country = dataSnapshot.getValue(Country.class);
assertEquals(TestUtilities.TEST_COUNTRY_ALGERIA, country.getName());
//get country key
String coutryKey = dataSnapshot.getKey();
}
#Override
public void onCancelled(DatabaseError databaseError) {
fail("Failed to get country: " + databaseError.getMessage());
}
});
When you fire a query, you will always get a list of results. Even when there is only a single item matching the query, the result will be a list of one item.
To handle the list, you can either use a ChildEvenListener or you can loop over the children in your ValueEventListener:
countryQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot countrySnapshot: dataSnapshot.getChildren()) {
Country country = countrySnapshot.getValue(Country.class);
assertEquals(TestUtilities.TEST_COUNTRY_ALGERIA, country.getName());
//get country key
String countryKey = countrySnapshot.getKey();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
fail("Failed to get country: " + databaseError.getMessage());
}
});