Reputation: 49
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()));
}
});
}
Upvotes: 0
Views: 175
Reputation: 36
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()) {
...
}
Upvotes: 1