androidfirebasefirebase-realtime-databasefirebase-authenticationmulti-user

How to retrieve a particular data from Firebase database


I'm doing an application where the user will be login is based on the role. One application for both Admin and employee.

Here when admin is loving in it should display a different dashboard, How can we do it, as of know I tired a bit to retrieved the role of the current user but for me it showing null pointer exception in the 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) {

            }
        });
    }
}

And my database looks like enter image description here

I want to check the condition whether the person is admin is user and then display activity based on that.

The error is been listed 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.

Solution

  • You cannot retrieve the uid before even signing in the application. Inside if(task.isSuccessful()){ do the following:

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

    Then you can use it in your dB reference


    Try the following to retrieve the role:

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