检查Firebase Realtime数据库中的值是否等于String

时间:2019-01-31 13:10:21

标签: java android firebase firebase-realtime-database

当在我的应用程序的用户日志,我要检查,如果用户类型是“客户”或“场馆业主”。这决定了下一步运行哪个活动。当前,尝试登录时应用程序崩溃。

下面是我的火力地堡实时数据库结构:

two muppets

这是相关代码:

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();
                        }
    }
});
    }
}

根据要求,以下是崩溃日志:

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)

这是整个班级:

    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();
                        }
            }
        });
    }
}

}

2 个答案:

答案 0 :(得分:2)

要解决此问题,请使用以下代码行:

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);

使用此代码,用户将被重定向到相应的活动。

答案 1 :(得分:0)

您必须获取数据快照的子级。由于响应来自datasnapshot的子级。 像这样的东西。

      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);
                 }
             }
        }