在asyncloader中排队之外改装onresponse android的返回值

ha5z0ras  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(293)

如何将值从enqueue函数返回到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()的值。这样我就可以在列表视图适配器中加载这些值。

gev0vcfq

gev0vcfq1#

你可以用 call.execute 同步得到回应。但是asynctask不是必需的,您可以使用当前代码而不使用asynctask。实际上,当您使用 call.enqueue ,因此您可以轻松地使用它而无需执行异步任务

相关问题