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

时间:2020-04-16 13:09:12

标签: android firebase firebase-realtime-database firebase-authentication multi-user

我正在做一个基于角色的用户将要登录的应用程序。管理员和员工均可使用的一个应用程序。

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

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

            }
        });
    }
}

我的数据库看起来像enter image description here

我要检查此人是否为管理员的条件是用户,然后根据该条件显示活动。

此错误已在此处列出

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.

1 个答案:

答案 0 :(得分:0)

即使登录应用程序,也无法检索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) {

            }
        });
    }