Save Uid from A FireBase user

1

Good, I have an application where I send some data and when I send the data I want you to save me with the User's Uid that is now connected.

The method I have is this

private void saveInformation()
{
    //initializing firebase authentication object
    firebaseAuth = FirebaseAuth.getInstance();

    //getting current user
    FirebaseUser user = firebaseAuth.getCurrentUser();

    //Getting values from database
    String aviso = aviso1.getText().toString().trim();
    String descripcion = textDes.getText().toString().trim();
    String ubicacion = textubi.getText().toString().trim();
    //La linea que esta mal
    Usuario usuario = user.getUid();

    //Creamos un objeto para guardar la informacion
    Aviso avisoInformation = new Aviso(aviso,descripcion,ubicacion,usuario);

    databaseReference.child("Aviso").push().setValue(avisoInformation);

    //displaying a success toast
    Toast.makeText(this, "Guardando informacion del aviso, espera...", Toast.LENGTH_LONG).show();
}

I have a constructor with its 3 Strings and User User. But now to try to save the Uid (Is a String) how could I save it or what can I do?

If you need any more part of the code, please advise.

Thanks

// VerAvisos

public class VerAviso extends MenuAvisos
{

    List<Aviso> avisos;
    ListView list;


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

        FirebaseDatabase database = FirebaseDatabase.getInstance();
        FirebaseUser user = firebaseAuth.getInstance().getCurrentUser();

        final ArrayAdapter<Aviso> adapter;

        list = (ListView)findViewById(R.id.listview);

        adapter = new ArrayAdapter<Aviso>(this, android.R.layout.simple_list_item_1);

        list.setAdapter(adapter);


        database.getReference("Aviso").child(user.getUid()).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                avisos.clear();
                for(DataSnapshot snapshot :
                        dataSnapshot.getChildren()){

                    Aviso aviso2 = snapshot.getValue(Aviso.class);
                    avisos.add(aviso2);

                }
                adapter.notifyDataSetChanged();

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }
}
    
asked by Cristian Prieto Beltran 25.04.2017 в 10:33
source

2 answers

2

Very good, To get the UID of the current user, you put this line at the beginning

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

You are declaring the user that it will be the instance of the current user.

And then you use it for whatever you like. Do I give you examples? There you go.

    btnAgregarEvento.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    //Llenado del objeto evento con los respectivos EditText
                    evento.setNombre(etNombreEvento.getText().toString());
                    evento.setLugar(etLugarEvento.getText().toString());

                    //Mandar evento a Firebase
                    FirebaseDatabase database = FirebaseDatabase.getInstance();
//Digo la ubicacion de lo que voy a guardar , por ejemplo,en nodo hijo evento del nodo hijo UID del usuario dentro del nodo usuario 
                    final DatabaseReference myRef = database.getReference("utilisateur").child(user.getUid()).child("evenement");
//Ya dentro de la ubicacion guardo todo.
                    Evento evento2= new Evento(evento.getNombre(),evento.getLugar());
                    myRef.push().setValue(evento2);

                }
            });

In the end what you kept would be like this in the database

Usuarios
       -- UID(De cada cliente)
                              --Evento (El Evento creado que tiene cada cliente)
                                    --EventoKey
                                        -- (Valores dentro del evento, como nombre,lugar, etc ) 
                                    --EventoKey
                                        -- (Valores dentro del evento, como nombre,lugar, etc ) 
                                    --EventoKey
                                        -- (Valores dentro del evento, como nombre,lugar, etc ) 
                                    --EventoKey
                                        -- (Valores dentro del evento, como nombre,lugar, etc ) 

Etc

But now you will ask:

-Oh Eduardo, but then how do I show the respective data (events in the example) of each user?

And I'll answer you: -Do not fear, here is an example of how to obtain the data:

database.getReference("utilisateur").child(user.getUid()).child("evenement").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            eventos.clear();
            for(DataSnapshot snapshot :
                    dataSnapshot.getChildren()){

               Evento evento2 = snapshot.getValue(Evento.class);
                eventos.add(evento2);

            }
            adapter.notifyDataSetChanged();

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

As you can see, just add the user node to the query. I hope it will help you, even though 3 hours have already passed, it serves the future ones that have your same doubt.

Any other questions about Firebase do not hesitate to post it and it will be answered. Bon courage.

    
answered by 25.04.2017 / 14:47
source
0

Actually the .getUid() method gets a String with the user id,

  

getUid () : Returns a user identifier specified by the authentication provider.

therefore, instead of saving it to a User object, simply save it to a variable type String :

//Usuario usuario = user.getUid();
  String usuario = user.getUid();

but this is if your Aviso object receives the user as String :

 //Creamos un objeto para guardar la informacion
 Aviso avisoInformation = new Aviso(aviso,descripcion,ubicacion,usuario);

If your Aviso object receives a user object, you can choose to create the object and add the user property:

//Instancia objeto usuario.
 Usuario usuario = new Usuario();
//Agrega Uid al objeto usuario. 
usuario.setUsuario(user.getUid());
    
answered by 25.04.2017 в 18:03