Edittext already completed after user login using firebase

Asked

Viewed 262 times

0

Hello!

I’m having second thoughts about a process I’m having trouble doing. I have the following screen, and I wanted the user Edittext is already filled with the user’s name or the user’s email. I’m new to mobile programming, and I tried to do this with sharedpreferences, but I couldn’t build the code.

Follow the screen of Activity and the firebase bank I’m using. Activity - campo usuário Follow my Activity code to here. public class Mensagemactivity extends Appcompatactivity {

EditText edtNome, edtMensagem;
Button btnEnviarMensagem;
Mensagem mensagem;

FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;

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

    edtNome = (EditText) findViewById(R.id.edtUsuario);
    edtMensagem = (EditText) findViewById(R.id.edtMensagem);
    btnEnviarMensagem = (Button) findViewById(R.id.btnEnviarMensagem);

    databaseReference = FirebaseDatabase.getInstance().getReference();

    btnEnviarMensagem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mensagem = new Mensagem();
            mensagem.setNome(edtNome.getText().toString());
            mensagem.setMensagem(edtMensagem.getText().toString());

            DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
            databaseReference.child("mensagens").push().setValue(firebaseDatabase, new DatabaseReference.CompletionListener() {
                @Override
                public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
                    //Problem with saving the data
                    if (databaseError != null) {
                        Toast.makeText(MensagemActivity.this, "Erro ao criar ocorrência / erro ao inserir dados!", Toast.LENGTH_LONG).show();
                    } else {
                        //Data uploaded successfully on the server
                        databaseReference.child("nome").setValue(edtNome.getText().toString());
                        databaseReference.child("texto").setValue(edtMensagem.getText().toString());
                        Toast.makeText(MensagemActivity.this, "Mensagem enviada com sucesso!", Toast.LENGTH_LONG).show();
                        retornaTela();
                }
            }
        });
    }
});

}

Banco com os dados de mensagem e usuario If anyone would be so kind as to help me, I’d appreciate it. Hugs.

1 answer

2

Good afternoon ! In this case you will need a Valueeventlistener to retrieve that user’s information on the system, you will need to create an instance pointing to for example databaseReference.getinstance(). Child("user"). Child("condominium").(in this case as you used the push method I do not know how to recover this value rsrs, but it would be the push"Ktdiz..."). Child("name"); So you’ll have a reference to that node and then you can access it from eentlistener... Following is an example of a code I made hj that in this case returns all user data registered in firebase:

/********************INICIO DA CAPTURA DE DADOS DO USUARIO ****************************/
    SharedPreferencesUser preferencesUser = new SharedPreferencesUser(getActivity());
    idUsuario = preferencesUser.getIdentificador();

    firebase = ConfiguracaoFirebase.getDataBase()
            .child("USUARIOS")
            .child(idUsuario);

    valueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot != null){
                Usuarios usuario = dataSnapshot.getValue(Usuarios.class);

                //SETANDO OS VALORES NA CLASSE MODEL
                nome.setText(usuario.getNome());
                email.setText(usuario.getEmail());
                nasc.setText(usuario.getNascimento());
                prof.setText(usuario.getProfissao());
                pais.setText(usuario.getPais());
                estado.setText(usuario.getEstado());
                cid.setText(usuario.getCidade());
                tel.setText(usuario.getTelefone());
                escolaridade.setText(usuario.getEscolaridade());

            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    };
    firebase.addValueEventListener(valueEventListener);
    /**********************FIM DA CAPTURA DE DADOS DO USUARIO *****************************/

This way I have saved in sharedpreferences the user ID, then passing it in the referenceFirebase that I called firebase I can access all nodes from there and arrow them in Textviews or Edittext, besides that I am using the model user class to mediate the data, the secret in this case is dataSnapshot, he is the one who brings the data of my reference. I advise you to research on valueEventListener. https://firebase.google.com/docs/database/android/read-and-write?hl=pt-br. This is the class responsible for storing my user id, in which case I also use Bas to generate an encrypted id, when logging in with the user I saved their id in the Sharedpreferenceuser class with the following command: `

                        //SALVANDO OS DADOS NO SHARED PREFERENCES
                        SharedPreferencesUser preferencesUser = new SharedPreferencesUser(LoginActivity.this);
                        preferencesUser.salvarUsuarioPreferences(identificador, gNome);

Where gnome is the variable that receives the name of the user and the identifier is his id, so when I log in I save this data to be able to recover them in the demias activities with the previous call.

public class SharedPreferencesUser {

//ATRIBUTOS
private Context contexto;
private SharedPreferences preferencias;
private final String NOME_ARQUIVO = "STUDYNG.PREFERENCES";
private final int MODE = 0;
private SharedPreferences.Editor editor;

private final String CHAVE_IDENTIFICADOR = "identificador";
private final String CHAVE_NOME = "nomeUsuario";

public SharedPreferencesUser(Context contextoParametro){
    contexto = contextoParametro;
    preferencias = contexto.getSharedPreferences(NOME_ARQUIVO, MODE);
    editor = preferencias.edit();
}

//SALVANDO E RECUPERANDO USUARIOS
public void salvarUsuarioPreferences(String ident, String nome){
    editor.putString(CHAVE_IDENTIFICADOR, ident);
    editor.putString(CHAVE_NOME, nome);
    editor.commit();
}

//RECUPERANDO
public String getIdentificador(){
    return preferencias.getString(CHAVE_IDENTIFICADOR, null);
}

public String getUsuarioNome(){
    return preferencias.getString(CHAVE_NOME, null);
}

}

  • All right, Eduardo, thanks for the answer. But, this code of yours, is it inserted in on create? In case I used it as a basis, I would include it in that place in my posted above (of course with the necessary amendments)?

  • This, it is created in the oncreate method, firebase.addeventlistener is responsible for activating it, but you can enter firebase.addeventlistener in the on Start method, so every time Activity is launched it will call Eventoouvinte, also advise to overwrite the onStop method and insert the following (for resource saving): firebase.removeEventListener(valueEventListener);

  • Eduardo, this Sharedpreferencesuser, you created how? Because I couldn’t implement sharedpreference with these same parameters that you set.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.