java - 在 doInBackground 中使用 OkHttpClient 时应用程序崩溃

标签 java android okhttp

我的应用程序在 Android LOLLIPOP 上运行良好,但在较低版本中,程序崩溃并显示此错误:

Exception caught java.lang.RuntimeException: An error occured while executing doInBackground()

并指向这行代码:

OkHttpClient client = new OkHttpClient();

这是我的代码:

private void getMoviesFromDBz(int id) {

    AsyncTask<Integer, Void, Void> asyncTask = new AsyncTask<Integer, Void, Void>() {



        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }


        @Override
        protected Void doInBackground(Integer... movieIds) {

            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(linkkk + movieIds[0])
                    .build();
            try {
                Response response = client.newCall(request).execute();

                JSONArray array = new JSONArray(response.body().string());

                for (int i = 0; i < array.length(); i++) {

                    JSONObject object = array.getJSONObject(i);

                    Movie movie = new Movie(object.getInt("id") , object.getString("per") , object.getString("movie_name"),
                            object.getString("movie_image"), object.getString("movie_genre") , object.getString("movie_discription") , object.getString("movie_lat"), object.getString("movie_lon") , object.getString("movie_marker") , object.getString("sort") , object.getString("price") , object.getString("email") , object.getString("tell") , object.getString("location") , object.getString("count"));


                    ItemOneFragment.this.movies2.add(movie);
                }


            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            adapter2.notifyDataSetChanged();
            getMoviesFromDB(0);
        }
    };

    asyncTask.execute(id);
    scroll2 = 1;
}

最佳答案

您正在尝试访问后台线程中的主/UI 线程:

ItemOneFragment.this.movi​​es2.add(电影);

只需返回 movie 对象并在 onPostExecute() 方法上执行上面的行,我也不建议实例化 OkHttpClient对于每个请求。

关于java - 在 doInBackground 中使用 OkHttpClient 时应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46266145/

相关文章:

java - VisualVM 堆转储 OQL 渲染对象内的数组

解决冲突后Android Studio Git-merge不会结束

java - Android 拨号器应用程序中禁止使用的号码是什么?

java - 如何在Java中创建临时文件时删除ip和其他数值

android - 每当我在模拟器中打开它时,我的布局都会变得困惑(它是带有 TextView 的背景图像)

android - 如何用okhttp MultipartBuilder数据发送字符串数组数据

android - 看不到作为依赖项添加的包内的类

java - 当我们有 OkHttp 时为什么要使用 Retrofit

java - 第二个套接字写入似乎没有发送到网络

android - 如何从 Android 上的电子邮件中的链接打开应用程序?