1

So far I have successfully implemented Firebase within my Android application, where I can add users to the Authentication portal through a SignUpActivity, and also add maintenance issues to the real-time database through a MaintenanceActivity.

However, at present, none of the database data is linked to specific users, which is what I want to achieve. So essentially at the moment when I log in as an arbitrary user, the same data will always come up.

Presumably, and having read several other threads on this, the User UID will be required here and will need to be present for every maintenance record.

I'm not sure, however, how I can implement this. Possibly a layer of authentication needs implemented into the MainActivity?

Finding it hard to get my head around this, so any help on this would be much appreciated.

SignUpActivity

mDatabase = FirebaseDatabase.getInstance().getReference().child("users");
    final DatabaseReference[] ref = new DatabaseReference[1];
    final FirebaseUser[] mCurrentUser = new FirebaseUser[1];
    mAuth.createUserWithEmailAndPassword(email, password)
            .addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    Toasty.info(getApplicationContext(), "creation of account was: " + task.isSuccessful(), Toast.LENGTH_SHORT).show();
                    if (task.isSuccessful()) {
                        mCurrentUser[0] = task.getResult().getUser();
                        ref[0] =mDatabase.child(mCurrentUser[0].getUid());
                        ref[0].child("email").setValue(email);

                        Intent intent = new Intent(SignUpActivity.this, MainActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                    }
                }
            });
Face Value
  • 49
  • 1
  • 9
  • I have exaplained in one of my **[tutorials](https://www.youtube.com/playlist?list=PLn2n4GESV0AmXOWOam729bC47v0d0Ohee)** step by step, the entire authentication process using **[Google](https://www.youtube.com/watch?v=bwgMWBhObDw&list=PLn2n4GESV0AmXOWOam729bC47v0d0Ohee&index=5)** and **[Firebase](https://www.youtube.com/watch?v=UIRt9Ts0fRU&list=PLn2n4GESV0AmXOWOam729bC47v0d0Ohee&index=6)**. If you are interested you can take a look. You can also take a look at an [answer](https://stackoverflow.com/questions/49253026/firebase-auth-and-database/49256810) given today. – Alex Mamo Mar 13 '18 at 17:30

2 Answers2

1

You can implement it like this:

 mDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
 DatabaseReference ref;
 FirebaseUser mCurrentUser;
 auth.createUserWithEmailAndPassword(email, password)
                    .addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            Toasty.info(getApplicationContext(), "creation of account was: " + task.isSuccessful(), Toast.LENGTH_SHORT).show();
                            if (task.isSuccessful()) {
                                mCurrentUser= task.getResult().getUser();
                                ref=mDatabase.child(mCurrentUser.getUid());
                                ref.child("email").setValue(email);
                                ref.child("name").setValue(name);

                                        }
                                    });

You can implement it like the above, then in your db you will have:

Users
  userid
    name: userx
    email: userx@gmail.com

After you authenticate the user using createUserWithEmailAndPassword(email, password), you can then retrieve the email and name, and whatever extra data was written and send it to the database.

This mCurrentUser.getUid() will give you the userid, that you can use in the database.

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
  • @FaceValue did the answer help you? – Peter Haddad Mar 13 '18 at 19:44
  • Sorry I am only getting back to you now. Thanks for this. Where is this code to be implemented? In `LoginActivity` or `SignUpAcitivity`? – Face Value Mar 14 '18 at 10:30
  • createUserWithEmailAndPassword is done in signupactivity, after it is sucessful you then will be able to send to database – Peter Haddad Mar 14 '18 at 10:33
  • I have edited the question having implemented your answer. Still getting quite a few errors here. I have removed `ref.child("name").setValue(name);` as it does not apply for my login process. – Face Value Mar 14 '18 at 10:40
  • yes you need to send data to the database, depending what you want to do. Anw what are the errors? – Peter Haddad Mar 14 '18 at 10:41
  • Edited to show errors. Struggling to understand them. – Face Value Mar 14 '18 at 10:50
  • did you add the library related to toasty in the dependencies ? You are having problem with the @override also because you cannot declare it there – Peter Haddad Mar 14 '18 at 11:22
  • Yes, I have this working now. How, though, do I link these users to other database data? When I am logging in with a random user, all maintenance data is still appearing, as opposed to data maintenance data just for that user. – Face Value Mar 14 '18 at 12:41
  • Done. It solved a part of the problem, yes, but my users are still not linked to the database. – Face Value Mar 14 '18 at 12:52
  • Can you help with this issue? @PeterHaddad – Face Value Mar 14 '18 at 13:50
