Retrieving Specific Data from Firebase Realtime Database - java

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

Related

Firebase .removeValue() adds deleted element automatically

So I'm new to firebase and i have a problem with the method .removeValue(), everytime that method is executed the addOnCompleteListener does not throw any exceptions and execute the .removeValue() method correctly by removing the element but the element keeps adding by itself after the deletion,
I'm trying to do a friend's list where i check the condition if there is a friend request or is the 2 users are actually friends, So i wrote this code on the onStart method to assign the stats variable a value according to these conditions:
#Override
protected void onStart() {
super.onStart();
if(profileUid.equals(userId)){
sendAccept.setVisibility(View.INVISIBLE);
}else {
friendDatabaseReference.child(userId).child(profileUid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String status = dataSnapshot.child("Status").getValue().toString();
if (status.equals("recieved")) {
sendAccept.setVisibility(View.VISIBLE);
sendAccept.setText("Accept Request");
cancelRequest.setText("Cancel friend Request");
cancelRequest.setVisibility(View.VISIBLE);
stats = "recieved";
} else if (status.equals("sent")) {
stats = "sent";
sendAccept.setText("Cancel Friend Request");
}
} else {
friendDatabaseReference1.child(userId).child(profileUid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
stats = "friends";
sendAccept.setText("UnFriend");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
Everything runs well there and the values are assigned correctly. After that depending of the value of stats these conditions can happen(These sendAccept.setOnClickistener()) is on the onCreate() method:
sendAccept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (stats.equals("none")) {
friendDatabaseReference.child(userId).child(profileUid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()) {
friendDatabaseReference.child(userId).child(profileUid).child("Status").setValue("sent").addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
friendDatabaseReference.child(profileUid).child(userId).child("Status").setValue("recieved").addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
stats = "sent";
sendAccept.setText("Cancel Friend Request");
}
}
});
}
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}else if(stats.equals("recieved")){
friendDatabaseReference1.child(userId).child(profileUid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
friendDatabaseReference1.child(userId).child(profileUid).child("friends").setValue("yes")
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
friendDatabaseReference1.child(profileUid).child(userId).child("friends").setValue("yes")
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
stats = "friends";
sendAccept.setText("Unfriend");
cancelRequest.setVisibility(View.INVISIBLE);
friendDatabaseReference.child(userId).child(profileUid).removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
friendDatabaseReference.child(profileUid).child(userId)
.removeValue().addOnCompleteListener(
new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
}
});
}
}
});
}
}
});
}
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}else if(stats.equals("sent")){
friendDatabaseReference.child(userId).child(profileUid).removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
friendDatabaseReference.child(profileUid).child(userId).removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
stats = "none";
sendAccept.setText("Send Friend Request");
if(task.isSuccessful()){
Toast.makeText(getApplicationContext(), "Asi que prende", Toast.LENGTH_LONG).show();
}
}
});
}
}
});
}else{
friendDatabaseReference1.child(userId).child(profileUid).removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
friendDatabaseReference1.child(profileUid).child(userId).removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
sendAccept.setText("Send Friend Request");
stats = "none";
}
});
}
}
});
}
}
});
These are my declared instances of FirebaseDatabase where i point out where the data will be or will be removed(these are also on the onCreate() method:
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
friendDatabaseReference = FirebaseDatabase.getInstance().getReference().child("friend_req");
friendDatabaseReference1 = FirebaseDatabase.getInstance().getReference().child("Friends");
The conditions don't throw any errors nor exceptions, and all the assigns are working well and finally the firebase deletes the record, but add it again after the deletion

how to delete the auto generated item from push method from Firebase Real-time database

I am new to Firebase and I am facing a problem in delete an item from the recycler view I created. but I am unable to understand how to delete items using an auto-generated key. This is how I added item into the database:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("categories");
String key = reference.push().getKey();
reference.child(key).setValue(categoryData).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(add_category.this, "Category added", Toast.LENGTH_SHORT).show();
finish();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(add_category.this, "Failed to add", Toast.LENGTH_SHORT).show();
}
});
As in your comment, if you want to delete, for example, the second item, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference secondChildRef = rootRef.child("categories").child("-M1qUEGi0u4rX5Ju59r4");
secondChildRef.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d("TAG", "Second item deleted!");
}
}
});
So to delete a particular item, you to know its ID so you can add it to the reference.

Direct to each activity according to type of user [duplicate]

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.

Loop trying to delete account on Firebase database

My main goal is to delete an account on both Firebase Auth and Firebase Database. I'm using an interface to synchronize the reception of data, a button to delete and a function to return my User.
Initial variables:
FirebaseAuth mAuth = FirebaseAuth.getInstance();
final FirebaseUser mUser = mAuth.getCurrentUser();
DatabaseReference mUserRef = FirebaseDatabase.getInstance().getReference("Users");
The interface:
public interface IMyInterface {
void returnUser(User user);
}
The button to delete User:
btnDeleteAccount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
readUser(new IMyInterface() {
#Override
public void returnUser(User user) {
String email = user.getEmail();
String password = user.getPassword();
Log.d("EMAIL+PASSWORD", email+password);
AuthCredential credential = EmailAuthProvider
.getCredential(user.getEmail(), user.getPassword());
mUser.reauthenticate(credential).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()) {
mUser.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
mUserRef.child(mUser.getUid()).removeValue();
mAuth.signOut();
finish();
startActivity(new Intent(MainActivity.this, LoginActivity.class));
Toast.makeText(MainActivity.this, "User account deleted!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
}
});
}
});
And the function to retrieve a User with user informations:
private void readUser(final IMyInterface myCallback) {
mUserRef.child(mUser.getUid()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
user = dataSnapshot.getValue(User.class);
myCallback.returnUser(user);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
So, after calling the button, it calls the function to receive the user informations (email and password) and then it uses both information to delete and log out. The problem is that when the last command inside the button ends, it restarts the button at String email = user.getEmail(), but since it does not have an User instantiated, the getEmail() method returns null and the app crashes.
Why is it returning again the method? Or is there something about synchronization which I'm missing? I do have another button which ends when User info is used and it needs to change activity.
You have this behaviour because you are using addValueEventListener method instead of addListenerForSingleValueEvent. Mosty, both do the same thing but there is a difference, addListenerForSingleValueEvent disconnects straight after getting the data, while addValueEventListener keeps listening.
So to sovle this, use the addListenerForSingleValueEvent method or remove the listener according to the life-cycle of your activity.

getting a null object reference when trying to receive data from firebase

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

Categories