如何从 Firebase 数据库中检索特定数据

How to retrieve a particular data from Firebase database

我正在做一个用户将基于角色登录的应用程序。管理员和员工都需要一份申请。

在这里,当管理员喜欢它时,它应该显示一个不同的仪表板,我们该怎么做,据我所知,我有点厌倦了检索当前用户的角色,但对我来说,它在 firebaseuser 中显示空指针异常.

 package com.example.loginregistration;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
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.auth.FirebaseUser;
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.Query;
import com.google.firebase.database.ValueEventListener;
import com.rengwuxian.materialedittext.MaterialEditText;

public class MainActivity extends AppCompatActivity {

    MaterialEditText email,password;
    Button login, register;
    FirebaseAuth fAuth;
    FirebaseUser User;
    DatabaseReference reff;
    String Role="";
    CheckBox loginstate;
    Query query,query1;

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

        email = findViewById(R.id.email);
        password = findViewById(R.id.password);
        fAuth = FirebaseAuth.getInstance();
        //loginstate = findViewById(R.id.checkbox);
        login = findViewById(R.id.login);
        register = findViewById(R.id.register);




        //query = FirebaseDatabase.getInstance().getReference().child("Employee").orderByChild("role");
        //query1 = FirebaseDatabase.getInstance().getReference().child("Employee").orderByChild(User.getUid()).equalTo("role");

        //final Query query1 = FirebaseDatabase.getInstance().getReference().child("Employee").orderByChild("Role").equalTo("User");


        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //String txtUserName = userName.getText().toString();
                String txtEmail = email.getText().toString().trim();
                String txtPassword = password.getText().toString().trim();
                //String txtMobile = mobile.getText().toString();

                if (TextUtils.isEmpty(txtEmail)){
                    email.setError("Email is Required.");
                    return;
                }

                if (TextUtils.isEmpty(txtPassword)){
                    password.setError("Password is Required.");
                    return;

                }

                if (password.length() < 6){

                    password.setError("Password must be more than 6 characters.");
                    return;

                }


                fAuth.signInWithEmailAndPassword(txtEmail,txtPassword).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()){

                            retrieve();

                            String user = task.getResult().getUser().getUid();



                            if (Role.equals("Admin")){
                                Toast.makeText(MainActivity.this,"Logged in successfully.",Toast.LENGTH_SHORT).show();
                                startActivity(new Intent(getApplicationContext(),AppStartActivity.class));
                            }
                            else {
                                Toast.makeText(MainActivity.this,"Logged in successfully.",Toast.LENGTH_SHORT).show();
                                startActivity(new Intent(getApplicationContext(),AppStartActivity.class));
                            }

                        }

                        /*else if (task.isSuccessful() && Role.equals("User")) {
                            Toast.makeText(MainActivity.this,"Logged in successfully.",Toast.LENGTH_SHORT).show();
                            startActivity(new Intent(getApplicationContext(),EmpStarActivity.class));
                        }
*/
                        else {
                            Toast.makeText(MainActivity.this, "Error ! " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();

                        }
                    }
                });

            }
        });
    }

    private void retrieve(){
        User = fAuth.getCurrentUser();

        reff = FirebaseDatabase.getInstance().getReference().child(User.getUid());

        reff.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                        /*for (DataSnapshot snap : dataSnapshot.getChildren())
                        {*/
                //Employee student = dataSnapshot.getValue(Employee.class);
                //Log.d("TAG","name: "+student.getRole());

                //Role = dataSnapshot.child("Admin").getValue(String.class);


                String Role = dataSnapshot.child("role").getValue().toString();
                //String prize = dataSnapshot.child("prize").getValue().toString();
                Log.e("Role", Role);

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }
}

我的数据库看起来像

我想检查这个人是admin是不是user的条件,然后据此显示activity。

这里列出了错误

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
        at com.example.loginregistration.MainActivity.onCreate(MainActivity.java:53)
        at android.app.Activity.performCreate(Activity.java:7136)
        at android.app.Activity.performCreate(Activity.java:7127)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:193) 
        at android.app.ActivityThread.main(ActivityThread.java:6669) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 
2020-04-16 19:02:12.431 1943-1978/system_process E/BatteryExternalStatsWorker: no controller energy info supplied for wifi
2020-04-16 19:02:13.267 1622-2110/? E/AudioPolicyIntefaceImpl: getInputForAttr permission denied: recording not allowed for uid 10023 pid 3445
2020-04-16 19:02:13.267 1622-2110/? E/AudioFlinger: createRecord() checkRecordThread_l failed
2020-04-16 19:02:13.267 3445-18622/com.google.android.googlequicksearchbox:search E/IAudioFlinger: createRecord returned error -22
2020-04-16 19:02:13.267 3445-18622/com.google.android.googlequicksearchbox:search E/AudioRecord: AudioFlinger could not create record track, status: -22
2020-04-16 19:02:13.267 3445-18622/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -22.
2020-04-16 19:02:13.269 3445-18622/com.google.android.googlequicksearchbox:search E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
2020-04-16 19:02:13.272 3445-18622/com.google.android.googlequicksearchbox:search E/ActivityThread: Failed to find provider info for com.google.android.apps.gsa.testing.ui.audio.recorded
2020-04-16 19:02:18.343 1622-2110/? E/AudioPolicyIntefaceImpl: getInputForAttr permission denied: recording not allowed for uid 10023 pid 3445
2020-04-16 19:02:18.343 1622-2110/? E/AudioFlinger: createRecord() checkRecordThread_l failed
2020-04-16 19:02:18.344 3445-18622/com.google.android.googlequicksearchbox:search E/IAudioFlinger: createRecord returned error -22
2020-04-16 19:02:18.344 3445-18622/com.google.android.googlequicksearchbox:search E/AudioRecord: AudioFlinger could not create record track, status: -22
2020-04-16 19:02:18.345 3445-18622/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -22.
2020-04-16 19:02:18.346 3445-18622/com.google.android.googlequicksearchbox:search E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
2020-04-16 19:02:18.347 3445-18622/com.google.android.googlequicksearchbox:search E/ActivityThread: Failed to find provider info for com.google.android.apps.gsa.testing.ui.audio.

您甚至无法在登录应用程序之前检索 uid。 在 if(task.isSuccessful()){ 中执行以下操作:

String user = task.getResult().getUser().getUid();

然后您可以在您的 dB 参考中使用它


尝试以下方法检索角色:

private void retrieve(){
        //User = fAuth.getCurrentUser();

        reff = FirebaseDatabase.getInstance().getReference().child("Employee").child("Admin");

        reff.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                        /*for (DataSnapshot snap : dataSnapshot.getChildren())
                        {*/
                //Employee student = dataSnapshot.getValue(Employee.class);
                //Log.d("TAG","name: "+student.getRole());

                //Role = dataSnapshot.child("Admin").getValue(String.class);


                String Role = dataSnapshot.child("role").getValue().toString();
                //String prize = dataSnapshot.child("prize").getValue().toString();
                Log.e("Role", Role);

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }