Result Web Service RETROFIT in Another Activity - Android

0

I have a Web Service method using the Retrofit library that can be queried from 2 different Activities.

How can I use the result of the Web Service method that is in a class and display on an Activity?

How can I also update a ListView , where I use a central class with the Retrofit method, and when I get the web service result, the list in Activity is updated?

I tried several times, requesting a return of the central class with the Retrofit method, however this return does not happen.

What should I do? Here's a snippet of my code:

I call the Web Service query method in an Activity and expect a return to show the result in TextView.

btnAtualizaEstoque.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    if (verificaConexao()) {

                       new RegrasWebServiceRetrofitHelper().buscaEstoqueOnLine(getActivity(), pro.codpro, pro.codder);

                       tvEstoqueAtual.setText(
                    }
                } catch (Exception ex) {
                    ex.getMessage();
                }
            }
        });

Below is the method that is in the RegrasWebServiceRetrofitHelper class:

public int buscaEstoqueOnLine(final Activity activity, String codpro, String codder) {
        this.context = activity;
        this.activity = activity;

        final int[] quantidade = new int[1];

        Log.e("Incio requisicao", "Estoque Online");

        String select = "SELECT (QTDEST-QTDRES) QTDEST FROM E210EST WHERE CODPRO= '" + codpro + "' AND CODDER = '" + codder + "' AND CODDEP = '1'";

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        Gson gson = new GsonBuilder().registerTypeAdapter(Estoque.class, new EstoqueDeserialize()).setLenient().create();
        final OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
        Retrofit retrofit = new Retrofit
                .Builder()
                .baseUrl(setURL_GET())
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();

        RetrofitService service = retrofit.create(RetrofitService.class);
        Call<List<Estoque>> request = service.estoqueOnLine(senha, select);

        request.enqueue(new Callback<List<Estoque>>() {
            @Override
            public void onResponse(Call<List<Estoque>> call, Response<List<Estoque>> response) {
                if (!response.isSuccessful()) {
                    Log.e(TAG, "Erro Response: " + response.code());
                    Toast.makeText(context.getApplicationContext(), "Erro ao sincronizar Validade Estoque! " + response.code(), Toast.LENGTH_LONG).show();
                } else {
                    Log.e("Final requisicao", "ValidadeEstoque");
                    Log.e("Incio insert", "ValidadeEstoque");

                    List<Estoque> retornoEstoque = response.body();
                    for (int n = 0; n < retornoEstoque.size(); n++) {
                        quantidade[0] = retornoEstoque.get(n).qtdest;
                    }

                }
            }

            @Override
            public void onFailure(Call<List<Estoque>> call, Throwable t) {
                Log.e(TAG, "Erro Failure: " + t.getMessage());
                Toast.makeText(context.getApplicationContext(), "Erro ao sincronizar Validade Estoque! " + t.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
        return quantidade[0];
    }

Thank you in advance for the help.

    
asked by anonymous 06.07.2017 / 13:25

1 answer

1

The enqueue() method of Retrofit accepts a Callback that is executed asynchronously after the request is made and converted.

You can simply pass Callback as a parameter to your method buscaEstoqueOnLine

btnAtualizaEstoque.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    if (verificaConexao()) {

                       new RegrasWebServiceRetrofitHelper().buscaEstoqueOnLine(getActivity(), pro.codpro, pro.codder,
                       new Callback<List<Estoque>>() {
                           @Override
                           public void onResponse(Call<List<Estoque>> call, Response<List<Estoque>> response) {
                               if (!response.isSuccessful()) {
                                   Log.e(TAG, "Erro Response: " + response.code());
                                   Toast.makeText(context.getApplicationContext(), "Erro ao sincronizar Validade Estoque! " + response.code(), Toast.LENGTH_LONG).show();
                                 } else {
                                   Log.e("Final requisicao", "ValidadeEstoque");
                                   Log.e("Incio insert", "ValidadeEstoque");

                               }

                               // Fazer algo com a respota
                               tvEstoqueAtual.setText(???)
                           }

                           @Override
                           public void onFailure(Call<List<Estoque>> call, Throwable t) {
                               Log.e(TAG, "Erro Failure: " + t.getMessage());
                               Toast.makeText(context.getApplicationContext(), "Erro ao sincronizar Validade Estoque! " + t.getMessage(), Toast.LENGTH_LONG).show();
                           }
                       });
                    }
                } catch (Exception ex) {
                    ex.getMessage();
                }
            }
        });

And in the buscaEstoqueOnLine method:

public void buscaEstoqueOnLine(final Activity activity, String codpro, String codder,
    Callback<List<Estoque>> callback) {
        this.context = activity;
        this.activity = activity;

        Log.e("Incio requisicao", "Estoque Online");

        String select = "SELECT (QTDEST-QTDRES) QTDEST FROM E210EST WHERE CODPRO= '" + codpro + "' AND CODDER = '" + codder + "' AND CODDEP = '1'";

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        Gson gson = new GsonBuilder().registerTypeAdapter(Estoque.class, new EstoqueDeserialize()).setLenient().create();
        final OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
        Retrofit retrofit = new Retrofit
                .Builder()
                .baseUrl(setURL_GET())
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();

        RetrofitService service = retrofit.create(RetrofitService.class);
        Call<List<Estoque>> request = service.estoqueOnLine(senha, select);
        request.enqueue(callback);
}

One tip: Creating instances of Gson, OkHttp, and Retrofit all made the requests, just like you are doing, is not the recommended way.

The ideal is to create them once and reuse them.

    
06.07.2017 / 15:37