{
users:
{
apple:
{
username : apple
email : apple#xy.com
uid : tyutyutyu
}
mango:
{
username : mango
email : mango#xy.com
uid : erererer
}
}
}
This is what I am doing
CREATING USER if checkUsername method returns 0
if(checkFirebaseForUsername(username)==0) {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(getBaseContext(),"inside",Toast.LENGTH_LONG).show();
User newUser = new User();
newUser.setUserId(mAuth.getCurrentUser().getUid());
newUser.setUsername(username);
newUser.setEmailId(email);
try{
mRef.child("users").child(username).setValue(newUser);
}
catch(Exception e){
Toast.makeText(SignUpActivity.this,"error while inserting",Toast.LENGTH_LONG).show();
}
AlertDialog.Builder builder = new AlertDialog.Builder(SignUpActivity.this);
builder.setTitle(R.string.signup_success)
.setPositiveButton(R.string.login_button_label, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(SignUpActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
});
AlertDialog dialog = builder.create();
dialog.show();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(SignUpActivity.this);
builder.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
My checkUsername method -
public int checkFirebaseForUsername(String passedUsername){
final int[] flag = {0};
final String myPassedUsername = passedUsername;
Log.e("tag","working now");
//flag[0]=1;
DatabaseReference mTest = FirebaseDatabase.getInstance().getReference();
mTest.child("users").child(passedUsername).addChildEventListener(new ChildEventListener() {
#Override
public void onDataChanged(DataSnapshot dataSnapshot) {
Log.e("tag","checking");
if(dataSnapshot.exists()){
Log.e("tag","exists");
flag[0]=1;
}
}
#Override
public void onCancelled(DataSnapshot datasnapshot){
}
});
if(flag[0]==1)
return 1;
else
return 0;
}
This is how I am inserting users in my firebase-database and I want to check if a username is available for a new user or not.
Therefore I need to check is there any user already registered with that username....Please help I have already tried whatever I could understand after reffering to documentation provided on the official firebase blog but all in vain!!
EDIT: New answer, old one still below.
I would get rid of your method "checkFirebaseForUsername" because it will always return 0, no matter what.
What you need to do is this:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("users").child("username").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
// use "username" already exists
// Let the user know he needs to pick another username.
} else {
// User does not exist. NOW call createUserWithEmailAndPassword
mAuth.createUserWithPassword(...);
// Your previous code here.
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Old Answer:
{
users:
{
apple[X]:
{
username : apple[Y]
email : apple#xy.com
uid : tyutyutyu
}
mango:
{
username : mango
email : mango#xy.com
uid : erererer
}
}
}
If for example, the node apple[X] will always have the same name as the child property "username":apple[Y], then it is as simple as this.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("users").child("username").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
// use "username" already exists
} else {
// "username" does not exist yet.
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
however, if say, the node apple[X] can have a different value than the property apple[Y], and you want to see if any node exists where the "username" property is the same, then you will need to do a query.
Query query = FirebaseDatabase.getInstance().getReference().child("users").orderByChild("username").equalTo("usernameToCheckIfExists");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getChildrenCount() > 0) {
// 1 or more users exist which have the username property "usernameToCheckIfExists"
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
You may try this.
final String userName = unameEditText.getText().toString();
databaseReference.child("users").orderByChild("username").equalTo(userName).addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i(Constants.TAG, "dataSnapshot value = " + dataSnapshot.getValue());
if (dataSnapshot.exists()) {
// User Exists
// Do your stuff here if user already exists
Toast.makeText(getApplicationContext(), "Username already exists. Please try other username.", Toast.LENGTH_SHORT).show();
} else {
// User Not Yet Exists
// Do your stuff here if user not yet exists
}
}
#Override
public void onCancelled (DatabaseError databaseError){
}
}
);
You just check if user is already exits or not by below code:
private DatabaseReference mDatabase;
// ...
mDatabase = FirebaseDatabase.getInstance().getReference();
final String userName = "your_user_name"; // replace with your user name
mDatabase.child("users").child(userName).addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// User Exists
// Do your stuff here if user already exits
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "getUser:onCancelled", databaseError.toException());
}
});
You can also see Firebase doc for the same on below link:
Read data once
Related
I want to retrieve houfxWvbwyVmbHX60IGjpNkZR9w2 key , How to do?
Here is the code for the same
mQuery = mfollowing.orderByChild("following").equalTo(user_id);
mQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final String key = dataSnapshot.getKey();
mdatabaseUsers.child(user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
DatabaseReference newfollscreen = mdatabaseFollwer.child(key).child(newPost.getKey());
newfollscreen.child("screen").setValue(downloadUrl.toString());
newfollscreen.child("engagement").setValue("NA");
newfollscreen.child("url").setValue("NA");
newfollscreen.child("uid").setValue(user_id);
newfollscreen.child("name").setValue(dataSnapshot.child("name").getValue());
newfollscreen.child("image").setValue(dataSnapshot.child("image").getValue()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(AddimageActivity.this, "Posted among your followers", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(AddimageActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled (DatabaseError
databaseError){
}
});
Here is the Firebase database
second image
enter image description here
I tried using child data snapshot method but did not worked. Any help for this will be much appreciated.
Assuming you have a DataSnapshot that points to the children rhZ4...wt2, you can call snapsthot.getRef().toString() which will return you something like https://xxx.firebaseio.com/.../houfxWvbwyVmbHX60IGjpNkZR9w2/rhZ4...wt2. From there you can extract the parent key.
From your example, after you query the database using mQuery, inside onDataChange you have a DataSnapshot.
So calling dataSnapshot.getRef().toString() will give you https://xxx.firebaseio.com/.../houfxWvbwyVmbHX60IGjpNkZR9w2/rhZ4...wt2/following.
Code to extract the parent key (put it inside your 1st onDataChange):
String reference = dataSnapshot.getRef().toString();
String[] tokens = reference.split("/");
String parentKey = tokens[tokens.length - 3];
This parentKey should be your houfxWvbwyVmbHX60IGjpNkZR9w2.
I am using firebase auth ui in order to create users with mail and password but after the registration I forward them to a new activity in order to choose I username which needs to be unique. My idea was to search the whole DB in order to see if that username exists already or not. Here is how I am trying to do this but no luck till now:
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("UserName", "Click: ");
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("USERS");
mDatabase.orderByChild("username").equalTo("name1").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
//Here you can get all data
Log.d("UserName", "onDataChange: "+snapshot.toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
I have also tried this one:
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("UserName", "Click: ");
DatabaseReference mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference();
Query query = mFirebaseDatabaseReference.child("USERS").orderByChild("username").equalTo("name1");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
//TODO get the data here
Log.d("UserName", "onDataChange: " + dataSnapshot.toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
query.addValueEventListener(valueEventListener);
}
});
The only reason your code is not working is because "username" is not a direct child of the USERS table.
Your direct children will have random ids , which you can iterate trough with ChildEventListener like this:
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("USERS");
mDatabase.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
User user = dataSnapshot.getValue(User.class); // pojo
if(user.getUsername().equals("name1") {
// do something
}
}
...
)
I want to connect the user id with the same key in Users, then show the key to FirebaseRecyclerAdapter. I get the key in Friend child already but don't know how to match this to Users.
And my code:
mFriendList = FirebaseDatabase.getInstance().getReference().child("Friends").child(current_id);
mFriendDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mFriendList.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String sd = snapshot.getKey(); //key from Friends
final FirebaseRecyclerAdapter<Users_Friends, UsersFriendViewHolder> firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter<Users_Friends, UsersFriendViewHolder>(
Users_Friends.class,
R.layout.users_single_friend_layout,
UsersFriendViewHolder.class,
filter
) {
#Override
protected void populateViewHolder(UsersFriendViewHolder viewHolder, Users_Friends users, int position) {
viewHolder.setDisplayName(users.getName());
viewHolder.setStatusUsers(users.getStatus());
viewHolder.setUserImage(users.getImage(), getContext().getApplicationContext());
final String user_id = getRef(position).getKey();
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent profileIntent = new Intent(getActivity(), ProfileActivity.class);
profileIntent.putExtra("user_id", user_id);
startActivity(profileIntent);
}
});
}
};
mReqList.setAdapter(firebaseRecyclerAdapter);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
You only need to use exists() method directly on the dataSnapshot object like this:
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child(current_id).exists()) {
Log.d("TAG", "User exists");
} else {
Log.d("TAG", "User does not exist");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
mFriendDatabase.addListenerForSingleValueEvent(eventListener);
If there's something I'm struggling with it's how to write good looking code with asynchronous calls to Firebase. Below is the code for one of my functions that retrieves all users and the current user from Firebase and checks the distance between their chosen locations.
I can't really move each of the ValueEventListeners to separate functions since they all have to fire in succession.
How do I make this code look good?
private void getUsersToDisplay() {
// Get users to display from firebase
Log.w(TAG, "User fetch initialized");
DatabaseReference currentUserRef = mDatabase.getReference().child("users/" + mCurrentUser.getUid());
// Get current user from firebase
currentUserRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot currentUserSnapshot) {
// Get the users chosen location for use in distance calculation
final Double currentUserChosenLatitude =
Double.parseDouble(currentUserSnapshot.child("chosen_location/latlng/latitude").getValue().toString());
final Double currentUserChosenLongitude =
Double.parseDouble(currentUserSnapshot.child("chosen_location/latlng/longitude").getValue().toString());
DatabaseReference usersRef = mDatabase.getReference().child("users");
// Get all users from firebase
usersRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot allUsersSnapshot) {
// For all users in firebase
for (DataSnapshot userSnap : allUsersSnapshot.getChildren()) {
String userId = userSnap.getKey();
DatabaseReference userRef = mDatabase.getReference().child("users/" + userId);
// If the user isn't the current user
if (!userId.equals(mCurrentUser.getUid())) {
// Get the user's info from firebase
userRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot userSnapshot) {
Double userChosenLatitude =
Double.parseDouble(userSnapshot.child("chosen_location/latlng/latitude").getValue().toString());
Double userChosenLongitude =
Double.parseDouble(userSnapshot.child("chosen_location/latlng/longitude").getValue().toString());
float[] results = new float[1];
Location.distanceBetween(
currentUserChosenLatitude,
currentUserChosenLongitude,
userChosenLatitude,
userChosenLongitude,
results);
// If the user is within 10km of the current user, display it
if (results[0] < 10000) {
users.put(userSnapshot.getKey(), (String) userSnapshot.child("first_name").getValue());
mUserAdapter.add((String) userSnapshot.child("first_name").getValue());
Log.w(TAG, "User to display fetch complete");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "User to display fetch cancelled");
}
});
}
}
Log.w(TAG, "Users fetch completed");
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "Users fetch cancelled");
}
});
Log.w(TAG, "Current user fetch complete");
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "Current user fetch cancelled");
}
});
}
I write my code like this so it easier to read:
onCreate() {
dataRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
doSomething(dataSnapshot);
...
}
...
}
}
doSomething(DataSnapshot dataSnapshot) {
...
}
If I want a Firebase call to run after another Firebase call, I place it inside doSomething.
BUT, if that call doesn't have to run after each other (like "get current user" and "get all user" call from your sample code), I made it like this:
boolean firstCallDone = false;
boolean secondCallDone = false;
DataSnapshot firstDataSnapshot = null;
DataSnapshot secondDataSnapshot = null;
onCreate() {
firstRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
firstCallDone = true;
firstDataSnapshot = dataSnapshot;
if (firsCallDone && secondCallDone)
doSomething();
}
...
}
secondRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
secondCallDone = true;
secondDataSnapshot = dataSnapshot;
if (firsCallDone && secondCallDone)
doSomething();
}
...
}
}
doSomething() {
// do something with firstDataSnapshot and secondDataSnapshot
...
}
Hope this help.
I'm trying to retrieve user's data from firebase using search by Email to find the user ID and use that ID to get the user's node children so i used that code to do that:
mSignin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mEmailStr = SignupActivityFragment.removeSpaces(mEmail.getText().toString());
mPasswordStr = mPassword.getText().toString();
mAuth.signInWithEmailAndPassword(mEmailStr, mPasswordStr).addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(Task<AuthResult> task) {
if (task.isSuccessful()){
getExistingUserInfo();
if(User!=null) {
sglstr = User.get("sgl");
if (sglstr.equals("true")) {
Intent intent = new Intent(getActivity(), ControllerSGL.class);
intent.putExtra("user", User);
startActivity(intent);
} else if (sglstr.equals("false")) {
Intent intent = new Intent(getActivity(), ControllerStudent.class);
intent.putExtra("user", User);
startActivity(intent);
}
}
else {
Toast.makeText(getActivity(), "NULL!!!!!!", Toast.LENGTH_SHORT).show();
}
Toast.makeText(getActivity(), "Success", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getActivity(), "Not Success", Toast.LENGTH_SHORT).show();
}
}
});
}
});
and getExistingUserInfo Method
public void getExistingUserInfo(){
FirebaseDatabase database = FirebaseDatabase.getInstance();
database.getReference().child("allUsers").orderByChild("emailAddress")
.equalTo(mEmailStr)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
uid = childSnapshot.getKey();
Log.v("HimaAbosalem",uid);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
database.getReference("allUsers").child(uid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//get user data from dataSnapshot
User=(HashMap<String,String>)dataSnapshot.getValue();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I need to use HashMap to send the data throw intent, but i gives me that java.lang.NullPointerException: Can't pass null for argument 'pathString' in child() at this part of getExistingUserInfo method
database.getReference("allUsers").child(uid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//get user data from dataSnapshot
User=(HashMap<String,String>)dataSnapshot.getValue();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
i thought the problem was uid value equal null but i made a log and it's not, and i tried to send that uid throw an intent to another activity and i recieved it to found it's not null but when i tried to get the data in that new Activity it gives the same Error!!!
I solved this problem by divide the getExistingUserInfo to two separate Function and call the function that get allUsers at onDataChange to guarantee that user's id returns
that's code after Edited:
public void getExistingUserInfo(){
FirebaseDatabase database = FirebaseDatabase.getInstance();
database.getReference().child("allUsers").orderByChild("emailAddress")
.equalTo(mEmailStr)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
uid = childSnapshot.getKey();
Log.v("HimaAbosalem",uid);
}
getUser(uid);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void getUser(String uid){
database.getReference("allUsers").child(uid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//get user data from dataSnapshot
User=(HashMap<String,String>)dataSnapshot.getValue();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}