简体   繁体   中英

How to store user data into Firbase database after authentication?

So i'm new to android studio and firebase and i'm doing an android application where i am required to create user roles to see different features in the app (client & trainer). I know that this isn't available through firebase authentication so i was advised to insert the user details into the database and assign/access roles from there. I'm trying to make the database look something like this...

How i'm trying to structure the real-time database (manually added to database)

//Where 'User1Email' can be either email of user or user id (as i think you cannot include @ into database)

However my code seems to be crashing the application. The way i've tried to update the data to the database in my .java file looks like this..

//ESTABLISH THE CONNECTIONS TO DATABASE AND GET TE USER ID
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        String uid = user.getUid();
        FirebaseDatabase database = FirebaseDatabase.getInstance();
        final DatabaseReference mRef = database.getReference("users");


        EditText emailField = findViewById(R.id.email);
        EditText passwordField = findViewById(R.id.password);

        //Get email and password from text views
        final String email = emailField.getText().toString();
        final String password = passwordField.getText().toString();

         mRef.child("password").setValue(password);
         mRef.child("role").setValue("Trainer");

// I DID ALSO TRY THIS BUT UID STAYS UNDERLINED RED-  mRef.child(uid).child("password").setValue(password);

ERROR:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.finalyearapp, PID: 13903
    java.lang.IllegalStateException: Could not execute method for android:onClick
        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:402)
        at android.view.View.performClick(View.java:6597)
        at android.view.View.performClickInternal(View.java:6574)
        at android.view.View.access$3100(View.java:778)
        at android.view.View$PerformClick.run(View.java:25885)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        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)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:397)
        at android.view.View.performClick(View.java:6597) 
        at android.view.View.performClickInternal(View.java:6574) 
        at android.view.View.access$3100(View.java:778) 
        at android.view.View$PerformClick.run(View.java:25885) 
        at android.os.Handler.handleCallback(Handler.java:873) 
        at android.os.Handler.dispatchMessage(Handler.java:99) 
        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) 
     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.finalyearapp.SignUpActivity.onClick(SignUpActivity.java:53)
        at java.lang.reflect.Method.invoke(Native Method) 
        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:397) 
        at android.view.View.performClick(View.java:6597) 
        at android.view.View.performClickInternal(View.java:6574) 
        at android.view.View.access$3100(View.java:778) 
        at android.view.View$PerformClick.run(View.java:25885) 
        at android.os.Handler.handleCallback(Handler.java:873) 
        at android.os.Handler.dispatchMessage(Handler.java:99) 
        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) 

You must authenticate an user before getting his instance.

To make sure that user is logged before doing anything, call getCurrentUser() method in createUserWithEmailAndPassword() (if you are using email and password authentication).

First of all create and initialize a Firebase Auth object :

FirebaseAuth mAuth = FirebaseAuth.getInstance();

Then when you want to sign up (supposed with a button) call createUserWithEmailAndPassword() method :

mAuth.createUserWithEmailAndPassword(email, password)
    .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if (task.isSuccessful()) {
                //Successfully created user
                FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
                String uid = user.getUid();
                FirebaseDatabase database = FirebaseDatabase.getInstance();
                final DatabaseReference mRef = database.getReference("users");


                EditText emailField = findViewById(R.id.email);

                //Get email from EditText
                final String email = emailField.getText().toString();

                mRef.child("role").setValue("Trainer");
            } else {
                //User not created,

                //Print exception
                Log.e("Sign up", task.getException().getMessage())

                //Write your code to handle user creation fail
            }
        }
    });

If you want to learn more of Firebase Authentication, look here

Remember that this solution is only for users creation.

Hope it helps! Write a comment to more explanation or if you have another question!

In your database you have Users node with a capital U , therefore you should change the following:

 final DatabaseReference mRef = database.getReference("users");

into this:

final DatabaseReference mRef = database.getReference("Users");

Also you need to add a child() to include the userId :

final DatabaseReference mRef = database.getReference("Users").child(uid);
mRef.child("password").setValue(password);
mRef.child("role").setValue("Trainer");

Then you will have:

Users
  userId
     password : password
     role     : Trainer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM