简体   繁体   中英

How to make a void method with Retrofit return string?

So, here is the method in my adapter. Later on, in onBindViewHolder() method I want to perform such action: String pic_url = showJustProduct(product_name); , but the onResponse method can`t return anything except void. What should I do to put img_url to pic_url ?

public void showJustProduct(String title){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://url")
                .addConverterFactory(GsonConverterFactory.create())
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();

        JustJsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JustJsonPlaceHolderApi.class);
        Call<JustProducts> call = jsonPlaceHolderApi.getProducts(title);

        call.enqueue(new Callback<JustProducts>() {

            @SuppressLint("SetTextI18n")
            @Override
            public void onResponse(@NotNull Call<JustProducts> call, @NotNull Response<JustProducts> response) {
                if (response.isSuccessful()) {
                    assert response.body() != null;
                    List<JustProduct> justproducts = response.body().getProducts();
                    JustProduct justProduct = justproducts.get(0);
                    String img_url = justProduct.getImage();
                    Log.e("1", "it works!");
                }

            }

            @Override
            public void onFailure(@NotNull Call<JustProducts> call, @NotNull Throwable t) {
                Log.e("failure", Objects.requireNonNull(t.getLocalizedMessage()));
            }
        });
    }

You can use synchronized call.execute() method instead of call.enqueue() .

This can lead to NetworkOnMainThreadException . So be sure to execute it on background thread not UI thread.

Example:

Response<JustProducts> response = jsonPlaceHolderApi.getProducts(title).execute();
if (response.isSuccessful()) {
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM