exist in Firebase database user name - android

I am trying to search a "username" in firebase database but it always returns the else statement
mDatabaseref = FirebaseDatabase.getInstance().getReference("user_info");
mDatabaseref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child("username").child(usernamedatabasesend).exists())
{
Log.i("USERINFO","USER EXISTS");
}
else
{
Log.i("USERINFO","USER DOES NOT EXISTS");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mDatabaseref = FirebaseDatabase.getInstance().getReference("user_info");
mDatabaseref.push().setValue(uic);
the usernamedatabasesend is the Edittext value to send it to the database to check if that same value the user is entering is existing on the db or not
The Database node is like this
"user_info" : {
"-L-7QPKXFyoN-GlPxTTN" : {
"email" : "",
"name" : "",
"password" : "",
"username" : "ujjwalbassi"
},
"-L-7QPMyzXCqpWT0YLPM" : {
"email" : "",
"name" : "",
"password" : "",
"username" : "ujjwalbassi"
}
}
****UPDATE*********
This is the new code
mDatabaseref.orderByChild("username").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1: dataSnapshot.getChildren())
{
userInfo userinfoclass = dataSnapshot1.getValue(userInfo.class);
String usernamegotunamn = userinfoclass.getUsername().toString();
if(usernamegotunamn.equals(usernamedatabasesend))
{
Log.i("YESONO","USEREXISTS"+"\n"+usernamegotunamn+"\n"+usernamedatabasesend);
}
else {
mDatabaseref.push().setValue(uic);
Log.i("YESONO", "USERDOESNOTEXIST");
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The if else is working but if the "IF" is true then else works with it too. but it shows that if the user exists or not.

Try this.
mDatabaseref.orderByChild("username").equalTo("ujjwalbassi").addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//data will be available on dataSnapshot.getValue();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "getUser:onCancelled", databaseError.toException());
}
});
Reference : How to Search for data in Firebase Android

To check if the user exists by looping, you'll need to loop through each DataSnapshot and see if the username matches. To do this you need to, first, get a DataSnapshot of all the users, and then loop through each one:
mDatabaseref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot user : dataSnapshot){
if(user.child("username").getValue(String.class).equals(usernamedatabasesend)){
//The username matches!
Log.i("USERINFO","USER EXISTS");
return
}
}
}
#Override public void onCancelled(DatabaseError databaseError) {}
});
This isn't the best practice (Will get slow if you have a ton of users) but it is definitely a working solution. I recommend using #lovekush-vishwakarma's answer as a faster solution.

You cannot use exists() method to check whether a value exists or not. If you want to use exists() method, then you should consider change your database structure a little bit. Instead of having as a unique identifier the id that is generated by the push() method, just use the user name. Your database structure should look like this:
"user_info" : {
"ujjwalbassi" : {
"email" : "",
"name" : "",
"password" : "",
},
"anotherUserName" : {
"email" : "",
"name" : "",
"password" : "",
}
}
The important thing here is, when you add a new user to the database to check the userame for uniqueness. To verify if a user exists, you can use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userNameRef = rootRef.child("user_info").child(usernamedatabasesend);
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) {}
};
userNameRef.addListenerForSingleValueEvent(eventListener);
Another approach will be to filter the database after usernamedatabasesend and get all the users with the same user name. This is not a good practice, to have users in your database which have the same user name. If you want to go with this, you can use orderByChild() method in a query like this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query userNameQuery = rootRef.child("user_info").orderByChild("username").equalTo(usernamedatabasesend);
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) {}
};
userNameQuery.addListenerForSingleValueEvent(eventListener);
If the user name contains a dot ., then you need to encode it in order to use it as a key in the database. To encode the user name please use the following mothod:
static String encodeUserName(String userName) {
return userName.replace(".", ",");
}
And to get it back, please use the following code:
static String decodeUserName(String userName) {
return userName.replace(",", ".");
}

Related

Retrieve data from Firebase as list

