I am trying to read data from Firebase but it isn't working for me. There's already data in the database but it's saying the value is null when I use getUserFName. So the second code is from the register activity, which creates an authentication and an id for the database to be matched together. the id holds the data for the class UserInformation. So that's why I am wondering why I am getting a null object when there's data when I register.
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
UserInformation userInformation = new UserInformation();
userInformation.setUserFName(ds.child(userID).getValue(UserInformation.class).getUserFName());
userInformation.setUserLName(ds.child(userID).getValue(UserInformation.class).getUserLName());
userInformation.setUserEmail(ds.child(userID).getValue(UserInformation.class).getUserEmail());
userInformation.setUserDescription(ds.child(userID).getValue(UserInformation.class).getUserDescription());
fName.setText(userInformation.getUserFName());
lName.setText(userInformation.getUserLName());
email.setText(userInformation.getUserEmail());
aboutYou.setText(userInformation.getUserDescription());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
firebaseAuth.createUserWithEmailAndPassword(email.getText().toString().trim(), password.getText().toString().trim())
.addOnCompleteListener(NewUserActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(NewUserActivity.this, "Account Created. Sign in!", Toast.LENGTH_SHORT).show();
String id = firebaseAuth.getCurrentUser().getUid();
UserInformation userInformation = new UserInformation(firstName.getText().toString(), lastName.getText().toString(), email.getText().toString(),
password.getText().toString());
databaseReference.child(id).setValue(userInformation);
Intent created = new Intent(NewUserActivity.this, LoginActivity.class);
startActivity(created);
finish();
} else if (password.getText().toString().length() < 6){
Toast.makeText(NewUserActivity.this, "Password at least 6 characters", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
} else{
Toast.makeText(NewUserActivity.this, "Email already exists", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
});
You are reading from a wrong location.
databaseReference.child(userID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserInformation userInformation = dataSnapshot.getValue(UserInformation.class);
fName.setText(userInformation.getUserFName());
lName.setText(userInformation.getUserLName());
email.setText(userInformation.getUserEmail());
aboutYou.setText(userInformation.getUserDescription());
}
}
Also make sure you have read permission in Firebase database as in https://firebase.google.com/docs/database/security/quickstart
Related
I want to check that if classection=Six:B already exist in firebase database then it show toast message please guide I am trying to solve this from 3 days but I cannot solve it Here is my code it doesnot show any error or toast
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users");
Query query = ref.child("Students");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String classsection=""+dataSnapshot.child("classsection").getValue();
if(classsection.equals("Six:B"))
{
Toast.makeText(MaintabclasActivity.this, "Class Six B is Already Exist",
Toast.LENGTH_LONG).show();
}
else
{
// updateclasfiveb();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(MaintabclasActivity.this, "error",
Toast.LENGTH_LONG).show();
}
});
Instead of addListenerForSingleValueEvent ,use onCompleteListener to get data once if you really wants access real time database. because addListenerForSingleValueEvent is for cache data.
// If you have child node id to go through each node use below method.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users");
ref.child("Students").child("node_id_under_student").get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (!task.isSuccessful()) {
Log.e("firebase", "Error getting data", task.getException());
}
else {
Log.d("firebase", String.valueOf(task.getResult().getValue()));
}
}
});
// Or use query method with ValueEventListener to listen for changes in database.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users/Students");
Query databaseQuery= ref.orderByChild("classsection").equalTo("Six:B");
databaseQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
String classsection=""+dataSnapshot.child("classsection").getValue();
if(classsection.equals("Six:B"))
{
Toast.makeText(MaintabclasActivity.this, "Class Six B is Already Exist",
Toast.LENGTH_LONG).show();
}
else
{
// updateclasfiveb();
}}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// ...
}
});
A query in Firebase consists of two parts:
A call to order the child nodes of a path on its key, or a certain property.
A call to then filter the child nodes down by a certain value or range.
In your case:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users/Students");
Query query = ref.orderByChild("classsection").equalTo("Six:B");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
Toast.makeText(MaintabclasActivity.this, "Class Six B is Already Exist", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(MaintabclasActivity.this, "error", Toast.LENGTH_LONG).show();
}
});
This question already has answers here:
How to redirect multiple types of users to their respective Activities?
(3 answers)
Closed 3 years ago.
I have created a project which has two types of user (patient and doctor). During login, I need to retrieve the role attribute in the firebase which under the users table.
In my database structure, user type maybe is "doctor" or "patient". During login, I think I need to retrieve the role information and then assign them to different activity in android studio. However, my code seems doesn't work. The application keeps stopped. Is there anyone can help me. Thanks in advance.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
email = findViewById(R.id.email);
psd = findViewById(R.id.psd);
}
public void clicked(View v) {
switch (v.getId()) {
case R.id.login:
LoginUser();
break;
case R.id.register:
Intent intent = new Intent(this, ChooseRole.class);
startActivity(intent);
break;
}
}
public void LoginUser() {
String email1 = email.getText().toString().trim();
String psd1 = psd.getText().toString().trim();
mAuth.signInWithEmailAndPassword(email1, psd1)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
indentify();
finish();
} else {
Toast.makeText(Login.this, "couldn't login",
Toast.LENGTH_SHORT).show();
}
}
});
}
public void indentify() {
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseDatabase.getInstance().getReference(uid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
long points = dataSnapshot.child("role").getValue(Long.class);
String role = String.valueOf(points);
if(role=="patient"){
Intent intent = new Intent(Login.this, HomePage.class);
startActivity(intent);
}
else{
Intent intent = new Intent(Login.this, HomePage2.class);
startActivity(intent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
}
Hi guys, I changed it like this and it is successful. Thanks for everyone helping :D
public void LoginUser(){
String email1 = email.getText().toString().trim();
String psd1 = psd.getText().toString().trim();
mAuth.signInWithEmailAndPassword(email1, psd1)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
currentUser = mAuth.getCurrentUser();
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseDatabase.getInstance().getReference("users").child(uid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child("role").getValue(String.class).equals("patient")) {
startActivity(new Intent(Login.this, HomePage.class));
return;
}
if (dataSnapshot.child("role").getValue(String.class).equals("doctor")) {
startActivity(new Intent(Login.this, HomePage2.class));
return;
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
}else {
Toast.makeText(Login.this, "couldn't login",
Toast.LENGTH_SHORT).show();
}
}
});
}
Since in your database you have a node called users, then add a reference to that node, for example:
FirebaseDatabase.getInstance().getReference("users").child(uid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Then do the following:
Change this:
if(role=="patient"){
into this:
if(role.equals("patient")){
You need to use equals() when you want to compare the value of each object.
I'm new to android and fire base, so the first thing is that inside fire base I can add new value inside my child("post") without problem, but the thing is inside 0-40 seconds when a user try add new post the old user's post gets overwritten by the new user's post and the same thing happens with comments, when a user try to post a comment inside the post.
private void SavingPostInformationToDatabase()
{ UsersRef.child(current_user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String userFullName = dataSnapshot.child("fullname").getValue().toString();
String UserName = dataSnapshot.child("username").getValue().toString();
String userProfileImage = dataSnapshot.child("profileimage").getValue().toString();
HashMap postsMap = new HashMap();
postsMap.put("uid", current_user_id);
postsMap.put("date", saveCurrentDate);
postsMap.put("time", saveCurrentTime);
postsMap.put("description", Description);
postsMap.put("postimage", downloadUrl);
postsMap.put("profileimage", userProfileImage);
postsMap.put("fullname", userFullName);
postsMap.put("username", UserName);
postsMap.put("counter", CountPost);
PostsRef.child(current_user_id + postRandomName).updateChildren(postsMap)
.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
SendUserToMainActivity();
Toast.makeText(PostRecipeActivity.this, "New Post is updated successfully.", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
} else {
Toast.makeText(PostRecipeActivity.this, "Error Occured while updating your post.", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
Please help i want to retrieve a specific data from the Firebase Realtime database I have 2 users Professor and Student and i want to use that data for validations.
FireBase Realtime Database
firebaseAuth.signInWithEmailAndPassword(email,pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if(task.isSuccessful()){
//The task is successful || Task Login
Toast.makeText(getApplicationContext(),"Successfully Login",Toast.LENGTH_LONG).show();
// If the users is professor but if it is student go to userStudent.class
finish();
startActivity(new Intent(getApplicationContext(),userProf.class));
FireBase Realtime Database
This is what you are looking for
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference;
firebaseAuth.signInWithEmailAndPassword(email,pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if(task.isSuccessful()){
//The task is successful || Task Login
Toast.makeText(getApplicationContext(),"Successfully Login",Toast.LENGTH_LONG).show();
reference = FirebaseDatabase.getInstance().
getReference("dbname").child(user.getUid());
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String usertype=datas.child("user").getValue().toString();
// If the users is professor but if it is
// student go to userStudent.class
if(usertype.equals("Student")){
startActivity(new
Intent(getApplicationContext(),studentProfile.class));
finish();
}else if (usertype.equals("Professor")) {
startActivity(new
Intent(getApplicationContext(),professorProfile.class));
finish();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Try this code
firebaseAuth.signInWithEmailAndPassword(email,pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if(task.isSuccessful()){
//The task is successful || Task Login
Toast.makeText(getApplicationContext(),"Successfully Login",Toast.LENGTH_LONG).show();
//user UID
String userId = task.getResult().getUser().getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child(userId);
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String user = dataSnapshot.child("user").getValue(String.class);
if (user.equals("Student")) {
startActivity(new Intent(getApplicationContext(),userStudent.class));
} else if(user.equals("Professor")) {
startActivity(new Intent(getApplicationContext(),userProf.class));
}
finish();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
Hope it helps
I have a database in which I store users and I want to check if a user exists before adding a new one so I don't overwrite.
I have a function that goes through database records and returns a boolean value if it finds or doesn't find the user.
public boolean checkUserExists(final String emailAddress, final String emailDomain){
DatabaseReference myRef = database.getReference("Users");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot mydata : dataSnapshot.getChildren()){
User user = mydata.getValue(User.class);
if (user.getEmailAddress().equals(emailAddress) &&
user.getEmailDomain().equals(emailDomain)){
userExists = true;
break;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return userExists;
}
The way I am currently trying to do the check is like this:
if (!(registerRepo.checkUserExists(emailAddress, emailDomain))){
User user = new User(firsName, lastName, emailAddress, emailDomain);
registerRepo.writeUser(user);
} else {
Toast toast = Toast.makeText(getBaseContext(), "User exists", Toast.LENGTH_SHORT);
toast.show();
}
The problem is that it doesn't wait for the read and goes ahead and creates a new record (I'm using push so it creates the same record under a new push ID). I've seen that firebase has such a thing called transaction handler and I think that is what I need to use but the documentation didn't help me and I've looked at others asking sort-of the same question here but couldn't figure out a solution so please, if you can explain how to do it and not redirect me to other question I'd be grateful.
Firebase requests are asynchronous.
So you need to add a callback in your checkUserExists if you want to do some code after getting the result from database.
For example :
public interface OnCheckUserExist {
void exist();
void notExist();
}
registerRepo.checkUserExists(emailAddress, emailDomain, new OnCheckUserExist(){
#Override
public void exist(){
Toast toast = Toast.makeText(getBaseContext(), "User exists",Toast.LENGTH_SHORT);
toast.show();
}
#Override
public void notExist(){
User user = new User(firsName, lastName, emailAddress, emailDomain);
registerRepo.writeUser(user);
}
})
public void checkUserExists(final String emailAddress, final String emailDomain, OnCheckUserExist onCheckUserExist){
DatabaseReference myRef = database.getReference("Users");
myRef.addValueEventListener(new ValueEventListener() {
boolean userExist;
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot mydata : dataSnapshot.getChildren()){
User user = mydata.getValue(User.class);
if (user.getEmailAddress().equals(emailAddress) &&
user.getEmailDomain().equals(emailDomain)){
onCheckUserExist.exist();
userExist = true;
break;
}
}
if (!userExist){
onCheckUserExist.notExist();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
You need to put your code inside onDataChange like this
public boolean checkUserExists(final String emailAddress, final String emailDomain){
DatabaseReference myRef = database.getReference("Users");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot mydata : dataSnapshot.getChildren()){
User user = mydata.getValue(User.class);
if (user.getEmailAddress().equals(emailAddress) &&
user.getEmailDomain().equals(emailDomain)){
userExists = true;
break;
}
}
if (userExists) {
User user = new User(firsName, lastName, emailAddress, emailDomain);
registerRepo.writeUser(user);
} else {
Toast toast = Toast.makeText(getBaseContext(), "User exists", Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return userExists;
}
Though I would suggest you to refactor this one by creating separate functions. :)