检查 Firebase 实时数据库中的值是否等于 String [英] Check if value in Firebase Realtime Database is equal to String

查看:17
本文介绍了检查 Firebase 实时数据库中的值是否等于 String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户登录我的应用程序时,我想检查 userType 是客户"还是场地所有者".这决定了接下来运行哪个活动.目前,应用程序在尝试登录时崩溃.

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.

这是我的 Firebase 实时数据库结构:

Here is my Firebase Realtime database structure:

相关代码如下:

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)

这是整个班级:

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

}

推荐答案

要解决这个问题,请使用以下几行代码:

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.

这篇关于检查 Firebase 实时数据库中的值是否等于 String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