How to structure writing user details into Firebase real-time database?

Ezan :

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 input the data 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) 
Gabriel 14 :

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!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=334214&siteId=1