Sarahtech
Sarahtech

Reputation: 61

How to add data in firebase database

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.

Upvotes: 1

Views: 6981

Answers (2)

Peter Haddad
Peter Haddad

Reputation: 80904

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:[email protected] <--example
    firstname:userx <--example

Upvotes: 1

balsick
balsick

Reputation: 1201

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.

Upvotes: 0

Related Questions