I want to be able to retrieve everything that is currently held in a Firebase child folder. I write to the database like so;
private void commitPost() {
final String commentInput = commentText.getText().toString().trim();
commentProgress.setMessage("Posting");
commentProgress.show();
String uniqueId = UUID.randomUUID().toString();
commentDB.child(postID).child("Comments").child(uniqueId).setValue(commentInput);
commentProgress.dismiss();
finish();
}
I want to be able to read all values that are currently held in the child folder and then eventually display them in a ListView.
Database JSON;
"Engagement" : {
"-Kne46iBe6ooNFKTv_8w" : {
"Comments" : {
"c323835c-290c-44f3-8070-f9febf698ec9" : "none now!",
"stg15QKZFhNmTCYrgL5PtQ4wxJf2" : "testing"
},
"Likers" : {
"stg15QKZFhNmTCYrgL5PtQ4wxJf2" : "email#email.com"
}
To get the data only from a particular node, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference engagementRef = rootRef.child("Engagement").child("-Kne46iBe6ooNFKTv_8w").child("Comments");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String value = ds.getValue(String.class);
Log.d("TAG", value + ", ");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
engagementRef.addListenerForSingleValueEvent(eventListener);
Your output will be:
none now!, testing,

Android - Getting an Object from DataSnapShot - firebase database

I created a helper class including the functions and processes I would like to perform over my data in FirebaseDatabase.
The following function was meant to get all Posts in posts Node in fireabseDataBase:
public static Jobs getAllJobs() {
Posts posts= new Posts();
postsDBRef= FirebaseDatabase.getInstance().getReference("posts").getRef();
postsDBRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot jobSnapshot: dataSnapshot.getChildren()) {
// TODO: handle the post
String key = jobSnapshot.getKey();
//here
Post post= jobSnapshot.child(key).getValue(Post.class);
// and here
posts.add(post);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.i(getClass().getName().toString(), ": " + databaseError.getMessage());
}
});
return posts;
}
in the onDataChange function I am trying to loop over the data and retrieve it, although while logging I do get data but the post object keeps giving Null
Here's How the data look like in firebase DataBase
{
"posts" : {
"-Kr9-ii-ArpC3fLuuGnb" : {
"address" : "sfhhfg",
"applied" : false,
"currency" : "le",
"description" : "ehdhyf",
"latitude" : 0,
"longitude" : 0,
"noOfWorkers" : 2,
"rating" : 0,
"reported" : false,
"salary" : "1250",
"title" : "rgchu",
"userId" : 0
},
"-Kr94BDkdEZrmxmjxv_Z" : {
/../
},
"-Kr9Dz3S0BQEYv4VO2l3" : {
/../
},
"-Kr9XqDPUvCRcv0lwFy_" : {
/../
}
}
}
and here’s what am getting from the Debugger in a single loop
DataSnapshot { key = -Kr9-ii-ArpC3fLuuGnb, value = {address=sfhhfg,
rating=0, title=rgchu, reported=false, description=ehdhyf, userId=0,
longitude=0, noOfWorkers=2, latitude=0, currency=le, applied=false,
salary=1250} }
Any idea what am I doing wrong?
After several trials
.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Job job = snapshot.getValue(Job.class);
System.out.println(job.getTitle());
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.i(getClass().getName().toString(), ": " + databaseError.getMessage());
}
});
Using .addChildEventListener was the only Solution for my issue, Still investigation the reason.
i have edited your code and it should work fine now, i have used the same code snippets in several projects before. make sure your pojo matches the json data, you can use this tool to make it easier for yourself.
and the most important thing , Don't use Firebase as functions that return values - it goes against it's asynchronous nature.make Firebase perform it's task and then within the closure (block) go to the next step.
P.S: before using ValueEventListener or ChildEventListener read the difference between them from here.
public void getAllJobs() {
Posts posts= new Posts();
postsDBRef= FirebaseDatabase.getInstance();
postsDBRef.child("posts").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot jobSnapshot: dataSnapshot.getChildren()) {
Post post= jobSnapshot.getValue(Post.class);
posts.add(post);
}
// go to next step from here e.g handlePosts(posts);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.i(getClass().getName().toString(), ": " + databaseError.getMessage());
}
});
}

