java - Okhttp3 - 调用 API 后出现 IndexOutOfBoundsException

标签 java android okhttp

我是 Android 开发新手,但我很困惑为什么我可以调用我的 API,但它没有及时填充我的类以供回收器 View 填充。我收到 IndexOutOfBoundsException 因为 mData.getDataFeeds() 返回 null。如果我调试这个应用程序并慢慢地浏览它,它就会起作用。

ListFeedAdapter listFeedAdapter = new ListFeedAdapter(mData.getDataFeeds());

我有一个获取 fragment 的 Activity 。

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_list, container, false);

    RecyclerView recyclerView = view.findViewById(R.id.listRecyclerView);

    try {
        login();
        getFeed();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

    ListFeedAdapter listFeedAdapter = new ListFeedAdapter(mData.getDataFeeds());
    recyclerView.setAdapter(listFeedAdapter);

    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
    recyclerView.setLayoutManager(layoutManager);


    return view;
}

然后我调用login()

private void login() throws IOException {

    String user = "user";
    String password = "pass";
    String loginUrl = getString(R.string.jsonLogin);

    OkHttpClient client = new OkHttpClient.Builder()
            .build();

    JSONObject credentials = new JSONObject();
    JSONObject session = new JSONObject();

    try {
        credentials.put("email", user);
        credentials.put("password", password);
        session.put("session", credentials);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    MediaType mediaType = MediaType.parse("application/json");

    RequestBody body = RequestBody.create(mediaType, session.toString());

    Request request = new Request.Builder()
            .url(loginUrl)
            .post(body)
            .addHeader("Content-Type", mediaType.toString())
            .build();

    Call call = client.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {

            String jsonData = response.body().string();
            String jsonHead = response.headers("Set-Cookie").toString();

            if(response.isSuccessful()) {
                for (String setCookie : response.headers("Set-Cookie")) {
                    cookies.add(Cookie.parse(response.request().url(), setCookie));
                }
            }
        }
    });

getFeed()

 private void getFeed() throws IOException, JSONException {

    String loginUrl = "http://testurlhere";

    OkHttpClient client = new OkHttpClient.Builder()
            .build();

    MediaType mediaType = MediaType.parse("application/json");

    Request request = new Request.Builder()
            .url(loginUrl)
            .get()
            .addHeader("Content-Type", mediaType.toString())
            .addHeader("_session", cookies.get(0).toString())
            .build();

    Call call = client.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            try {

                String jsonData = response.body().string();
                String jsonHead = response.headers("Set-Cookie").toString();
                Log.v(TAG, jsonData);

                if (response.isSuccessful()) {
                    mData = parseDataFeed(jsonData);
                    getActivity().runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            updateDisplay();
                        }
                    });

                }
            }
            catch (IOException e) {
                Log.e(TAG, "Exception caught: ", e);
            }
            catch (JSONException e) {
                Log.e(TAG, "Exception caught: ", e);
            }
        }
    });
}

最佳答案

okhttp是异步操作,应该在onResponse()之后使用mData

 call.enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        e.printStackTrace();
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        try {

            String jsonData = response.body().string();
            String jsonHead = response.headers("Set-Cookie").toString();
            Log.v(TAG, jsonData);

            if (response.isSuccessful()) {
                mData = parseDataFeed(jsonData);
                getActivity().runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        ListFeedAdapter adapter = new ListFeedAdapter(mData.getDataFeeds());
                        rexyxlerView.setAdapter(adapter);
                        updateDisplay();
                    }
                });

            }
        }
        catch (IOException e) {
            Log.e(TAG, "Exception caught: ", e);
        }
        catch (JSONException e) {
            Log.e(TAG, "Exception caught: ", e);
        }
    }
});

关于java - Okhttp3 - 调用 API 后出现 IndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48332744/

相关文章:

java - 在扩展 RecyclerView.Adapter 时使用装饰器模式是否合适?

java - 定义要在 java 端点和 android 中使用的 Java 类

android - Flutter:如何将 RefreshIndicator 与 SliverAppBar 一起使用

linux - 无法使用 Apache HTTP 从 OkHTTP/ALPN/Linux 客户端建立 HTTP/2 连接

java - 通过okhttp3上传文件

java - 在 xtext 语法中定义原语

java - 监视 Java Hibernate 数据检索

java - 返回 OkHttp 异步结果有问题

java - 具有 Spring Security 4(java 配置)的 CAS 4 - 在票证授予 SSO 后卡在重定向循环中

Android Base64 返回比图像大得多的字符串