cannot be cast to com.google.firebase.database.DatabaseReference - java

Hi I'm creating a simple login system. I have 2 users of my application
user
admin
I'm trying that if the user login app intends to user activity and if the admin login app intents to admin activity.
For this, I am passing a String "admin" when the new admin register and "user" went the new user register, And in Login Activity, I match these String but this error occurs.
mAuth.signInWithEmailAndPassword(dbemail, dbpassword)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
FirebaseUser users = FirebaseAuth.getInstance().getCurrentUser();
if (users != null){
DatabaseReference databaseReference = (DatabaseReference) FirebaseDatabase.getInstance().getReference().child("users")
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.child("as").equals("Admin")){
startActivity(new Intent(LoginActivity.this,MainActivity.class));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
else {
Toast.makeText(LoginActivity.this, "Failed to login! Please check your credentials", Toast.LENGTH_LONG).show();
}
}
else {
Toast.makeText(LoginActivity.this, "This account don't exist! Create Account", Toast.LENGTH_LONG).show();
}
}
});

addValueEventListener method returns ValueEventListener type, not DatabaseReference so it cannot be cast.
If you don't need DatabaseReference object, it should be enough:
FirebaseDatabase.getInstance().getReference().child("users")
.addValueEventListener(...);

Related

firebase realtime database push infinite loop error

I'm using firebase authentication with email and password.
So I want to save user data in realtime database .
But when i push the data to database, infinite loop was executing.
I don't know why..
I want to save data like this form and continue saving.
But when I starting, infinite loop is starting
private void createUser(String email, String password,String name, String phone, String
nickname) {
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) { //Join Success
Toast.makeText(JoinActivity.this, "Join Success", Toast.LENGTH_SHORT).show();
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(firebaseAuth.getCurrentUser()!=null) {
String email=editTextEmail.getText().toString().trim();
FirebaseUser user=firebaseAuth.getCurrentUser();
String uid=user.getUid();
if(dataSnapshot.child("USER").child("user_info").child(uid).exists()){
Toast.makeText(JoinActivity.this,"already exist",Toast.LENGTH_SHORT).show();
}else{
User user_info = new User(uid, editTextId.getText().toString(), editTextEmail.getText().toString(), editTextPassword.getText().toString(),
editTextname.getText().toString(), editTextNickname.getText().toString(), editTextPhone.getText().toString());
//delete all data
mDatabase.setValue(null);
String key = mDatabase.child("USER").push().getKey();
// mDatabase.child("USER").child("user_info").child(key).setValue(user_info);
Toast.makeText(JoinActivity.this, "save the data", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Intent intent = new Intent(JoinActivity.this, MainActivity.class);
startActivity(intent);
} else { //already exists
Toast.makeText(JoinActivity.this, "already exists", Toast.LENGTH_SHORT).show();
return;
}
}
});
}
}
Instead of :
mDatabase.addValueEventListener(new ValueEventListener() {
Use the following:
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
This way you will retrieve data only once.

Validate if data already exist in firebase

I am trying to find if the data already exist in the database. However it doesn't enter the loop. It always go to the else
This is my validation part, it always goes to the else part
full code is in pastebin
private void validate(final String Song) {
final DatabaseReference RootRef;
RootRef = FirebaseDatabase.getInstance().getReference();
RootRef.addListenerForSingleValueEvent(new ValueEventListener()
{
public void onDataChange(DataSnapshot dataSnapshot)
{
if (!(dataSnapshot.child("Participants").child(Song).exists()))
{
HashMap<String, Object> userdataMap = new HashMap<>();
userdataMap.put("song", Song);
RootRef.child("Participants").child(Song).updateChildren(userdataMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if (task.isSuccessful())
{
Toast.makeText(Register.this, "This song already exists.", Toast.LENGTH_SHORT).show();
}
}
});
}
else {
Toast.makeText(Register.this, "Your have choosed your song", Toast.LENGTH_SHORT).show();
// Toast.makeText(Register.this, "Please try again.", Toast.LENGTH_SHORT).show();
}}
public void onCancelled(DatabaseError databaseError) {
}
});
}
RootRef = FirebaseDatabase.getInstance().getReference().child("Participants").child(Song);
RootRef.addListenerForSingleValueEvent(new ValueEventListener()
{
public void onDataChange(DataSnapshot dataSnapshot)
{
if (dataSnapshot.exists())
{
Toast.makeText(Register.this, "This song already exists.", Toast.LENGTH_SHORT).show();
}
else {
HashMap<String, Object> userdataMap = new HashMap<>();
userdataMap.put("song", Song);
RootRef.setValue(userdataMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if (task.isSuccessful())
{
Toast.makeText(Register.this, "This song successfully added", Toast.LENGTH_SHORT).show();
}
}
});
}}
public void onCancelled(DatabaseError databaseError) {
}
});
If you want to check exist a song, you can give it as a reference. If datasnapshot is exists then your database has the song. If not, you can add the song to the database.

Couldn't get the output "Username has been used!" when I have entered the username that has been stored in the database

