Check if value in Firebase Realtime Database is equal to String [duplicate]

我只是一个虾纸丫 提交于 2020-12-23 08:19:26

问题


When a user logs in on my application, I want to check if the userType is a "Customer" or a "Venue Owner". This decides which activity is run next. Currently, the application crashes when attempting to log in.

Here is my Firebase Realtime database structure:

two muppets

Here is the related code:

public void loginUser(View v)
{
    if(e1.getText().toString().equals("") && e2.getText().toString().equals(""))
    {
        Toast.makeText(getApplicationContext(),"Blank fields not allowed", Toast.LENGTH_SHORT).show();
    }
    else
    {
        auth.signInWithEmailAndPassword(e1.getText().toString(),e2.getText().toString())
                .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if(task.isSuccessful())
                        {
                            Toast.makeText(getApplicationContext(),"User logged in successfully",Toast.LENGTH_SHORT).show();
                            finish();


                            //Intent i = new Intent(getApplicationContext(),ProfileActivity.class);
                            //startActivity(i);
                            DatabaseReference mDatabaseReference = FirebaseDatabase.getInstance().getReference();
                            mDatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
                                public void onDataChange(DataSnapshot dataSnapshot) {
                                    //String userType = dataSnapshot.getValue(String.class);

                                    String userType = (String) dataSnapshot.child("userType").getValue();
                                    if (userType.equals("Customer")) {
                                        Intent i = new Intent(getApplicationContext(), UserMainPageActivity.class);
                                        startActivity(i);

                                    } else {
                                        Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
                                        startActivity(i);
                                    }
                                }

                                @Override
                                public void onCancelled(@NonNull DatabaseError databaseError) {

                                }
                            });
                        }
                        else
                        {
                            Toast.makeText(getApplicationContext(),"User could not be logged in",Toast.LENGTH_SHORT).show();
                        }
    }
});
    }
}

As requested, here is the crash log:

01-31 13:35:14.348  5322  5322 E AndroidRuntime: FATAL EXCEPTION: main
01-31 13:35:14.348  5322  5322 E AndroidRuntime: Process: 
com.example.myapplication, PID: 5322
01-31 13:35:14.348  5322  5322 E AndroidRuntime: 
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean 
java.lang.String.equals(java.lang.Object)' on a null object reference
01-31 13:35:14.348  5322  5322 E AndroidRuntime:        at 
com.example.myapplication.LoginActivity$1$1.onDataChange(
LoginActivity.java:66 01-31 13:35:14.348  5322  5322 E AndroidRuntime:        
at com.google.firebase.database.zzp.onDataChange(Unknown Source)
01-31 13:35:14.348  5322  5322 E AndroidRuntime:        at 
com.google.android.gms.internal.firebase_database.zzfc.zza(Unknown Source)
01-31 13:35:14.348  5322  5322 E AndroidRuntime:        at 
com.google.android.gms.internal.firebase_database.zzgx.zzdr(Unknown Source)
01-31 13:35:14.348  5322  5322 E AndroidRuntime:        at 
com.google.android.gms.internal.firebase_database.zzhd.run(Unknown Source)
01-31 13:35:14.348  5322  5322 E AndroidRuntime:        at 
android.os.Handler.handleCallback(Handler.java:746)
01-31 13:35:14.348  5322  5322 E AndroidRuntime:        at 
android.os.Handler.dispatchMessage(Handler.java:95)
01-31 13:35:14.348  5322  5322 E AndroidRuntime:        at 
android.os.Looper.loop(Looper.java:148)
01-31 13:35:14.348  5322  5322 E AndroidRuntime:        at 
android.app.ActivityThread.main(ActivityThread.java:5443)
01-31 13:35:14.348  5322  5322 E AndroidRuntime:        at 
java.lang.reflect.Method.invoke(Native Method)
01-31 13:35:14.348  5322  5322 E AndroidRuntime:        at 
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run
(ZygoteInit.java:728)
01-31 13:35:14.348  5322  5322 E AndroidRuntime:        at 
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)

