【问题标题】:Android App won't write to Firebase Realtime DatabaseAndroid 应用不会写入 Firebase 实时数据库
【发布时间】:2020-01-02 20:10:53
【问题描述】:

我正在使用 Firebase 和 Android Studio 来构建应用。我有一个注册屏幕,要求用户输入用户名和位置等信息。单击注册按钮时,用户的电子邮件和密码会起作用,并显示在 Firebase 控制台的身份验证选项卡中。但是,我无法将用户名和位置等用户详细信息存储在 Firebase 实时数据库中。

package com.example.securityapp;

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

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
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;

public class register extends AppCompatActivity {

    private FirebaseAuth mAuth;
    EditText emailReg, passwordReg, password2, roleReg, officeReg;
    Button regButton;
    DatabaseReference databaseUsers;
    EditText usernameReg;

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

        emailReg = (EditText) findViewById(R.id.regEmail);
        usernameReg = (EditText) findViewById(R.id.regUsername);
        passwordReg = (EditText) findViewById(R.id.regPassword);
        regButton = (Button) findViewById(R.id.register_Button);
        password2 = (EditText) findViewById(R.id.confirm_password);
        roleReg = (EditText) findViewById(R.id.regRole);
        officeReg = (EditText) findViewById(R.id.regOffice);
        databaseUsers = FirebaseDatabase.getInstance().getReference();
        mAuth = FirebaseAuth.getInstance();
    }

    public void registerUser() {
        final String email = emailReg.getText().toString();
        final String password = passwordReg.getText().toString();
        String pass2 = password2.getText().toString();
        if(!pass2.equals(password))
        {
            Toast.makeText(register.this, "Passwords Do Not Match",
                    Toast.LENGTH_SHORT).show();
                    return;
        }
        //Code taken from https://firebase.google.com/docs/auth/android/start on 10/11/2019
        mAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            // Sign in success, update UI with the signed-in user's information

                            Intent intent_signup = new Intent(register.this, home.class);
                            startActivity(intent_signup);
                            finish();
                            FirebaseUser user = mAuth.getCurrentUser();
                            Toast.makeText(register.this, "Authentication Successful!",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            // If sign in fails, display a message to the user.
                            Toast.makeText(register.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                        }

                        // ...
                    }
                });

    }


    public void registerOnClick(View view)
    {
        regButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {

                registerUser();
                insertDataDB();

            }
        });


    }

    public void insertDataDB()
    {
         String username = usernameReg.getText().toString();
         String office = officeReg.getText().toString();
         String job = roleReg.getText().toString();
         String email = emailReg.getText().toString();


        String id = databaseUsers.push().getKey();

        Users user1 = new Users(username, office, job, email);
        databaseUsers.child(id).setValue(user1);


    }

}

Users.java

package com.example.securityapp;

public class Users {

     String username;
     String job;
     String email;
     String office;

     public Users()
    {

    }

    public Users(String username, String job, String email, String office)
    {
        this.username = username;
        this.job = job;
        this.email = email;
        this.office = office;
    }

    public String getUsername()
    {
        return username;
    }

    public String getJob() { return job; }

    public String getEmail()
    {
        return email;
    }

    public String getOffice()
    {
        return office;
    }



}

【问题讨论】:

    标签: java android firebase firebase-realtime-database


    【解决方案1】:

    将安全规则更改为以下内容:

    {
      // Allow read/write access to all users under any conditions
      // Warning: **NEVER** use this ruleset in production; it allows
      // anyone to overwrite your entire database.
    
      "rules": {
        ".read": true
        ".write": true
      }
    }
    
    

    【讨论】:

    • 感谢您的回复,但我已经设置了这些,但仍然没有运气:(
    • 方法insertDataIntoDb应该在createuserwithEmailAndPassword里面
    • 我也尝试将 insertDataDB 方法移到这里,但仍然一无所获:(我真的很困惑发生了什么。一个朋友的代码与我的完全相同,她的代码似乎有效?
    【解决方案2】:

    这是我收到的通知,但我没有使用 Cloud Firestore,我正在尝试使用实时数据库

    【讨论】:

    • @Ticherhaz 这就是我所看到的
    【解决方案3】:

    使用mAuth 完成帐户创建后,您应该将数据位置等存储在 Firebase 中。

    //Code taken from https://firebase.google.com/docs/auth/android/start on 10/11/2019
    mAuth.createUserWithEmailAndPassword(email, password)
        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if (task.isSuccessful()) {
                // Sign in success, update UI with the signed-in user's information
    
            // Here we will get the user information, ex userUid (optional)
            FirebaseUser user = mAuth.getCurrentUser();
    
            //After that store the data before intent to next activity
            insertDataDB();
    
            //Then proceed to next activity
            Intent intent_signup = new Intent(register.this, home.class);
            startActivity(intent_signup);
            finish();
    
            Toast.makeText(register.this, "Authentication Successful!", Toast.LENGTH_SHORT).show();
        } else {
            // If sign in fails, display a message to the user.
            Toast.makeText(register.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
        }
    
        // ...
    }
    });
    

    更新: 存储方法。

     public void insertDataDB()
     {
            String username = usernameReg.getText().toString();
            String office = officeReg.getText().toString();
            String job = roleReg.getText().toString();
            String email = emailReg.getText().toString();
            String id = databaseUsers.push().getKey();
    
            Users user1 = new Users(username, office, job, email);
            databaseUsers.child(id).setValue(user1).addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (task.isSuccessful()){
                    //Success store data in database.
                    Toast.makeText(getApplicationContext(),"Success",Toast.LENGTH_LONG).show();
                }else {
                    //Something happened
                    Toast.makeText(getApplicationContext(),"Error: " + task.getException().getMessage(),Toast.LENGTH_LONG).show();
                }
            }
        });
    }
    

    【讨论】:

    • 感谢您的回复。当我移动 insertData();方法要在意图之前,我仍然遇到同样的问题。身份验证成功,但详细信息未存储在实时数据库中?
    • @ChloeHamilton 你检查实时数据库的安全规则了吗?
    • 是的,我的数据库规则设置为读真写真
    • @ChloeHamilton 我认为这是异常情况。 !task.isSuccessfull() 。更新你的 setValue(user1).addOnSuccessListener
    • 你是什么意思?我是否只需将 .addOnSuccessListener 添加到 insertData 方法的最后一行? - 谢谢:)
    猜你喜欢
    • 2021-08-23
    • 2018-01-12
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 2021-07-03
    相关资源
    最近更新 更多