简体   繁体   English

如何使用 Retrofit 返回字符串制作 void 方法?

[英]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);稍后,在 onBindViewHolder() 方法中,我想执行这样的操作: String pic_url = showJustProduct(product_name); , but the onResponse method can`t return anything except void. ,但是 onResponse 方法除了 void 不能返回任何东西。 What should I do to put img_url to pic_url ?我应该怎么做才能将img_url放到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() .您可以使用同步call.execute()方法而不是call.enqueue()

This can lead to NetworkOnMainThreadException .这可能导致NetworkOnMainThreadException So be sure to execute it on background thread not UI thread.所以一定要在后台线程而不是 UI 线程上执行它。

Example:例子:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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