Login with retrofit android

Asked

Viewed 839 times

-2

Hi I asked a question and could not help me, I have a webservice who’s making a get that when entered the user name it will allow access to the application and thus will pass the user to the next screen.

That is the code:

public class LoginActivity extends AppCompatActivity {

    public static final String PREFS_USER = "Preferencia";
    EditText user;
    Button salvar;
    EditText password;

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

        user = (EditText) findViewById(R.id.username);
        password = (EditText) findViewById(R.id.senha);

        salvar = (Button) findViewById(R.id.salvar);
        salvar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences settings = getSharedPreferences(PREFS_USER, 0);
                SharedPreferences.Editor editor = settings.edit();
                editor.putString("PrefUser", user.getText().toString());
                editor.putString("PrefPass", password.getText().toString());

                //Confirma a gravação dos dados
                editor.commit();

                loadJson(user.getText().toString());

            }
        });

        SharedPreferences settings = getSharedPreferences(PREFS_USER, 0);
        user.setText(settings.getString("PrefUser", ""));
        password.setText(settings.getString("PrefPass", ""));
    }

    public void loadJson(String usuario){

        Retrofit.Builder builder = new Retrofit.Builder()
                .baseUrl("http://"+getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).getString("PrefHost", "") +":8080/FazendaWebservice/webresources/fazenda/")
                .addConverterFactory(GsonConverterFactory.create());

        Retrofit retrofit = builder.build();

        AcessoClient client = retrofit.create(AcessoClient.class);
        Call<Acesso> call = client.reposForUsuario(usuario);

        call.enqueue(new Callback<Acesso>() {
            @Override
            public void onResponse(Call<Acesso> call, Response<Acesso> response) {

            }

            @Override
            public void onFailure(Call<Acesso> call, Throwable t) {
                Toast.makeText(LoginActivity.this, "         Erro ao estabelecer conexão"+ "\n"+"            Verifique o host inserido"+"\n"+"Por favor tente novamente mais tarde!", Toast.LENGTH_SHORT).show();
            }
        });
    }

Class Acesso:

public class Acesso {

    private String nomeusuario;
    private String senhausuario;
    private String listaprodutos;
    private String vendasonline;

    public String getNomeusuario() {
        return nomeusuario;
    }

    public void setNomeusuario(String nomeusuario) {
        this.nomeusuario = nomeusuario;
    }

    public String getSenhausuario() {
        return senhausuario;
    }

    public void setSenhausuario(String senhausuario) {
        this.senhausuario = senhausuario;
    }

    public String getListaprodutos() {
        return listaprodutos;
    }

    public void setListaprodutos(String listaprodutos) {
        this.listaprodutos = listaprodutos;
    }

    public String getVendasonline() {
        return vendasonline;
    }

    public void setVendasonline(String vendasonline) {
        this.vendasonline = vendasonline;
    }
}

Class AcessoClient:

public interface AcessoClient {
    @GET("Acesso/get/{usuario}")
    Call <Acesso> reposForUsuario(
            @Path("usuario") String usuario
    );
}

JSON returned from Webservice

{"nomeusuario":"admin","senhausuario":"yMJsiuiTcpC","listaprodutos":"S","vendasonline":"S"}

I don’t know what to put inside the onResponse so he ends up doing the validation, someone helps me?

  • 2
  • Dude is not duplicate of anything, they didn’t solve my problem I’m trying, they did this duplicate scheme there, but the other code had nothing to do with my

  • 1

    it will not be by asking several times the same question that will solve :), for that there is the edit, in case someone does not understand your explanation you can improve it, Asking the same questions over and over can even be interpreted as spam and lead to a possible ban or limitation on your account. You asked the same question (changed the words), and copied the same code result yes is duplicated

  • Got it, all right, you know how to help me?

  • Understand @Renatocrim that a duplicate question is a question that has relevance or that addresses the same theme as yours. Hardly the duplicate of the question will have the same code as your question, but the answers of them can guide you in solving the problem.

  • Yes I know, and I researched and tested the other code I changed it and it didn’t lead me to anything... But I’ve solved thank you

Show 1 more comment

1 answer

5


First you have to "serialize" the variables of your class Acesso. Take an example:

public class Acesso implements Serializable {

    private static final long serialVersionUID = -2161110911377686463L;

    @SerializedName("nomeusuario")
    private String nomeusuario;

    @SerializedName("senhausuario")
    private String senhausuario;

    // restante do seu código aqui... 
}

It is also necessary to change method loadJson() to receive the user and password values.

public void loadJson(final String usuario, final  String password){
    // restante do conteúdo aqui...
}

So, finally, to receive the information inside the onResponse you use the response.body(). Take an example:

call.enqueue(new Callback<Acesso>() {
    @Override
    public void onResponse(Call<Acesso> call, Response<Acesso> response) {

         Acesso acesso = response.body();

         // essa condição compara os valores do webservice
         // com os valores que você está passando por parâmetro
         if(acesso.getNomeusuario().equals(usuario) 
               && acesso.getSenhausuario.equals(password)){
             // se entrou aqui, as credenciais estão corretas

             // aqui você será redirecionado para uma classe qualquer
             // que deseja ir usando o Intent
             Intent i = new Intent(LoginActivity.this, Entrou.class);
             startActivity(i);
         } else {
             // se entrou aqui, ou a nome de usuário ou password
             // estão incorretas
         }             
    }

    @Override
    public void onFailure(Call<Acesso> call, Throwable t) {
        Toast.makeText(LoginActivity.this, "Erro ao estabelecer conexão"+ "\n"+"            Verifique o host inserido"+"\n"+"Por favor tente novamente mais tarde!", Toast.LENGTH_SHORT).show();
    }
});
  • Then face what I can’t do is do onrespons Access = Access.body(); // Here below you will have already filled the variable // access, in which you can do the validation // user access. That part not knowing how to do, I’m new to android

  • @Renatocrispim Do you know how to debug the code?! The information will actually arrive in response.body()... You have to debug and see what’s coming for you on resnponse.body();

  • I know debug, but it turns out dps Access = Answer.body(); I don’t have any code you understand?

  • @Renatocrispim would be interesting if you put in your code the Access class and also the result that is coming from your webservice. Otherwise it gets hard Brow, without a crystal ball.

  • OK I’ll edit and put it here, but debugging it, it looks for the user I want, just not passing the page

  • @Renatocrispim will not pass until you put a condition to pass. For me to do this for you, I need you to edit and input the two information I asked for. The class Acesso and the result that returns from the webservice.

  • It’s redacted, I wonder if you can make it?

  • @Renatocrispim the second information I asked you did not put in the question. It would be the JSON that returns from the server.

  • This is ip: http://192.168.25.212:8080/Fazendawebservice/webresources/farm/Access/get/admin and this is what it returns {"username":"admin","senhausuario":"yMJsiuiTcpC","listproducts":"S","vendasonline":"S"}

  • @Renatocrispim ask the question please.

  • I got it, it’s at the end

  • Got to see man ?

  • @Renatocrispim it there works for me always. Good luck.

  • I don’t understand, how it works for you always?

  • I’m trying to put this code inside onResponse: Access = Response.body(); if (access.getNomeuser() == user.gettext().toString()) { Toast.makeText(getApplicationContext(), "User : " + user.gettext().toString(), Toast.LENGTH_SHORT). show(); Intent Intent = new Intent(Loginactivity.this, Buscaactivity. }class); startActivity(Intent); }

  • @Renatocrispim I’m saying that this is how I showed you is how I do in my applications.

  • 1

    Worked thanks.

Show 12 more comments

Browser other questions tagged

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