String userID = user.getUid();
mFirebaseDatabase = FirebaseDatabase.getInstance();
I have userId of the user so when I'm opening my app for the 2nd time(after signing in) I should not show the select user type layout. So I ve to check whether the use is Customer or Staff internally. So the problem is I ve to check the User Id is there . I couldn't find any method to get whether user Id is there or not! There is method called addListenerForSingleValueEvent but that won't help me in my scenario. Pic of the database is given here
I don't know how to continue after this
mFirebaseDatabase.getReference().child("Users").child("Customers")
To check if an user exists in a particular section of your Firebase database, first you need to add a listener and then use exists() method directly on the dataSnapshot object. So, asumming that Users node is a direct child of the Firebase-database root, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference customersRef = rootRef.child("Users").child("Customers").child(userID);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
//do somethig
} else {
//do something else
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
customersRef.addListenerForSingleValueEvent(eventListener);
Related
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.
In my solution I save data from Windows form application. There is no problem. I can list them in my android app. On this point I am trying to get key value to update the data, but always I get null.
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myReference = database.getReference();
Query myTopPostsQuery = myReference.child("DURUSLAR").orderByChild("kayitid").equalTo("1298843637");
myTopPostsQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren())
{
//Childadi =postSnapshot.getKey().toString();
String anahtar=postSnapshot.getKey().toString();
Toast.makeText(getApplicationContext(),anahtar,Toast.LENGTH_LONG);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Can you please help me?
When you execute a query at a location in the Firebase Database, it will search for the property you order/filter on in each child under that location. Since you query in /DURUSLAR, Firebase looks for /DURUSLAR/{something}/kayitid. Such a property does not exist, since you only have /DURUSLAR/{something}/{pushid}/kayitid.
To fix this problem you have two options:
query at a lower level
query to the property at its (fixed) path
The first option is to create the query at a lower level in the tree:
Query myTopPostsQuery = myReference.child("DURUSLAR/K6").orderByChild("kayitid").equalTo("1298843637");
Now the query is looking for /DURUSLAR/{pushid}/kayitid and it will work.
The second option is to query for the known path of the property:
Query myTopPostsQuery = myReference.child("DURUSLAR").orderByChild("K6/-KknsAR4_KFAeZ1HVXPW/kayitid").equalTo("1298843637");
It seems unlikely you want this here, but the approach may be helpful in other situations. Often when you need this approach with push IDs in the path, you'll want to look at http://stackoverflow.com/questions/40656589/firebase-query-if-child-of-child-contains-a-value.
The reason you are getting null is because you are doing orderByChild on the wrong level of data . According to your data u need to have a child K4-> which has a unique_id_push_id -> kayitid.Therefore you need to traverse the K4 in order to get 1298843637 for key kayitid.You can follow this tutorial to understand the retrieving of data from firebase .
Query myTopPostsQuery = myReference.child("DURUSLAR").child("k6").orderByChild("kayitid").equalTo("1298843637");
myTopPostsQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren())
{
//Childadi =postSnapshot.getKey().toString();
String anahtar=postSnapshot.getKey().toString();
Toast.makeText(getApplicationContext(),anahtar,Toast.LENGTH_LONG);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I have the following database structure:
I need to delete a child (both key and value), for example, the first one, by knowing his value: xzFD1RahhZYr05nZljIW9BRzvSq1
So I have
String itemToDelete = "xzFD1RahhZYr05nZljIW9BRzvSq1";
FirebaseDatabase database = FirebaseDatabase.getInstance();
databaseReference deleteRef=database.getReference("richieste").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
deleteRef.orderByValue().equalTo(itemToDelete);
deleteRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//What to do with .removeValue(); ?
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
}
I don't know exactly what to do with dataSnapshot to remove the child
Thank you for the answer
Bonus question: what should I do with onCancelled event?
To get the DatabaseReference, you can call DataSnapshot.getReF(), and then you can remove the value by calling .removeValue().
But based on your case, you should iterate the DataSnapshot or use ChildEventListener to make sure you are removing the child and not the whole data under richieste/<user_id>.
To iterate and remove the value:
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
childSnapshot.getRef().removeValue();
}
There's another error in your code, you should store the reference of this line deleteRef.orderByValue().equalTo(itemToDelete); to another DatabaseReference before attaching the event listener or you can directly attach the listener with this trick deleteRef.orderByValue().equalTo(itemToDelete).addListenerForSingleValueEvent(...);
For the bonus question, the onCancelled will be called if there's an error reading the database such as network or permission problem.
Hope this helps :)
Willik's answer covers the important issues. The code below implements them all.
Update for Comments:
Query is a class in the Firebase SDK. You should be able to import it:
import com.google.firebase.database.Query;
If dataSnapshot.exists() is false, it means there is no data in the database at /richieste/$uid. Check that the UID of the signed-in user is what you expect and there is data for that UID in your database.
String itemToDelete = "xzFD1RahhZYr05nZljIW9BRzvSq1";
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference deleteRef = database.getReference("richieste")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
// orderByValue() and equalTo() return a query; can't use the original reference
Query deleteQuery = deleteRef.orderByValue().equalTo(itemToDelete);
deleteQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// If the value to delete is not unique, there may be multiple children
for (DataSnapshot child : dataSnapshot.getChildren()) {
// TODO Should also check the result of removeValue()
// using a CompletionListener or the returned Task
// in case you don't have write access
child.getRef().removeValue();
Log.d(TAG, "onDataChange: Removed " + child.getKey());
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Often get here because of a protection violation;
// i.e. the security rules are not set to grant read access.
// One option is to log the failure
Log.e(TAG, "onCancelled: FAILED " + databaseError.getMessage());
// Or you can also throw the exception
throw databaseError.toException();
}
});
DatabaseReference databaseReference=mDatabase;
String queryText="Hotel";
databaseReference.orderByChild("Coupon")
.startAt(queryText)
.endAt(queryText+"\uf8ff");
Here I attached the code which I used to get child names of "Coupon" when I entered the "Hotel" query under the Coupon.But I got blank.I supposed to get Hotel1,Hotel2 object.I'm new to firebase.So hope your support .Thanks in advance.
In the Web version, they use something called ElasticSearch, you could try to read more here: https://firebase.googleblog.com/2014/01/queries-part-2-advanced-searches-with.html
But for Android, I think there isn't any functionality to perform a search like that. What I would do is to query all the records then filter them myself:
DatabaseReference databaseReference = mDatabase;
mDatabase.addValueEventListener(new ValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot val : dataSnapshot.getChildren()){
//I am not sure what record are you specifically looking for
//This is if you are getting the Key which is the record ID for your Coupon Object
if(val.getKey().contains("Hotel")){
//Do what you want with the record
}
//This is if your are querying for the hotel child
if(val.child("hotel").getValue(String.class).contains("Hotel")){
//Do what you want with the record
}
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
}
Don't load your whole database to filter out needed data. It produces unnecessary traffic which has to be loaded, calculated and deleted. Instead, use:
DatabaseReference myRef = FirebaseDatabase.getDatabaseReference();
Query searchQuery = myRef.child("Coupon").orderByChild("hotel").equalTo("yourSearchString");
To make this code work, you also have to add indexOn on your corresponding attribute in the rules (of Firebase Database console).
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.