Search code examples
androidfirebasefirebase-authenticationuniqueidentifier

Why is firebase authentication returning null?


I am trying to implement Firebase anonymous authentication and obtain a unique ID from the application but it keeps running into a null UID error. I have used the following block of code for the anonymous login and getting the UID of the user:

// Firebase Anonymous Auth
        firebaseAuth = FirebaseAuth.getInstance();
        firebaseUser = firebaseAuth.getCurrentUser();

        if(firebaseUser == null){
            firebaseAuth.signInAnonymously()
                    .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            if (task.isSuccessful()) {
                                // Sign in success, update UI with the signed-in user's information
                                firebaseUser = firebaseAuth.getCurrentUser();
                                currentUserID = firebaseUser.getUid();
                            }
                        }
                    });
        }

I followed the directions given in the Firebase documentation but it doesn't work for some reason. Whenever I try to reference the currentUserID it returns the error : Attempt to invoke virtual method 'void com.example.rllauncher.TouchData.setUniqueID(java.lang.String)' on a null object reference

I've been trying to narrow down the problem but most implementations of Anonymous Login have been done this way only so I am not able to narrow down the problem source. What exactly is causing the issue here?

Here's the full Activity code:

public class ButtonPress extends AppCompatActivity implements View.OnClickListener {
    private Button button;
    private DisplayMetrics displaymetrics;
    private RelativeLayout loOPenArea;
    private Handler mHandler = new Handler();
    private String currentUSerID;
    String TASK_NAME = "ButtonPress";

    FirebaseAuth mAuth = FirebaseAuth.getInstance();
    FirebaseUser mFirebaseUser = mAuth.getCurrentUser();
    String mCurrentUserID = mFirebaseUser != null
            ? mFirebaseUser.getUid()
            : null;

    FirebaseAuth.AuthStateListener mAuthListener = new FirebaseAuth.AuthStateListener() {
        @NonNull
        @Override
        public void onAuthStateChanged(FirebaseAuth auth) {
            mFirebaseUser = auth.getCurrentUser();
            if (mFirebaseUser == null) {
                // user has been confirmed to be signed out
                // reset state, detach listeners, etc
                mCurrentUserID = null;
                return;
            }
            // user has been confirmed to be signed in
            mCurrentUserID = mFirebaseUser.getUid();
            currentUSerID = mCurrentUserID;
            // do something, refresh UI, etc
        }
    };
    private VelocityTracker mVelocityTracker = null;
    public static final DatabaseReference databaseReference = FirebaseDatabase.getInstance("https://pragya-datacollector.firebaseio.com").getReference();


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

        button = findViewById(R.id.my_button);
        button.setClickable(true);
        button.setOnClickListener(this);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent i = new Intent(ButtonPress.this, IntermediateActivity.class);
                i.putExtra("type", "failure");
                if (!ButtonPress.this.isFinishing())
                { ButtonPress.this.startActivity(i);
                ButtonPress.this.finish();
                }
            }
        }, 10000);

        // Wait until the first layout to get button size and placement to compute x/y placement range.
        button.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                button.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                // Capture width and x/y placement ranges here
                final Button button = (Button) findViewById(R.id.my_button);
                displaymetrics = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
                loOPenArea = (RelativeLayout) findViewById(R.id.open_area_press);

                // Button will have a horizontal margin from zero to the width of its parent less
                // the width of the button less the initial left side of the button which is likely
                // to be the initial margin.
                int buttonMaxXMargin = loOPenArea.getWidth() - button.getWidth() - button.getLeft();
                // Similar for the vertical placement.
                int buttonMaxYMargin = loOPenArea.getHeight() - button.getHeight() - button.getTop();

                int leftMargin = new Random().nextInt(buttonMaxXMargin);
                int topMargin = new Random().nextInt(buttonMaxYMargin);

                ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) button.getLayoutParams();
                p.setMargins(leftMargin, topMargin, 0, 0);

                button.setLayoutParams(p);
            }
        });


    }

    @Override
    public void onClick(View v) {
        Vibrator x = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            x.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));
        } else {
            x.vibrate(500);
        }
        Intent i = null;
        switch (v.getId()) {

            case R.id.my_button:
                i = new Intent(ButtonPress.this, IntermediateActivity.class);
                i.putExtra("type", "null");
                if (!ButtonPress.this.isFinishing())
                { ButtonPress.this.startActivity(i);
                    ButtonPress.this.finish();
                }
                break;
        }
    }
    public boolean dispatchTouchEvent(MotionEvent event) {

        TouchData touchData = null;

        int index = event.getActionIndex();
        int pointerId = event.getPointerId(index);
        List<Float> xTraj = new ArrayList<Float>();
        List<Float> yTraj = new ArrayList<Float>();


        final int X = (int) event.getRawX();
        final int Y = (int) event.getRawY();
        xTraj.add(event.getX());
        yTraj.add(event.getY());
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_DOWN:

                xTraj.add(event.getX());
                yTraj.add(event.getY());
                if(mVelocityTracker == null) {
                    // Retrieve a new VelocityTracker object to watch the velocity of a motion.
                    mVelocityTracker = VelocityTracker.obtain();
                }
                else {
                    // Reset the velocity tracker back to its initial state.
                    mVelocityTracker.clear();
                }
                // Add a user's movement to the tracker.
                mVelocityTracker.addMovement(event);
                break;

            case MotionEvent.ACTION_UP:
                mVelocityTracker.recycle();

                float centreX = button.getX() + button.getWidth()  / 2;
                float centreY = button.getY() + button.getHeight() / 2;

                long eventDuration = event.getEventTime() - event.getDownTime();

                touchData.setUniqueID(currentUSerID);
                touchData.setTaskName(TASK_NAME);
                touchData.setTouchDuration(eventDuration);
                touchData.setxTrajectory(xTraj);
                touchData.setyTrajectory(yTraj);
                touchData.setxVelocity(VelocityTrackerCompat.getXVelocity(mVelocityTracker, pointerId));
                touchData.setyVelocity(VelocityTrackerCompat.getYVelocity(mVelocityTracker, pointerId));
                touchData.setTargetX(centreX);
                touchData.setTargetY(centreY);
                databaseReference.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot snapshot) {
                        databaseReference.setValue(touchData);
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError error) {

                    }
                });
                break;
            case MotionEvent.ACTION_MOVE:
                xTraj.add(event.getX());
                yTraj.add(event.getY());
                mVelocityTracker.addMovement(event);
                mVelocityTracker.computeCurrentVelocity(1);

                break;

            case MotionEvent.ACTION_CANCEL:
                mVelocityTracker.recycle();
                break;
        }
        return super.dispatchTouchEvent(event);
    }

    @Override
    public void onBackPressed() {
        finish();
        IntermediateActivity.visitCount = 0;
        Intent k = new Intent(ButtonPress.this, MainActivity.class);
        k.putExtra("type", "null");
        startActivity(k);
    }

    @Override
    protected void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
        if (mFirebaseUser == null) {
            mAuth.signInAnonymously()
                    .addOnFailureListener(new OnFailureListener() {
                        @NonNull
                        @Override
                        public void onFailure(Exception ex) {
                            // TODO: Handle exceptions!
                            Log.e("TAG", "Failed to sign in anonymously: " +  ex.getMessage());
                        }
                    });
        }


    }

    @Override
    protected void onStop() {
        super.onStop();
        mAuth.removeAuthStateListener(mAuthListener);
    }
}

Solution

  • I think you should initialize once the task.isSuccessful().

    firebaseAuth = FirebaseAuth.getInstance();
    
    if(firebaseAuth.getCurrentUser() == null){
       firebaseAuth.signInAnonymously().addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
           @Override
           public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()) {
                      // Sign in success, update UI with the signed-in user's information
                      final FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
                      currentUserID = firebaseUser.getUid();
                }
           }
       });
    }
    

    UPDATE:

    You cannot initialize them outside the method.

    public class ButtonPress extends AppCompatActivity implements View.OnClickListener {
        private Button button;
        private DisplayMetrics displaymetrics;
        private RelativeLayout loOPenArea;
        private Handler mHandler = new Handler();
        private String currentUSerID;
        String TASK_NAME = "ButtonPress";
    
       FirebaseAuth mAuth; //Just variable, dont do anything
       FirebaseUser mFirebaseUser;//Just variable, dont do anything
       String mCurrentUserID;//Just variable, dont do anything