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>
orCall<T>
. I recommend you upgrade the retrofit to version 2 and read this tutorial on retrofit 2. It is well simplified– Uilque Messias
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".
– Clicnet