EditText already filled in after user login using firebase

0

Hello

I have a question about a process that I can not do. I have the following screen, and I wanted the EditText user to already be populated with the user name or the user's email. I'm new to the mobile programming area, and I tried to do this with sharedpreferences, but I could not mount the code.

Follow the activity screen and firebase database that I'm using. FollowthecodeImadefromactivityhere.publicclassMessageActivityextendsAppCompatActivity{

EditTextedtNome,edtMensagem;ButtonbtnEnviarMensagem;Mensagemmensagem;FirebaseDatabasefirebaseDatabase;DatabaseReferencedatabaseReference;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){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(newView.OnClickListener(){@OverridepublicvoidonClick(Viewv){mensagem=newMensagem();mensagem.setNome(edtNome.getText().toString());mensagem.setMensagem(edtMensagem.getText().toString());DatabaseReferencedatabaseReference=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();
                }
            }
        });
    }
});

}

If anyone can help me out, I'm grateful. Hugs.

    
asked by anonymous 07.09.2017 / 17:23

1 answer

2

Good afternoon! In this case you will need a ValueEventListener to retrieve the information from that user on the system, you will need to create an instance pointing to for example databaseReference.getinstance (). Child ("user"). you used the push method I do not know how to retrieve this value rsrs, but it would be the push "KtDIZ ..."). child ("name"); So you have a reference to this node and then you can access it through the eentlistener ... Here is an example of a code that I did hj which in this case returns all the data of the user registered in the 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 the sharedpreferences the user ID, then passing it on the Firebase reference I called from firebase I can access all nodes from there and arrow them in TextViews or EditText, I am also using the user class model to mediate the data, the secret in this case is the dataSnapshot, it is who brings the data of my reference. I would advise you to search for valueEventListener. link . This is the class responsible for storing my user id, in that case I also use bas to generate an encrypted Id, when I log in with the user I save 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 gets the user's name and the identifier is his id, so when I log in I save this data so I can retrieve it in the previous activities.

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);
}

}

    
07.09.2017 / 18:13