【问题标题】:Return value from retrofit onResponse android outside of enqueue in AsyncLoader从 AsyncLoader 中的入队之外的改造 onResponse android 返回值
【发布时间】:2021-04-23 01:13:04
【问题描述】:

如何从入队函数返回值到 LoadinBackground() listnews 返回为 null

公共类 NewsAppLoader 扩展 AsyncTaskLoader {

private static final String USGS_REQUEST_URL =
        "https://newsapi.org/v2/everything?q=tesla&from=2021-04-18&sortBy=publishedAt&apiKey=47ebcd70505c4649b04dd050c8bbe307";
private static final String BASE_URL =
        "https://newsapi.org/v2/";
private static final String LOG_TAG = "check";
final String API_KEY = "47ebcd70505c4649b04dd050c8bbe307";

public NewsAppLoader(Context context) {
    super(context);
    //this.apiClient = apiClient;
}

NewsAppAdapter newsAdapter;
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build();

APIInterface api = retrofit.create(APIInterface.class);
Call<ResponseModel> call = api.getLatestNews("Tesla", API_KEY);

// @Nullable
@SuppressLint("LongLogTag")
@Override
public ArrayList<News> loadInBackground() {

    ArrayList<News> listNews = new ArrayList<News>();


    call.enqueue(new Callback<ResponseModel>() {
        @Override
        public void onResponse(Call<ResponseModel> call, Response<ResponseModel> response) {

            if (response.body().getStatus().equals("ok")) {

                List<Article> articleList = response.body().getArticles();
                if (articleList.size() > 0) {
                    String title = articleList.get(0).getTitle();
                    String desc = articleList.get(0).getDescription();
                    String author = articleList.get(0).getAuthor();
                    String imgURL = articleList.get(0).getUrlToImage();

                    listNews.add(new News(title, null, desc, author));
                    // return new ArrayList<News>(listNews);
                    //getNewsList(listNews);

                }
            }


            //return articleList;
        }

        @Override
        public void onFailure(Call<ResponseModel> call, Throwable t) {
            Log.e("out", t.toString());
        }
    });


    return listNews;
}

// listNews = callRetrofit(call);

//return listNews;


public ArrayList<News> getNewsList(ArrayList<News> news) {
    return news;
}

}

请建议任何将值从 OnResponse 返回到 LoadinBackground() 的方法。这样我就可以在 List View 适配器中加载这些值。

【问题讨论】:

    标签: java android retrofit


    【解决方案1】:

    您可以使用call.execute 同步获取响应。但是 AsyncTask 根本不是强制性的,您可以在没有 AsyncTask 的情况下使用您当前的代码。实际上,Retrofit 在你使用call.enqueue 时会在后台执行 HTTP 请求,所以你可以在没有 AsyncTask 的情况下轻松使用它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-10
      • 1970-01-01
      • 1970-01-01
      • 2021-03-27
      • 1970-01-01
      • 1970-01-01
      • 2020-10-11
      • 1970-01-01
      相关资源
      最近更新 更多