Get all usernames in a database SYNCHRONOUSLY

So I have a root in the database like this:
users {
"user1" {
username: "username1",
email: "email#email.com"
}
"user2" {
...
}
...
}
Now, I want to register a new user, so for that I need to check if the username that the new user choose is already chosen.
For that I created a single time event and gather all usernames in a string list:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> res = new ArrayList<String>();
Iterable<DataSnapshot> users = dataSnapshot.getChildren();
for (DataSnapshot user : users) {
res.add(user.child("username").getValue(String.class));
}
// No way to return anything
}
#Override
public void onCancelled(DatabaseError databaseError) {
//handle databaseError
}
});
But I have a problem, that method is asynchronous. I need to gather all usernames and know if any exists in that list synchronously.
Is there any way to achieve this?

How to read / query data from one userID Firebase Android

I want to retrieve data for a given user ID, which I am storing as a value in the database under each user. My database structure looks like below:
user: {
UserID: {
uniqueId: {
Name: ""
Email: ""
userId: ""
}
UserID: {
uniqueId: {
Name: ""
Email: ""
userId: ""
}
}
I tried this but it doesn't seem to work as it doesn't display anything on the app:
FirebaseUser user = mAuth.getCurrentUser();
df.child("UsersTable").orderByChild("userid").equalTo(user.getUid())).addChildEventListener
even when I try to give a specific value like below, it still does not read from firebase:
------------- Updated:
I want to get all data from userID. so for example, I want to retrieve all information from fmXWU324VHdDb8v6h7gvNjRojnu33, which will be name, email and userid.
UserTable
{
"fmXWU324VHdDb8v6h7gvNjRojnu33" : {
"-KbJtw467nl6p253HZ537" : {
"Name" : "name1",
"Email" : "something1#something.com",
"userid" : "fmXWU324VHdDb8v6h7gvNjRojnu33"
}
},
"pJtC45fW0MMi352UiPWnWdIS7h88" : {
"-Kb012ls9iMnzEL723o9I" : {
"Name" : "name2",
"Email" : "something2#something.com",
"userid" : "pJtC45fW0MMi352UiPWnWdIS7h88"
},
"-Kb0aq0q25FJq38256SrC" : {
"Name" : "name3",
"Email" : "something3#something.com",
"userid" : "pJtC45fW0MMi352UiPWnWdIS7h88"
},
"-Kb0atopfK64F6jy124Qi1u" : {
"Name" : "name3",
"Email" : "something1#something.com",
"userid" : "pJtC45fW0MMi352UiPWnWdIS7h88"
}
}
Update 2:
DatabaseReference df= FirebaseDatabase.getInstance()
.getReference("user").child(getCurrentUser().getUid());
df.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
get(dataSnapshot);
}
....
...
Update 3:
I assume based on what I am looking for (getting all data under defined userId) the query should look something like this:
df.child("UserTable").child(user.getUid())).addChildEventListener(new ChildEventListener()
However, this is throwing this error:
Can't convert object of type java.lang.String to type com.android.example.UserTable
Try Using addChildEventListener and Query like following..
mReference.child("user").orderByChild("userId").equalTo(user.getUid()).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//deal with data object
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
OR use addValueEventListener
mReference.child("user").orderByChild("userId").equalTo(user.getUid()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//deal with data object
}
#Override
public void onCancelled(DatabaseError databaseError) {
//toastMsg(databaseError.getMessage());
Log.e(TAG, "onCancelled: " + databaseError.getMessage());
}
});
Use something like the below code which i am using in my application and it works -
public static void storagesSetup(final Context context){
if(!hasSignedInUser()) {
**your business logic here**
return;
}
// Write a message to the database
final DatabaseReference databaseRef = FirebaseDatabase.getInstance()
.getReference("cart").child(getCurrentUser().getUid());
// Read from the database
databaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
**put your business logic here**
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
}
A Firebase Database query inspects the child nodes directly under the location that you execute it on. If you want to order on a child property of those nodes (i.e. use orderByChild()), that property must exist at a fixed path under each child nodes.
In your case, you have two nested dynamic children, which means you:
can query a known user for their results ordered by score
can't query across all users for their results ordered by score
If you want to allow the latter query, you'll need to change your data model to allow it. For example, by keeping a list of all results across all players:
ResultsTable:{
"-KbJtw467nl6p253HZ537" : {
"Name" : "name1",
"Email" : "something1#something.com",
"userid" : "fmXWU324VHdDb8v6h7gvNjRojnu33"
},
"-Kb012ls9iMnzEL723o9I" : {
"Name" : "name2",
"Email" : "something2#something.com",
"userid" : "pJtC45fW0MMi352UiPWnWdIS7h88"
},
"-Kb0aq0q25FJq38256SrC" : {
"Name" : "name3",
"Email" : "something3#something.com",
"userid" : "pJtC45fW0MMi352UiPWnWdIS7h88"
},
"-Kb0atopfK64F6jy124Qi1u" : {
"Name" : "name3",
"Email" : "something1#something.com",
"userid" : "pJtC45fW0MMi352UiPWnWdIS7h88"
}
}
Please get a idea from below code.
Order objects:
DatabaseReference mDatabaseReference = FirebaseDatabase.getInstance()
.getReference();
DatabaseReference node = mDatabaseReference.child("order")
node.orderByChild("timestamp").equalTo("-KZFQLVAv_kARdfnNnib")
.addValueEventListener(mValueEventListener);
private ValueEventListener mValueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
Log.i(TAG, "onDataChange: " + snapshot.getValue());
// Your code
}
#Override
public void onCancelled(DatabaseError error) {
Log.w(TAG, "onCancelled: " + error.getMessage());
}
};
This return the first order object. Hope you get the point Thanks! :)

