如何从代码编写实时数据库?

时间:2019-05-04 18:52:32

标签: java android firebase firebase-realtime-database

我正在创建一个项目,我的目标是编写Firebase数据库。我制作了一个注册方法来注册用户,当他们注册后,他们创建了一个名为 Usuario(User)的对象,其值分别为“ nombre” “ correo” 。我正在遵循一个教程,但是我遵循了所有步骤进行操作,并让他们使用电子邮件和密码成功注册,但是他们没有使用输入名称的值来创建对象。

这是我的RegisterActivity代码以及所有方法:


import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.logincorreopass.Entidades.Usuario;
import com.example.logincorreopass.R;
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.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class RegisterActivity extends AppCompatActivity {

    private EditText name, email, password, repPassword;
    private Button registrar;
    private FirebaseAuth mAuth;
    private FirebaseDatabase database;
    private DatabaseReference referenceUsers;

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



        name = findViewById(R.id.etNombre);
        email = findViewById(R.id.etCorreo);
        password = findViewById(R.id.etContraseña);
        repPassword = findViewById(R.id.etRepContraseña);



        registrar = findViewById(R.id.btnRegister);


        mAuth = FirebaseAuth.getInstance();
        database = FirebaseDatabase.getInstance();


        //Create the object Usuario in the path "Usuarios" in my Database.

        referenceUsers = database.getReference("Usuarios");


        //Register button with all the methods to regist them in the Database and create the Object Usuario (User in english)
        registrar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String correo = email.getText().toString();
                final String nombre = name.getText().toString();
                if (isValidEmail(correo) && validarContraseña() && validarNombre(nombre)) {
                    String contraseña = password.getText().toString();

                    mAuth.createUserWithEmailAndPassword(correo, contraseña)
                            .addOnCompleteListener(RegisterActivity.this, new OnCompleteListener<AuthResult>() {
                                @Override
                                public void onComplete(@NonNull Task<AuthResult> task) {
                                    if (task.isSuccessful()) {
                                        Toast.makeText(RegisterActivity.this, "Se ha registrado correctamente.", Toast.LENGTH_SHORT).show();
                                        Usuario usuario = new Usuario();
                                        usuario.setCorreo(correo);
                                        usuario.setNombre(nombre);
                                        referenceUsers.push().setValue(usuario);
                                    } else {
                                        Toast.makeText(RegisterActivity.this, "Error al registrarse.", Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });
                }else{
                    Toast.makeText(RegisterActivity.this, "Validaciones funcionando.", Toast.LENGTH_SHORT).show();
                }
            }
        });




    }
    //check email
    public final static boolean isValidEmail(CharSequence target){
        return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
    }

    //Check password
    public boolean validarContraseña(){
        String contraseña, contraseñarepetida;

        contraseña = password.getText().toString();
        contraseñarepetida = repPassword.getText().toString();
        if(contraseña.equals(contraseñarepetida)){
            if(contraseña.length()>=6 && contraseña.length()<=16){
                return true;
                }else return false;
            }else return false;
    }

        //Check name
            public boolean validarNombre(String nombre){
        return !nombre.isEmpty();
            }
        }


我在本教程中检查了所有代码,它在本教程中有效,但在我的项目中无效。我不知道这有什么问题。 如果有用的话,这也是我的gradle依赖项:

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.logincorreopass"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.google.firebase:firebase-auth:16.2.1'
    implementation 'com.google.firebase:firebase-database:16.1.0'
}

谢谢。

0 个答案:

没有答案