Here is the entire class:

    package com.example.myapplication;

    import android.content.Intent;
    import android.support.annotation.NonNull;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.EditText;
    import android.widget.Toast;

    import com.google.android.gms.tasks.OnCompleteListener;
    import com.google.android.gms.tasks.Task;
    import com.google.firebase.auth.AuthResult;
    import com.google.firebase.auth.FirebaseAuth;
    import com.google.firebase.database.DataSnapshot;
    import com.google.firebase.database.DatabaseError;
    import com.google.firebase.database.DatabaseReference;
    import com.google.firebase.database.FirebaseDatabase;
    import com.google.firebase.database.ValueEventListener;

    public class LoginActivity extends AppCompatActivity {

EditText e1,e2;

FirebaseAuth auth;

private static final String TAG = "MainActivity";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    e1 = (EditText)findViewById(R.id.editText);
    e2 = (EditText)findViewById(R.id.editText2);

    auth = FirebaseAuth.getInstance();
}

public void loginUser(View v)
{
    if(e1.getText().toString().equals("") && e2.getText().toString().equals(""))
    {
        Toast.makeText(getApplicationContext(),"Blank fields not allowed", Toast.LENGTH_SHORT).show();
    }
    else
    {
        auth.signInWithEmailAndPassword(e1.getText().toString(),e2.getText().toString())
                .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if(task.isSuccessful())
                        {
                            Toast.makeText(getApplicationContext(),"User logged in successfully",Toast.LENGTH_SHORT).show();
                            finish();

                            //Intent i = new Intent(getApplicationContext(),ProfileActivity.class);
                            //startActivity(i);

                            String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
                            DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
                            DatabaseReference uidRef = rootRef.child(uid);
                            uidRef.addListenerForSingleValueEvent(new ValueEventListener() {
                                @Override
                                public void onDataChange(DataSnapshot dataSnapshot) {
                                    if(dataSnapshot.child("userType").equals("Customer")) {
                                        startActivity(new Intent(getApplicationContext(), UserMainPageActivity.class));
                                    } else if (dataSnapshot.child("userType").equals("Venue Owner")) {
                                        startActivity(new Intent(getApplicationContext(), ProfileActivity.class));
                                    }
                                }

                                @Override
                                public void onCancelled(@NonNull DatabaseError databaseError) {
                                    Log.d(TAG, databaseError.getMessage());
                                }
                            });
                        }
                        else
                        {
                            Toast.makeText(getApplicationContext(),"User could not be logged in",Toast.LENGTH_SHORT).show();
                        }
            }
        });
    }
}

}


回答1:


To solve this, please use the following lines of code:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if(dataSnapshot.child("userType").getValue(String.class).equals("Customer")) {
            startActivity(new Intent(getApplicationContext(), UserMainPageActivity.class));
        } else if (dataSnapshot.child("userType").getValue(String.class).equals("Venue Owner")) {
            startActivity(new Intent(getApplicationContext(), ProfileActivity.class));
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d(TAG, databaseError.getMessage());
    }
};
uidRef.addListenerForSingleValueEvent(valueEventListener);

Using this code the user will be redirected to the corresponding activity.




回答2:


You have to get the children of the datasnapshot. Since the response comes as child of datasnapshot. Something like this.

      public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
               String userType = (String) dataSnapshot.child("userType").getValue();
            if (userType.equals("Customer")) {
                       Intent i = new Intent(getApplicationContext(), 
                       UserMainPageActivity.class);
                      startActivity(i);

            } else {
    I          Intent i = new Intent(getApplicationContext(), 
                ProfileActivity.class);
                   startActivity(i);
                 }
             }
        }


来源:https://stackoverflow.com/questions/54461377/check-if-value-in-firebase-realtime-database-is-equal-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!