This's the database structure
Database Reference
DatabaseReference referSales;
referSales = FirebaseDatabase.getInstance().getReference("Sales");
Username Validation (Including Password Validation )
referSales.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(!(edtPassword.getText().toString()).equals(edtConfirmPassword.getText().toString())) {
loadingDialog.dismiss();
Toast.makeText(Registration.this, "Password and Confirm Password are not identical!", Toast.LENGTH_SHORT).show();
if(dataSnapshot.child(edtUsername.getText().toString()).exists()){
loadingDialog.dismiss();
Toast.makeText(Registration.this, "Username has been used!", Toast.LENGTH_SHORT).show();
}
Update Database
When the username entered is not duplicated with the username stored in the database, the password and confirm password are identical, the new user information will be added to the database.
}else{
loadingDialog.dismiss();
final Sales salesperson = new Sales(edtFirstName.getText().toString(),edtLastName.getText().toString(),
edtPhoneNo.getText().toString(),edtEmail.getText().toString(), edtUsername.getText().toString(),
edtPassword.getText().toString(),edtConfirmPassword.getText().toString());
referSales.child(edtUsername.getText().toString()).setValue(salesperson).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> salesperson) {
if(salesperson.isSuccessful()){
Toast.makeText(Registration.this, "Added Successfully!", Toast.LENGTH_SHORT).show();
finish();
}
}
});
}
}
You can query the database for the to check if the username has already been used in your database.
Query query = databaseReference.child("users").orderByChild("userName")
.equalTo(edtUserName.getText().toString().trim();
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
//user exist
Toast.makeText(getApplicationContext(),"Usename Has been used" ,
Toast.LENGTH_LONG).show();
}else{
//CREATE THE USER
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});

I want to open three different activity when I login with their respective roles from firebase database

I have three roles in my firebase database
teacher
Student
coordinator.
In that, if I log in with teacher then it should check role from the database and open teacher activity. Same for student and coordinator.
** Code:**
firebaseAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(Login_Form.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Intent intent = new Intent(Login_Form.this, Adminpage.class);
progressDialog.dismiss();
startActivity(intent);
} else {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Login Failed Or User Not Available", Toast.LENGTH_LONG).show();
}
I have tried with this one
firebaseAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(Login_Form.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Intent intent = new Intent(Login_Form.this, Adminpage.class);
progressDialog.dismiss();
startActivity(intent);
} else {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Login Failed Or User Not Available", Toast.LENGTH_LONG).show();
}
While login , you must be using either phone number or email Id .
If so , then you can fetch the result using the entered email id .
postRef.orderByChild("email").equalTo(email)
.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onCancelled(p0: DatabaseError) {
}
override fun onDataChange(dataSnapshot: DataSnapshot) {
if (dataSnapshot.exists()) {
val userData: HashMap<String, User> = dataSnapshot.value as HashMap<String, User>
var userId :String = ""
userData.keys.forEach { userId =it}
Toast.makeText(this#SplashActivity,"Welcome Back . Happy to see you again" ,Toast.LENGTH_SHORT).show()
startHomeActivity()
}
}
})
In above , i have check if the email is present in the firebase database or not . Once it get success, then we have dataSnapshot in which you will get complete data associated with that email id .There you can check if its teacher , student etc.
There is a check if dataSnapshot is empty or not just to ensure your dataSnapshot is having user data.
val userData: HashMap<String, User> = dataSnapshot.value as HashMap<String, User>
This will give you the entire data of your entry .

Firebase get uid from email

I would like to get a uid from inputing an email for making it possible to add friends with an email.
Here is what I have gotten so far:
final DatabaseReference mRef = FirebaseDatabase.getInstance().getReference().child("users");
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
final String currentUserUid = user.getUid();
mRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild(uid)) {
DatabaseReference newRef = mRef.child(uid);
newRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChild(uid)) {
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
String username = String.valueOf(dataSnapshot.child("username").getValue());
String email = String.valueOf(dataSnapshot.child("email").getValue());
String firebaseToken = String.valueOf(dataSnapshot.child("firebaseToken").getValue());
Friend friend = new Friend(uid, username, email, firebaseToken);
database.child(Constants.ARG_USERS)
.child(currentUserUid)
.child(Constants.ARG_FRIENDS)
.child(uid)
.setValue(friend)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
mOnFriendDatabaseListener.onSuccess(context.getString(R.string.friend_successfully_added));
} else {
mOnFriendDatabaseListener.onFailure(context.getString(R.string.friend_unable_to_add));
}
}
});
} else {
Log.d("Adding Friend", "User already not exist");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
Log.d("Adding Friend", "User does not exist");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
This works if I input an uid directly but I would like to have my input be an email and get an uid out from it, or if there are other solutions please suggest.
This is how the database structure looks like:
Thanks for the help in advance.
To search for a user by their email address you need to order/filter on that property:
Query query = mRef.orderByChild("email").equalTo("example#example.com");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// There may be multiple users with the email address, so we need to loop over the matches
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
System.out.println(userSnapshot.getKey());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "find email address:onCancelled", databaseError.toException());
// ...
}
});
Not directly related to the question, but please restructure your data to remove the nesting of friends and profiles. For many reasons it's best to keep your Firebase data structure flat and separate user profiles from friends lists.
/users
uid1: ... profile for user 1
uid2: ... profile for user 2
/friends
uid1: ... friends list for user 1
uid2: ... friends list for user 2

Categories

Resources