使用Firebase当前的用户UID而不是随机UID来保存我的文档文件。

huangapple go评论68阅读模式
英文:

Save my document files with the firebase current uid instead of a random one

问题

以下是您的代码翻译:

package com.LiFit;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;

import java.util.HashMap;

public class RegisterActivity extends AppCompatActivity {

    private EditText UserName, FullName, eMail1, eMail2, Password, Day, Month, Year;
    private Button registerButton;
    private CheckBox male, female, other;
    private FirebaseAuth mAuth;
    private ProgressDialog loadingBar;
    public String currentUserId, username;

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

        mAuth = FirebaseAuth.getInstance();
        loadingBar = new ProgressDialog(this);
        UserName = (EditText) findViewById(R.id.register_username);
        FullName = (EditText) findViewById(R.id.register_name);
        eMail1 = (EditText) findViewById(R.id.register_email);
        eMail2 = (EditText) findViewById(R.id.register_email_2);
        Password = (EditText) findViewById(R.id.register_password);
        Day = (EditText) findViewById(R.id.register_birthday_day);
        Month = (EditText) findViewById(R.id.register_birthday_month);
        Year = (EditText) findViewById(R.id.register_birthday_year);
        registerButton = (Button) findViewById(R.id.register_button);
        male = (CheckBox) findViewById(R.id.register_male);
        other = (CheckBox) findViewById(R.id.register_other);
        female = (CheckBox) findViewById(R.id.register_female);
        registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CreateNewAccount();
            }
        });
    }

    private void CreateNewAccount() {
        username = UserName.getText().toString();
        String fullname = FullName.getText().toString();
        String email1 = eMail1.getText().toString();
        String email2 = eMail2.getText().toString();
        String password = Password.getText().toString();
        String day = Day.getText().toString();
        String month = Month.getText().toString();
        String year = Year.getText().toString();

        if(TextUtils.isEmpty(username)){
            Toast.makeText(this,"请输入用户名...", Toast.LENGTH_SHORT).show();
        }
        else if(TextUtils.isEmpty(fullname)){
            Toast.makeText(this,"请输入您的全名...", Toast.LENGTH_SHORT).show();
        }
        else if(TextUtils.isEmpty(email1)){
            Toast.makeText(this,"请输入您的电子邮件...", Toast.LENGTH_SHORT).show();
        }
        else if(TextUtils.isEmpty(email2)){
            Toast.makeText(this,"请重新输入您的电子邮件...", Toast.LENGTH_SHORT).show();
        }
        else if(!email1.equals(email2)){
            Toast.makeText(this,"您输入了两个不同的电子邮件... 请重试", Toast.LENGTH_SHORT).show();
        }
        else if(TextUtils.isEmpty(password)){
            Toast.makeText(this,"请输入密码...", Toast.LENGTH_SHORT).show();
        }
        else if(TextUtils.isEmpty(day)){
            Toast.makeText(this,"请输入您的生日日...", Toast.LENGTH_SHORT).show();
        }
        else if(TextUtils.isEmpty(month)){
            Toast.makeText(this,"请输入您的生日月...", Toast.LENGTH_SHORT).show();
        }
        else if(TextUtils.isEmpty(year)){
            Toast.makeText(this,"请输入您的生日年...", Toast.LENGTH_SHORT).show();
        }
        else if(!male.isChecked() && !female.isChecked() && !other.isChecked()){
            Toast.makeText(this,"选择您的性别...", Toast.LENGTH_SHORT).show();
        }
        else if(male.isChecked() && female.isChecked()){
            Toast.makeText(this,"请选择一个性别...", Toast.LENGTH_SHORT).show();
        }
        else if(male.isChecked() && other.isChecked()){
            Toast.makeText(this,"请选择一个性别...", Toast.LENGTH_SHORT).show();
        }
        else if(female.isChecked() && other.isChecked()){
            Toast.makeText(this,"请选择一个性别...", Toast.LENGTH_SHORT).show();
        }
        else{
            loadingBar.setTitle("创建新帐户");
            loadingBar.setMessage("请稍候,正在创建您的新帐户...");
            loadingBar.show();
            loadingBar.setCanceledOnTouchOutside(true);
            mAuth.createUserWithEmailAndPassword(email1, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if(task.isSuccessful()){
                        FirebaseUser user = mAuth.getCurrentUser();
                        SaveAccountInformation();
                        Toast.makeText(RegisterActivity.this,"您的帐户已创建,请检查电子邮件以获取激活邮件", Toast.LENGTH_LONG).show();
                        loadingBar.dismiss();
                        SendUserToMainActivity();
                    }
                    else{
                        String message= task.getException().getMessage();
                        Toast.makeText(RegisterActivity.this, "出现错误: " + message, Toast.LENGTH_LONG).show();
                        loadingBar.dismiss();
                    }
                }
            });
        }
    }

    private void SaveAccountInformation() {
        currentUserId = mAuth.getCurrentUser().getUid();
        FirebaseFirestore db = FirebaseFirestore.getInstance();
        String gender;
        username = UserName.getText().toString();
        String fullname = FullName.getText().toString();
        String day = Day.getText().toString();
        String month = Month.getText().toString();
        String year = Year.getText().toString();

        if(male.isChecked()) {
            gender = "男性";
        } else if(female.isChecked()){
            gender = "女性";
        } else {
            gender = "其他";
        }

        HashMap userMap = new HashMap();
        userMap.put("用户名", username);
        userMap.put("性别", gender);
        userMap.put("全名", fullname);
        userMap.put("生日", day+"/"+month+"/"+year);
        userMap.put("uid", mAuth.getCurrentUser().getUid());
        userMap.put("已验证", "false");
        db.collection("用户")
                .add(userMap)
                .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                    @Override
                    public void onSuccess(DocumentReference documentReference) {

                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {

                    }
                });
    }

    private void SendUserToMainActivity() {
        Intent mainIntent = new Intent(RegisterActivity.this, MainActivity.class);
        mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(mainIntent);
    }
}

