i want to check id duplication
i want to make id duplication check code.
so i get the id which is typed from user by using sid = id.getText().toString().trim();
and then make json trees FirebaseDatabase.getInstance().getReference().child("users").child("id").setValue("add");
by using child() method ...
and put the value using setvalue() method.
because it was not possible to use ondatachange() method... (i think this method only works when there is data so i put some no useful data) i will remove the value which is in setvalue() method later (is there another method that can be used even though there is no change... i need to check the db contents)
anyway if (data.getValue()==sid) this part
i thought it can check the id ...
but it does not work
12-25 21:06:00.771 6700-6700/com.example.pc.login D/myTag: {id=add}
android log looks like this... id is the child part... and the add is the value that i put
that is the result of the getvalue() method...
summary
:
1. how can i put the id from users to the firebase db
2. how can i get the only id value except child part
when i use getvalue() method. it takes child name and the value that i put
so if the id is exist ...user made ... user should write another...
if not... the firebase db store the id user made...
thank you for reading ... help me...
idcheckbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//store the id user created
sid = id.getText().toString().trim();
FirebaseDatabase.getInstance().getReference().child("users").child("id").setValue("add");
FirebaseDatabase.getInstance().getReference().addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot data: dataSnapshot.getChildren()){
if (data.getValue()==sid) {
Log.d("myTag",""+dataSnapshot.getChildren());
Toast.makeText(MainActivity.this, "aleady exists",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "you can use this id",Toast.LENGTH_SHORT).show();
FirebaseDatabase.getInstance().getReference().child("users").child("id").setValue(sid);
Log.d("myTag",""+data.getValue());
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
because it was not possible to use ondatachange() method... (i think this method only works when there is data so i put some no useful data)
No onDataChange(DataSnapshot dataSnapshot) method is triggered once when the listener is attached, whether there is data or NOT.
If the database path where the ValueEventListener is attached is empty/null/non-existent than dataSnapshot.exits() will return false.
Hence here can be your final code:
idcheckbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sid = id.getText().toString().trim();
// No need to store the id user created
// FirebaseDatabase.getInstance().getReference().child("users").child("id").setValue("add");
FirebaseDatabase.getInstance().getReference().child(sid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// sid already exists
} else {
// sid does not exists already
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
By the way your Firebase Database will look something like this:
{
"sid_1": "...",
"sid_2": "..."
}
Related
How do i Check Check in Database with User Entered Phone Number?
And i Want Notice to the User If he already registered.
String _getUserEnteredPhoneNumber = pNumber.getEditText().getText().toString().trim();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("People");
Query checkUser = reference.orderByChild("uid").equalTo(_getUserEnteredPhoneNumber);
checkUser.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
pNumber.setError("Username Exists,Please Enter Another User Name");
} else {
updateData();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
If you want to query on the phone number, you need to specify that property in your call to orderByChild(). So:
Query checkUser = reference.orderByChild("phone").equalTo(_getUserEnteredPhoneNumber);
I highly recommend checking out the documentation on sorting and filtering data, which covers Firebase's query capabilities in more detail.
Initially, I wrote a code to store the value in Firebase realtime database.
mDbRef = mDatabase.getReference().child("Users");
mDbRef.child("name").setValue(rname);
mDbRef.child("email").setValue(remail);
The child value was stored under its Uid in 'Users' child.
Then I changed the code to
String name = userName.getText().toString();
mDbRef = mDatabase.getReference().child("Users").child(name);
mDbRef.child("name").setValue(rname);
mDbRef.child("email").setValue(remail);
Now, the child value was stored under its name in 'Users' child.
Now I have two issues,
If I add same name with different sub child values, it was not accepted. How to rectify it?
I wrote the following code to check user before starting an activity.
public void checkUserExists () {
final String user_id = Objects.requireNonNull(uAuth.getCurrentUser()).getUid();
mDbRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild(user_id)) {
startActivity(new Intent (LoginActivity.this, HomeActivity.class));
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
The new Intent activity was working fine when the child was under Uid. When it was changed to 'name' in lieu of Uid, the intent activity doesn't start. But if I restart the app after closing it, it directly goes to Home activity. What should be done to rectify the issue?
May I suggest something like that:
String key = mDatabase.child("users").push().getKey();
// key is generated by Firebase and is unique
mDbRef = mDatabase.getReference().child("users").child(key);
mDbRef.child("name").setValue(rname);
mDbRef.child("email").setValue(remail);
And check the documentation
happy to help!
I am having trouble trying to query some information in my database, the following picture resumes what information I am trying to fetch, I am trying to get the "productId"
This is how my database looks like:
https://i.stack.imgur.com/JhJNs.png
In fact, I am trying to get this value in order to put a condition on it. I am trying to send a notification, ONLY if the productId = 02 is selected, here is my code
if (request.getFoods().isEmpty()) {
Toast.makeText(Cart.this, "Your cart is empty", Toast.LENGTH_SHORT).show();
} else{
final DatabaseReference tokens = FirebaseDatabase.getInstance().getReference("Requests");
final Query data = tokens.orderByChild("productId").equalTo("02"); // get all node with isServerToken
data.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String order_number = String.valueOf(System.currentTimeMillis());
requests.child(order_number).setValue(request);
sendNotificationOrder(order_number);
Toast.makeText(Cart.this, "Notification sent", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Thank you for the help!
Actually your above code would not work with orderByChild() like that. If you have multiple items in your foods node with their parent nodes being 0, 1 and so on, and you want to check their productId, then only this can be done.
For this, you'd have to make the parent child foods and call orderByChild() on it, for productId. The code would look something like this:
final DatabaseReference tokens = FirebaseDatabase.getInstance().getReference("Requests").child(id).child("foods");
tokens.orderByChild("productId").equalTo("02").addSingleValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// do what you want
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Do something for errors, don't ignore
}
However, if you have database structure with different parent nodes and there is one more median node between it and the node you want to retrieve data from, then that won't work with a code like above.
Learn more about how to make a database structure suitable for orderByChild() here.
I have the following JSON structure in my Firebase Database:
- users
|
+--- key: 123
| |
| +-----name : Tom
| +-----email: tom#mymail.com
|
+--- key: 456
|
+-----name : Peter
+-----email: peter#othermail.com
Now I want to check if any user with the email tom#mymail.com exists or not.
I thought:
DatabaseReference usersRef = db.getReference("users");
usersRef.orderByChild("email")
.equalTo("tom#mymail.com")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//fires if exists
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
But this only fires if a user exists and not if it doesn't. How to do it properly?
You can use exactly the code you provided. It will fire no matter if it exists or not. You only need to check if the data exists in the onDataChange() method:
DatabaseReference usersRef = db.getReference("users");
usersRef.orderByChild("email")
.equalTo("tom#mymail.com")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
//exists!
}
else {
//does not exist
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I thought this does not work and I could swear I tried it (maybe with an earlier version of Firebase) but it works!
I see two ways of approaching this:
Load the entire list of users and process it on the device (Not recommended if you have a huge number of users, which you probably do). I will not post the code here because I'm affraid beginners will simply copy and paste it and write awful apps...
Create a node containing the emails of users registered (let's call it userEmails):
userEmails
{
"tom#mymail.com":true,
"peter#othermail.com": true
}
Now, in order to check if the user exists or not:
usersRef.child("tom#mymail.com").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
//User exists
}
else
{
//User doesn't exist
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
The downside of this is that you will have to insert data into both nodes when a new user is registered.
I created A method that could be able to get the data in my firebase using the userId when I debugging it, it couldn't be able to go inside am wondering whats wrong with my code. This is my code:
public static String GetUserRole(final String userId){
Role = null;
getUsersRef().child(userId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String role = dataSnapshot.getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return Role;
}
is there any problem with this?
When implementing the ValueEventListener, the overridden methods are called when an event happens. this means that it isn't called and executed when the GetUserRole method is executed, but it is called separately, when the event happens (data received from Firebase). If you print a log you will see that the onDataChange method or the onCancelled method will be called (after GetUserRole run).
Try adding a Log print like this:
getUsersRef().child(userId).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG, "onDataChange!");
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "onCancelled!");
}
});