Result Web Service RETROFIT in Other Activity - Android

Asked

Viewed 190 times

0

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

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

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

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

What should I do? Follow an excerpt 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 in the class Regraswebserviceretrofithelper:

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];
    }

Thanks in advance for the help.

1 answer

1


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

You can just pass the Callback as a parameter for 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 method buscaEstoqueOnLine:

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);
}

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

The ideal is to create them once and reuse them.

  • Hello Leonardo, thank you so much for the tip. I will implement your suggestion and post the result after. Hugs

  • Leonardo, the 'Callback' method worked perfectly. Thank you very much for your help. As for the questions of creating instances of 'Gson', 'Okhttp' and 'Retrofit', how would be the best method to make this request a single time, and as you see, I need to do a Deserialize. Your help would help me because I make more or less requests, one after the other. I thank you already.

  • The request can (in some cases must) be made several times. I was referring to the creation of the variables Gson, Retrofit and Okhttp. The simplest way is to create a Singleton to store and reuse them. Here are some examples. https://stackoverflow.com/a/41672999

Browser other questions tagged

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