请注意,我已经将代码中的注释和字符串内容进行了翻译,并将函数和变量名保留在英文状态下。如果您有任何问题,请随时问我。

英文:

So look when my user registers himself his ID in the firebase database is randomly generated and I want to have the UID of the newly registered user as the document´s id in firebase how can I change that ? I haven´t found any function to make the document save as a String or something like that..

Here is my register code:


import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.HashMap;
public class RegisterActivity extends AppCompatActivity {
private EditText UserName, FullName, eMail1, eMail2, Password, Day, Month, Year;
private Button registerButton;
private CheckBox male, female, other;
private FirebaseAuth mAuth;
private ProgressDialog loadingBar;
public String currentUserId, username;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
mAuth = FirebaseAuth.getInstance();
loadingBar = new ProgressDialog(this);
UserName = (EditText) findViewById(R.id.register_username);
FullName = (EditText) findViewById(R.id.register_name);
eMail1 = (EditText) findViewById(R.id.register_email);
eMail2 = (EditText) findViewById(R.id.register_email_2);
Password = (EditText) findViewById(R.id.register_password);
Day = (EditText) findViewById(R.id.register_birthday_day);
Month = (EditText) findViewById(R.id.register_birthday_month);
Year = (EditText) findViewById(R.id.register_birthday_year);
registerButton = (Button) findViewById(R.id.register_button);
male = (CheckBox) findViewById(R.id.register_male);
other = (CheckBox) findViewById(R.id.register_other);
female = (CheckBox) findViewById(R.id.register_female);
registerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CreateNewAccount();
}
});
}
private void CreateNewAccount() {
username = UserName.getText().toString();
String fullname = FullName.getText().toString();
String email1 = eMail1.getText().toString();
String email2 = eMail2.getText().toString();
String password = Password.getText().toString();
String day = Day.getText().toString();
String month = Month.getText().toString();
String year = Year.getText().toString();
if(TextUtils.isEmpty(username)){
Toast.makeText(this,&quot;Please type in your username...&quot;, Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(fullname)){
Toast.makeText(this,&quot;Please type in your full name...&quot;, Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(email1)){
Toast.makeText(this,&quot;Please type in your eMail...&quot;, Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(email2)){
Toast.makeText(this,&quot;Please retype your eMail again...&quot;, Toast.LENGTH_SHORT).show();
}
else if(!email1.equals(email2)){
Toast.makeText(this,&quot;You entered two different emails...? Please try again&quot;, Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(password)){
Toast.makeText(this,&quot;Please type in your password...&quot;, Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(day)){
Toast.makeText(this,&quot;Please enter your birthday day...&quot;, Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(month)){
Toast.makeText(this,&quot;Please enter your birthday month...&quot;, Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(year)){
Toast.makeText(this,&quot;Please enter your birthday year...&quot;, Toast.LENGTH_SHORT).show();
}
else if(!male.isChecked() &amp;&amp; !female.isChecked() &amp;&amp; !other.isChecked()){
Toast.makeText(this,&quot;Chose your gender...&quot;, Toast.LENGTH_SHORT).show();
}
else if(male.isChecked() &amp;&amp; female.isChecked()){
Toast.makeText(this,&quot;Please choose only one gender...&quot;, Toast.LENGTH_SHORT).show();
}
else if(male.isChecked() &amp;&amp; other.isChecked()){
Toast.makeText(this,&quot;Please choose only one gender...&quot;, Toast.LENGTH_SHORT).show();
}
else if(female.isChecked() &amp;&amp; other.isChecked()){
Toast.makeText(this,&quot;Please choose only one gender...&quot;, Toast.LENGTH_SHORT).show();
}
else{
loadingBar.setTitle(&quot;Creating New Account&quot;);
loadingBar.setMessage(&quot;Please wait, while we are creating your new Account...&quot;);
loadingBar.show();
loadingBar.setCanceledOnTouchOutside(true);
mAuth.createUserWithEmailAndPassword(email1, password).addOnCompleteListener(new OnCompleteListener&lt;AuthResult&gt;() {
@Override
public void onComplete(@NonNull Task&lt;AuthResult&gt; task) {
if(task.isSuccessful()){
FirebaseUser user = mAuth.getCurrentUser();
SaveAccountInformation();
Toast.makeText(RegisterActivity.this,&quot;Your account was created please check your email for an activation mail&quot;, Toast.LENGTH_LONG).show();
loadingBar.dismiss();
SendUserToMainActivity();
}
else{
String message= task.getException().getMessage();
Toast.makeText(RegisterActivity.this, &quot;Error Occured: &quot; + message, Toast.LENGTH_LONG).show();
loadingBar.dismiss();
}
}
});
}
}
private void SaveAccountInformation() {
currentUserId = mAuth.getCurrentUser().getUid();
FirebaseFirestore db = FirebaseFirestore.getInstance();
String gender;
username = UserName.getText().toString();
String fullname = FullName.getText().toString();
String day = Day.getText().toString();
String month = Month.getText().toString();
String year = Year.getText().toString();
if(male.isChecked()) {
gender = &quot;male&quot;;
} else if(female.isChecked()){
gender = &quot;female&quot;;
} else {
gender = &quot;other&quot;;
}
HashMap userMap = new HashMap();
userMap.put(&quot;username&quot;, username);
userMap.put(&quot;gender&quot;, gender);
userMap.put(&quot;fullname&quot;, fullname);
userMap.put(&quot;birthday&quot;, day+&quot;/&quot;+month+&quot;/&quot;+year);
userMap.put(&quot;uid&quot;, mAuth.getCurrentUser().getUid());
userMap.put(&quot;verified&quot;, &quot;false&quot;);
db.collection(&quot;users&quot;)
.add(userMap)
.addOnSuccessListener(new OnSuccessListener&lt;DocumentReference&gt;() {
@Override
public void onSuccess(DocumentReference documentReference) {
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
}
});
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(RegisterActivity.this, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
}
}

答案1

得分: 2

不要使用 add()

add() 会在集合中添加一个带有随机 ID 的新文档。

但是当您提供文档 ID 并使用 set 方法时,它会创建一个具有当前用户 UID 的文档,并将数据设置到该特定 ID。

请使用 set() 并提供文档 ID 给 Firestore:

db.collection("users").document(currentUserId)
    .set(userMap)
    .addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            //您想要执行的操作
        }
    })
    .addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {

        }
    });
英文:

Instead of using add().

add() will just add new document in the collection with random id.

But when you provide documentid and set method. It creates document with current user uid and set the data to that specific id.

Use set() and provide the document id to firestore

db.collection(&quot;users&quot;).document(currentUserId)
.set(userMap)
.addOnSuccessListener(new OnSuccessListener&lt;Void&gt;() {
@Override
public void onSuccess(Void aVoid) {
//Do what you want
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
}
});

huangapple
  • 本文由 发表于 2020年5月5日 19:25:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/61612010.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定