How to add data in firebase database

你离开我真会死。 提交于 2019-12-24 14:18:01

问题


I am creating car park app and i want users to enter some information in edit texts before registering. The edit texts are as follows:

First Name, Last Name, Email, password, car no.

When user hits register button, i want to store these values in firebase database connected to my project.I want to know how to create tables in firebase and how these values will be stored. I am new to programming.


回答1:


First retrieve the edittexts:

  String email = textEmail.getText().toString().trim();
  String firstname = firstName.getText().toString().trim();
  //etc

first authenticate the user using createUserWithEmailAndPassword and then add to the database:

 private DatabaseReference mDatabase, newUser;
 private FirebaseUser mCurrentUser;
 mDatabase = FirebaseDatabase.getInstance().getReference().child("users");
 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()) {
                                Toasty.error(getApplicationContext(), "Authentication failed: " + task.getException().getMessage(),
                                        Toast.LENGTH_SHORT).show();
                            } else {
                                 mCurrentUser= task.getResult().getUser();<-- gets you the uid
                                newUser=mDatabase.child(mCurrentUser.getUid());


                                            newUser.child("email").setValue(email);
                                            newUser.child("firstname").setValue(name);



                                        }
                                    });

you will have the following database:

users
  userid
    email:userx@gmail.com <--example
    firstname:userx <--example



回答2:


Firebase doesn't store data in tables, it is not a classic database. It's just a big JSON file that might be replicated in several nodes and might span several of them too.

The classic approach is to have the first level children of the root be what you imagine would be the tables. So, for example, you will have

{
"users": {
    ...
    }
 }

Second, what you are trying to do is very simple and you can know how to do it by opening the starting guide.

Moreover, the best approach to handle users' authentication is not this but using FirebaseAuth. In the guide you'll find about this too.



来源:https://stackoverflow.com/questions/49391801/how-to-add-data-in-firebase-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!