该函数总是返回null,我被卡在上面

时间:2016-12-11 15:23:23

标签: android json rest retrofit

我从REST API获取图像并在onResponse上成功分配给数组。但是,我无法将随机图像传递给另一个类,因为它始终返回empty 我怎么做到的?请帮帮我。

我的function如下:

private String[] headerImages = new String[10];

public String fetchOnlyImages(String url) {
    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .readTimeout(60, TimeUnit.SECONDS)
            .connectTimeout(60, TimeUnit.SECONDS)
            .authenticator(new Authenticator() {
                @Override
                public Request authenticate(Route route, Response response) throws IOException {
                    String credential = Credentials.basic(USERNAME, PASSWORD);

                    return response.request().newBuilder()
                            .header(AUTH, credential).build();
                }
            }).build();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(NewsService.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .client(okHttpClient)
            .build();

    final NewsService newsService = retrofit.create(NewsService.class);
    Call<HolderNode> holderNodeCall = newsService.holderNode(url);



    holderNodeCall.enqueue(new Callback<HolderNode>() {
        @Override
        public void onResponse(Call<HolderNode> call, retrofit2.Response<HolderNode> response) {
            if (response.isSuccessful()) {
                HolderNode holderNode = response.body();
                MainNode mainNode;

                try {
                    for (int i = 0; i < holderNode.nodes.size(); i++) {
                        mainNode = holderNode.nodes.get(i);
                        if (mainNode.node.image != null) {
                            String imageUrl = mainNode.node.image.src.substring(0, mainNode.node.image.src.length() - 13);
                            headerImages[i] = imageUrl;
                        }
                    }
                } catch (Exception ignored) {
                }
            }
        }

        @Override
        public void onFailure(Call<HolderNode> call, Throwable t) {

        }
    });

    Random random = new Random();
    int chosenNumber = random.nextInt(headerImages.length);

    return headerImages[chosenNumber];
}
}

1 个答案:

答案 0 :(得分:3)

您无法从此方法返回 - 这不是异步代码的工作方式。

在保证拥有阵列后,您必须在onResponse方法内继续处理。

您的问题是在输入onResponse之前返回null数组

您可以为fetchOnlyImages提供回调参数,并将其传递给网络电话