I want to retrieve data from my database. For example: I just want to get the username and password from my database, what should I implement next ?
public void loginToSystem(String usernameLogin, String passwordLogin){
usernameLogin = username.getText().toString();
passwordLogin = password.getText().toString();
if(TextUtils.isEmpty(usernameLogin)){
username.setError("Please Input Username");
return;
}
else if(TextUtils.isEmpty(passwordLogin)){
password.setError("Please Input Password");
return;
}
else {
Query query1 = databaseReference.orderByChild("usnername").equalTo(usernameLogin);
Query query2 = databaseReference.orderByChild("password").equalTo(passwordLogin);
//What Should I do Here
}
}
What should I do with the Code.
Ps: I am using the DatabaseReference and am I doing a good way to proceed Login with using this ?
Or I have to separate my data username and password using FireAuth
And Personal Data using Firebase Database
You need to add ValueEventListener to be able to retrieve the data:
Query query1 = databaseReference.orderByChild("username").equalTo(usernameLogin);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String address=datas.child("address").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError error) {
}
});
Also you can only use one orderByChild with each listener.
You dont need to add the password in the database as it is stored in the firebase auth. Also you are using a random id generated by push(). Since you are using Firebase Auth, then get the userid and add the data inside of it.
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
String userid=user.getUid();
then you will have:
Users
userid
address: address_here
name: name_here
email:email_here
What you could do is when the user clicks on the login button you could add a ValueEventListener on the node that you want to listen then what you'll get is the whole data from the node and then we could check that if the username and password are contained in the node then you could log in or maybe save the data whichever suits your case.
I have tried the same logic by clicking on a login button and it worked for me. Kindly try the below code.
DatabaseReference ref = mDatabaseReference.child("YOUR NODE NAME");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()){
HashMap<String,String> map = (HashMap<String,String>)dataSnapshot1.getValue();
if (map.get("username").equals("USERNAME THAT TO BE CHECKED")){
Log.d("Testing","True "+map.get("name"));
}
else {
Log.d("Testing","True "+map.get("name"));
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Hope it works.
Related
I am trying to retrieve a list of friends for a user so I can display them in a list view. The friends and user info is structured like this in my firebase database:
So basically, I want to take the user ids listed in the friends part and query my users data to get all the info under every node that is in that set of user ids. How can I achieve this using the android firebase database sdk querying? I would like to be able to retrieve all the users in a single database query.
Thanks.
You cannot get that data in single query, you need to query your database twice. This is a common practice when it comes to Firebase. Assuming that friends and users nodes are direct childs of your Firebase root, to achieve this, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference friendIdRef = rootRef.child("friends").child(friendId)
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String key = ds.getKey();
DatabaseReference usersRef = rootRef.child("users").child(key);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
String username = dSnapshot.child("username").getValue(String.class);
Log.d("TAG", username);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(eventListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
friendIdRef.addListenerForSingleValueEvent(valueEventListener);
It will print all user names of those particular users. One more thing to note, is that you don't need to add in your database those friends that have the value of false, only those with the value of true.
I am creating a login page in android using Firebase Email Password Authentication and I want when a user enters its Email address and shift to password the system automatically get the PhotoUrl and DisplayName and display on the Login page Before a user enters His Full Password.
For do what you want one way is doing that:
So you have something like that in firebase database:
ASDEYRDSDDA
Email: jonh#doe.com
Display_name: Jonh
Photo_URL: your_url
WERSWERSDFR
Email: maria#doe.com
Display_name: Maria
Photo_URL: maria_url
to get the data from firebase you only need to create a reference like that:
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("users");
and the listener:
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot data: dataSnapshot.getChildren()){
String email=data.child("Email").getvalue(String.class);
if (email.equals("jonh#doe.com")) {
//do ur stuff
String displayname=data.child("Display_name").getvalue(String.class);
String photourl=data.child("Photo_URL").getvalue(String.class);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
So it checks in all childs if the data that you want exists and if yeas you do what you whant.
I am storing user details 'firstname' and 'lastname' in UserNode. But when i want to retrieve that details then no data is being retrieved. I tried almost all solutions on the internet but nothing solved my problem. Here is my code for retrieving data of the current user:
FirebaseUser userr = FirebaseAuth.getInstance().getCurrentUser();
if (userr != null) {
String name = userr.getDisplayName();
Log.e("value", name);
}
but it says "println needs a message"
I also tried with this but nothing happened:
DatabaseReference DataRef;
DataRef = FirebaseDatabase.getInstance().getReference().child("UserNode");
DataRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String acctname = (String)dataSnapshot.child("firstname").getValue();
Log.e("name", acctname);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
]1
Please help me I am stuck with it
You're reading a collection of user with a ValueEventListener. As the [Firebase documentation for reading lists with a value event](Listen for value events) explains:
While using a ChildEventListener is the recommended way to read lists of data, there are situations where attaching a ValueEventListener to a list reference is useful.
Attaching a ValueEventListener to a list of data will return the entire list of data as a single DataSnapshot, which you can then loop over to access individual children.
Even when there is only a single [child node], the snapshot is still a list; it just contains a single item. To access the item, you need to loop over the result.
So in your code:
DatabaseReference DataRef;
DataRef = FirebaseDatabase.getInstance().getReference().child("UserNode");
DataRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
String acctname = (String)childSnapshot.child("firstname").getValue();
Log.i("name", acctname);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
Using FirebaseUser:
FirebaseUser implements UserInfo and in UserInfo's getDisplayName() documentation says
Returns the user's display name, if available.
So, it is possible that FirebaseUser.getDisplayName() return null when display name is not set. In that case Log.e() receives null as message and therefore prints println needs a message
Using your own structure:
Instead of using type conversion use getValue(Class<T>) like so:
String acctname = dataSnapshot.child("firstname").getValue(String.class);
Please, read how to retrieve data from firebase. I think you have a problem because you don't have Class Model.
Your steps:
Create model UserModel with firstname and lastname field
Use listener (example from docs):
// Attach a listener to read the data at our posts reference
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Post post = dataSnapshot.getValue(Post.class);
System.out.println(post);
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
See other answers: How to retrieve data from one single userID Firebase Android and retrieving data from firebase android
I've been trying to retrieve an element from my Firebase database using its key. I have a class User and users are present in database.
I want to retrieve an object user using its key with this method :
public User getConnectedUserByUId(final String uid){
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = database.child("users");
final List<User> connectedUser= new ArrayList<User>();
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot item: dataSnapshot.getChildren()) {
if (item.getKey()==uid)
{
User user= dataSnapshot.getValue(User.class);
connectedUser.add(user);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return connectedUser.get(0);
}
but it returns an empty list every time.
The issue is here:
if (item.getKey()==uid)
since you are comparing 2 String in java you have to use the method
string.equals(Object other) not the == operator.
Moreover, since you know the key of the data in Firebase you can use it to get the reference without cycling all children.
Something like:
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = database.child("users").child(uid);
Here you try to check a very specific ID only on changed data. Instead, try using a Firebase Query with filterByKey and not using your own function to achieve that. Here's sample code that I would use to try to replace your function:
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = database.child("users");
Query connectedUser = ref.equalTo(uid);
connectedUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
// TODO: handle the post here
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// ...
}
});
As specified in the Firebase documentation here: https://firebase.google.com/docs/database/android/lists-of-data#filtering_data
in the line : User user= dataSnapshot.getValue(User.class);
you have to put : User user= item.getValue(User.class);
and you have to check the id after you get the user:
if (user.getKey()==uid){
connectedUser.add(user);
}
There are 2 mistakes and a minor issue:
you are using == to compare two String objects. In java, this is true only if they are the same reference. Use equals instead.
addValueEventListener only adds a listener that gets invoked once after you add it and then every time something changes in the value you are listening to: this is an asynchronous behaviour. You are trying to get data synchronously instead. Please read something about this.
you are fetching useless data: you only need an object but you are fetching tons of them. Please consider to use the closest reference you can to the data you are fetching.
So, in conclusion, here's some code. I'd like to point out right now that forcing synchronous acquisition of naturaly asynchronous data is a bad practice. Nevertheless, here's a solution:
public User getConnectedUserByUId(final String uid){
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = database.child("users").child(uid);
Semaphore sem = new Semaphore(0);
User[] array = new User[1];
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot item: dataSnapshot.getChildren()) {
if (item.getKey()==uid)
{
User user= dataSnapshot.getValue(User.class);
array[0] = user;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
try
{
sem.tryAcquire(10, TimeUnit.SECONDS);
}
catch (Exception ignored)
{
}
return array[0];
}
EDIT: I've just seen that this post is very old. I'm not sure how I ended up here.
I m currently developing an android app In which I m using firebse as DB.
I want to select a sepcific node and set It's password so how can I do that?
i used this code but it add another password attribute to the selected node.
this is the DB structure and i want to set password value of user toto.
public void resetPassword(){
//setting connexion parameter
final Firebase ref = new Firebase("https://test.firebaseio.com/users");
Query query = ref.orderByChild("username").equalTo("toto");
Firebase statusRef =query.getRef().child("password");
statusRef.setValue("COMPLETED");
System.out.println("Hellooooo FBM ");
}
Your query does not yet have the nodes that match that query. To get the matching nodes, you will have to attach a listener (as shown in the documentation on reading data).
A quick example:
public void resetPassword(){
//setting connexion parameter
final Firebase ref = new Firebase("https://test.firebaseio.com/users");
Query query = ref.orderByChild("username").equalTo("toto");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot user: snapshot.getChildren()) {
Firebase statusRef = user.child("password").getRef();
statusRef.setValue("COMPLETED");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "getUser:onCancelled", databaseError.toException());
}
});
}