繁体   English   中英

从 retrofit onResponse android 在 AsyncLoader 中的队列之外返回值

[英]Return value from retrofit onResponse android outside of enqueue in AsyncLoader

如何从队列 function 返回值到 LoadinBackground() listnews 返回为 null

公共 class NewsAppLoader 扩展 AsyncTaskLoader<ArrayList> {

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() 的方法。 这样我就可以在列表视图适配器中加载该值。

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

暂无
暂无

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

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