0

After adding your project to the firebase U can also try this.

     public class RegisterActivity extends AppCompatActivity implements 
     View.OnClickListener {

     private static final String TAG = "MAGIC";
     Firebase mref =null;

     private User user;
     private EditText email;
     private EditText password;
     private FirebaseAuth mAuth;
     private ProgressDialog mProgressDialog;

     @Override
     protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_register);
     Firebase.setAndroidContext(this);
     mAuth = FirebaseAuth.getInstance();
     }

     @Override
     protected void onStart() {
     super.onStart();

     email = (EditText) findViewById(R.id.edit_text_new_email);
     password = (EditText) findViewById(R.id.edit_text_new_password);

     }

     @Override
     public void onStop() {
     super.onStop();
     }

    //This method sets up a new User by fetching the user entered details.
     protected void setUpUser() {
     user = new User();

     user.setEmail(email.getText().toString().trim());
     user.setPassword(password.getText().toString().trim());
     }

    @Override
    public void onClick(View v) {

    //paste your firebase database link address here.
    mref = new Firebase("https://citypride-97902.firebaseio.com/");
    createNewAccount(email.getText().toString(), 
    password.getText().toString());
    }


     private void createNewAccount(String email, String password) {
     Log.d(TAG, "createNewAccount:" + email);
     if (!validateForm()) {
        return;
      }

     showProgressDialog();
     mAuth.createUserWithEmailAndPassword(email, password)
    .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {


                 Log.d(TAG, "Register Successfully " + task.isSuccessful());
                    hideProgressDialog();

        if (!task.isSuccessful()) {
        Toast.makeText(RegisterActivity.this, "Registration failed.", 
        Toast.LENGTH_SHORT).show();
                        hideProgressDialog();

                    } else {
             onAuthenticationSuccess(task.getResult().getUser());
             Toast.makeText(RegisterActivity.this, "Register Successful.", 
             Toast.LENGTH_SHORT).show();
                    } hideProgressDialog();
                }
            });

     } 

     private void onAuthenticationSuccess(FirebaseUser mUser) {
    // Write new user
    saveNewUser(mUser.getUid(), user.getEmail(), user.getPassword());
    signOut();
    // Go to LoginActivity
    Intent i =new Intent(LoginActivity.this, YourActivity.class);
    startActivity(i);
    }


       private void saveNewUser(String userId, 
       String email, String password) {

     User user = new User(userId,email,password);

     mref.child("Users").child(name).setValue(user);
     }

     private void signOut() {
     mAuth.signOut();
     }
     //This method, validates email address and password
     private boolean validateForm() {
     boolean valid = true;

     String userEmail = email.getText().toString();
     if (TextUtils.isEmpty(userEmail)) {
        email.setError("Required.");
        valid = false;
     } else {
        email.setError(null);
      }

     String userPassword = password.getText().toString();
     if (TextUtils.isEmpty(userPassword)) {
        password.setError("Required.");
        valid = false;
     } else {
        password.setError(null);
     }

      if(!Patterns.EMAIL_ADDRESS.matcher(userEmail).matches()){
         Toast.makeText(getApplicationContext(),"please enter valid 
      email",Toast.LENGTH_LONG).show();
     }

      if (userEmail.isEmpty() && userPassword.isEmpty()){
        Toast.makeText(getApplicationContext(),"all fields are 
        mandatory",Toast.LENGTH_LONG).show();
       }

      return valid;
      }


     public void showProgressDialog() {
     if (mProgressDialog == null) {
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setMessage("Loading");
        mProgressDialog.setIndeterminate(true);
     }
     mProgressDialog.show();
      }

     public void hideProgressDialog() {
       if (mProgressDialog != null && mProgressDialog.isShowing()) {
          mProgressDialog.dismiss();
    }
     } 

    }

Below is User class

   class User {
   private String id;
   private String email;
   private String password;

   public User() {
   }

    public User(String id,String email, String password) {
    this.id = id;
    this.email = email;
    this.password = password;
   }

    public String getId() {
    return id;
   }

   public void setId(String id) {
    this.id = id;
   }

    public void setName(String name) {

    public String getEmail() {
    return email;
   }

    public void setEmail(String email) {
    this.email = email;
    }

    public String getPassword() {
    return password;
    }

    public void setPassword(String password) {
    this.password = password;
    }
    } 

this will show email and password field in your firebase database.

Speedy
  • 11
  • 6