Firebase querying data

{
"random_key 1" : {
"id": 0,
"text": "This is text"
},
"random_key 2" : {
"id": 1,
"text": "This is text"
}
}
If I'm storing my data like this, and I want to get the node where id is equal to 0. How can I do that?
The above is the child of issue, which is a child of root.
In your case you would have to setup a Query like this:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("issue").orderByChild("id").equalTo(0);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// dataSnapshot is the "issue" node with all children with id 0
for (DataSnapshot issue : dataSnapshot.getChildren()) {
// do something with the individual "issues"
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
#Linxy's answer is correct but since you'll be reading a list of items from the database, it's better to use a child event listener instead of the value event listener.
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("issue").orderByChild("id").equalTo(0);
query.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//Do something with the individual node here`enter code here`
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
This code works for me
Query query = mFirebaseDatabase.child("issue").orderByChild("id").equalTo(0)
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(final DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
//If email exists then toast shows else store the data on new key
if (!data.getValue(User.class).getEmail().equals(email)) {
mFirebaseDatabase.child(mFirebaseDatabase.push().getKey()).setValue(new User(name, email));
} else {
Toast.makeText(ChatListActivity.this, "E-mail already exists.", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(final DatabaseError databaseError) {
}
});
How I can use this SQL query in firebase?
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
For an easy-to-use cross platform integration of Firebase you can also have a look at V-Play Engine for mobile apps
FirebaseDatabase {
id: firebaseDb
Component.onCompleted: {
//use query parameter:
firebaseDb.getValue("public/bigqueryobject", {
orderByKey: true, //order by key before limiting
startAt: "c", //return only keys alphabetically after "c"
endAt: "m", //return only keys alphabetically before "m"
limitToFirst: 5, //return only first 5 sub-keys
})
}
}

Categories

Resources