Get response from a restful java web service on Android

Asked

Viewed 637 times

1

I am developing an application for Android and would like to know how I do to receive a response from the server, the technology I am using on Android is retrofit 2. After sending a POST request, how do I receive a response from the server and from this information make an "if" in the method onResponse Android. When I run the application gives an error on the server, in which case I would just like to receive a true or false so that from this reply I can mount my conditions in the application.

Follow my code on the web service:

@POST
    @Consumes({"application/json"})
    @Path("Usuario/inserir")
    public boolean inserirUsuario(String content) {
        Gson g = new Gson();
        try{
            //JsonReader reader = new JsonReader(new StringReader(content));
            //reader.setLenient(true);
            Usuario u = (Usuario) g.fromJson(content, Usuario.class);
            UsuarioBusiness ub = new UsuarioBusiness();
            System.out.println("Teste saida: " + ub.inserir(u));
            return ub.inserir(u);

        } catch (Exception e){
            throw new NoContentException(content);
        } 
    }

Follow the method code insert into the Business package:

public boolean inserir(Usuario usuario) {
        UsuarioDAO dao = new UsuarioDAO();
        if(dao.inserir(usuario) > 0){
            return true;
        } else {
            return false;
    }
}

Follow my code on Android:

call.enqueue(new Callback<Usuario>() {
                        @Override
                        public void onResponse(Call<Usuario> call, Response<Usuario> response) {
                            if(response.isSuccessful()) {
                                AlertDialog.Builder dialogo1 = new AlertDialog.Builder(MainActivity.this);
                                dialogo1.setTitle("Sucesso");
                                dialogo1.setMessage("Usuario cadastrado com sucesso!");
                                dialogo1.setNeutralButton("ok", null);
                                dialogo1.show();
                            } else {
                                AlertDialog.Builder dialogo1 = new AlertDialog.Builder(MainActivity.this);
                                dialogo1.setTitle("Duplicidade");
                                dialogo1.setMessage("Usuario não cadastrado!");
                                dialogo1.setNeutralButton("ok", null);
                                dialogo1.show();
                            }
                        }

                        @Override
                        public void onFailure(Call<Usuario> call, Throwable t) {
                            txtResult.setText(t.getLocalizedMessage());
                            Log.d("my_tag", "ERROR: " + t.getMessage());
                            Log.d("my_tag", "ERROR: " + t.toString());
                        }
                    });
            }
            });
  • As far as I know, you cannot (and should not) create an instance of Callback<T> or Call<T>. I recommend you upgrade the retrofit to version 2 and read this tutorial on retrofit 2. It is well simplified

  • That way I can register a user in the bank quietly , if I try to register the same user I get a message in the server log saying that that user already exists, my goal would only send a true or false to the android application but it’s not working, only plays for the "onFailure method".

1 answer

1


You’re trying to get a guy Usuario when the server is sending a type boolean.

Try changing your code to:

public interface ClicnetServiceApiContract {  
    @GET("/inserirUsuario")
    Call<boolean> inserirUsuario(@Body Usuario usuario);
}

...

// Aqui você passa o usuário e retorna um objeto to tipo Call<boolean>
Call<boolean> call = seuObjetoApi.inserirUsuario(seuObjetoUsuario);

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

    @Override
    public void onFailure(Call<boolean> call, Throwable t) {

        ...
    }
});

This is because you’re trying to make a call asynchronous

I hope I helped the/

  • It was an error when using "Boolean", I used java.lang.Boolean (Boolean) but it ended up generating this error: "Caused by: com.sun.jersey.api.Messageexception: A message body Writer for Java class java.lang.Boolean, and Java type Boolean, and MIME media type application/octet-stream was not found".

  • 1

    @Clicnet, I just edited the answer :)

  • 1

    In my "insert" method I put a String as return and made the changes you recommended and now it worked. I am very grateful to have helped me. It solved a problem that already beat many days. Thank you very much!

Browser other questions tagged

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