在Firebase实时数据库和经过身份验证的用户之间创建链接

时间:2018-03-13 17:25:39

标签: java android firebase firebase-realtime-database

到目前为止,我已在我的Android应用程序中成功实施了Firebase,我可以通过MaintenanceActivity将用户添加到身份验证门户,并通过MainActivity向实时数据库添加维护问题

但是,目前,没有任何数据库数据链接到特定用户,这是我想要实现的目标。因此,当我以任意用户身份登录时,总会出现相同的数据。

据推测,并且已经阅读了其他几个线程,此处将需要用户UID,并且每个维护记录都需要存在。

但是,我不确定如何实现这一点。可能需要在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); } } });

中实现一层身份验证需求

发现很难理解这一点,所以对此的任何帮助都将非常感激。

SignUpActivity

import csv

def get_stock_count():
    ITEM_COUNT = 0
    with open('stock.csv', 'r') as STOCK_READ:
        reader = csv.reader(STOCK_READ)
        for line in reader:
            ITEM_COUNT = ITEM_COUNT + 1
            print("{0} - {1} - {2} in stock".format(ITEM_COUNT,line[0],line[1]))
    return ITEM_COUNT

2 个答案:

答案 0 :(得分:1)

您可以像这样实现:

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

                                        }
                                    });

你可以像上面那样实现它,然后在你的数据库中你将拥有:

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

使用createUserWithEmailAndPassword(email, password)对用户进行身份验证后,您可以检索电子邮件和名称,以及编写的任何额外数据并将其发送到数据库。

mCurrentUser.getUid()将为您提供可在数据库中使用的用户标识。

答案 1 :(得分:0)

将项目添加到firebase后 你也可以试试这个。

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

    }

以下是用户类

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

这将在您的firebase数据库中显示电子邮件和密码字段。