I'm developing an Android application and would like to know how do I get a response from the server, the technology I'm using on Android is the retrofit 2. After sending a POST request, how do I get a response from the server and from that information do an "if" in Android's onResponse method. When I run the application it gives an error on the server, in that case I would just like to receive a true or false so that from this answer I can mount my conditions in the application.
Follow my code in 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);
}
}
Here is the code for the insert method in 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());
}
});
}
});