0

I need to handle the return of a call, however it can return a Boolean or a object. When the phone number is found, it crash right into onFailure.

I'm looking for solutions but all found did not solve my problem.

My Interface:

public interface PessoaService {

    @FormUrlEncoded
    @POST("Pessoa/BuscaContatosAgenda/")
    Call<Boolean> buscaContatoAgenda(@Field("Identificador") String identificador,
                                     @Field("UnidadeId") String unidadeId,
                                     @Field("Telefones") ArrayList<String> telefone);
}

My RetrofitConfig

public class RetrofitConfig {
    private final Retrofit retrofit;

    public RetrofitConfig() {
        this.retrofit = new Retrofit.Builder()
                .baseUrl(DadosEmpresa.URL)
                //O método addConverterFactory recebe a classe que será responsável por lidar com a conversão
                .addConverterFactory(JacksonConverterFactory.create())
                //Utilizamos o método build para criar o objeto Retrofit
                .build();
    }

    public PessoaService getBuscaContatoAgenda() {
        return this.retrofit.create(PessoaService.class);
    }
}

My Activity Function:

 private void verificandoContatos() {
        cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                null, null, null, ContactsContract.Contacts.DISPLAY_NAME);

        telefonesArrayList = new ArrayList<>();
        while (cursor.moveToNext()) {
            String telefone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            telefonesArrayList.add(telefone);
        }
        cursor.close();

        Call<Boolean> call = new RetrofitConfig().getBuscaContatoAgenda().buscaContatoAgenda(pessoa.getIdentificador(), DadosEmpresa.UnidadeID, telefonesArrayList);
        call.enqueue(new Callback<Boolean>() {
            @Override
            public void onResponse(Call<Boolean> call, Response<Boolean> response) {
                if (response.body() == true) {
                    Toast.makeText(AgendaContatoActivity.this, "Nenhum contato foi encontrado na sua agenda!", Toast.LENGTH_LONG).show();
                } else if (response.body() == false) {
                    Toast.makeText(AgendaContatoActivity.this, "Ocorreu um erro inesperado. Tente novamente mais tarde.", Toast.LENGTH_LONG).show();
                    Log.e(TAG, "onResponse: " + response.body().toString());
                } else {
                    Toast.makeText(AgendaContatoActivity.this, "Esses são seus contatos encontrados", Toast.LENGTH_LONG).show();
                    createRecyclerView();
                }
            }

            @Override
            public void onFailure(Call<Boolean> call, Throwable t) {
                Log.e(TAG, "onFailure: Erro ao enviar contatos: " + t.getMessage());
                Toast.makeText(getBaseContext(), "Ocorreu um erro inesperado. Tente novamente.", Toast.LENGTH_LONG).show();

            }
        });
    }

t.getMessage = com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.Boolean out of START_ARRAY token at [Source: okhttp3.ResponseBody$BomAwareReader@f41ca80; line: 1, column: 1]

EDIT/UPDATE/SOLUTION

I found a way to resolve my problem after help in comments. Is not the best way, but WORKS FOR THIS CASE:

 private void verificandoContatos() {
        cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                null, null, null, ContactsContract.Contacts.DISPLAY_NAME);

        telefonesArrayList = new ArrayList<>();
        while (cursor.moveToNext()) {
            String telefone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            telefonesArrayList.add(telefone);
        }
        cursor.close();

        Call<ArrayList<GetContatoAgenda>> call = new RetrofitConfig().getBuscaContatoAgenda().buscaContatoAgenda(pessoa.getIdentificador(), DadosEmpresa.UnidadeID, telefonesArrayList);
        call.enqueue(new Callback<ArrayList<GetContatoAgenda>>() {
            @Override
            public void onResponse(Call<ArrayList<GetContatoAgenda>> call, Response<ArrayList<GetContatoAgenda>> response) {
                Toast.makeText(AgendaContatoActivity.this, "Esses são seus contatos encontrados em nossa aplicativo!", Toast.LENGTH_LONG).show();
                contatoArrayList = new ArrayList<GetContatoAgenda>();
                //Como a Callback do Retrofit já faz o mapeamento, então fazemos o contatoArrayList receber a response.body();
                contatoArrayList = response.body();
                createRecyclerView();
            }

            @Override
            public void onFailure(Call<ArrayList<GetContatoAgenda>> call, Throwable t) {
                Log.e(TAG, "onFailure: Erro ao enviar contatos: " + t.getMessage());
                Toast.makeText(getBaseContext(), "Ocorreu um erro inesperado. Tente novamente.", Toast.LENGTH_LONG).show();

            }
        });
    }

1 Answer 1

0

The problem is in your model. You need to make sure that JSON response which you get is 100% fit the model you use for deserialization This line is a problem. Here suppose to be a model which you show in comments

Call<Boolean> call

When you got the JSON response you suppose to parse data from it. That is good topic how to do that Android parse JSONObject

Sign up to request clarification or add additional context in comments.

22 Comments

This is my problem. I receive 2 JSON responses. Is there a way to make a generic retrofit callback?
@GabrielJúniordeSouza you have to make a model for each type of response and connect response to the model properly. It will not generate model for you. Glad to help you
@GabrielJúniordeSouza show your response what you got there? I guess it suppose to be an object NOT boolean.
The response return multiple results. If TRUE, the return is a message (because no contacts are found), if FALSE, the return is a error message and if catch on another excepetion, return a ArrayList of Contatos
@GabrielJúniordeSouza TRUE or FALSE is a VALUE of the result. Response suppose to be an OBJECT where value can be true or false. Where this response come from? Give the whole picture
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.