java - Android:无法显示 JSON 数据,原因未知

标签 java android json android-fragments android-volley

应用程序中没有错误,logcat 也没有显示任何有用的内容,应用程序没有崩溃,但是,它也没有显示任何内容。以下是我收到的 JSON 响应类型:

{
"backdrop_path": "/mmxxEpTqVdwBlu5Pii7tbedBkPC.jpg",
"created_by": [
    {
        "id": 1216615,
        "name": "Andrew Kreisberg",
        "profile_path": "/giFmwdBAw6uwC8yeHPaW6dq6YT8.jpg"
    },
    {
        "id": 211962,
        "name": "Geoff Johns",
        "profile_path": "/xkaRZu1o1NILQ4PcRXqnjOrJ0Y0.jpg"
    }
],
"episode_run_time": [
    44
],
"first_air_date": "2014-10-07",
"genres": [
    {
        "id": 18,
        "name": "Drama"
    },
    {
        "id": 10765,
        "name": "Sci-Fi & Fantasy"
    }
],
"homepage": "http://www.cwtv.com/shows/the-flash/",
"id": 60735,
"in_production": true,
"languages": [
    "en"
],
"last_air_date": "2017-04-25",
"name": "The Flash",
"networks": [
    {
        "id": 71,
        "name": "The CW"
    }
],
"number_of_episodes": 65,
"number_of_seasons": 3,
"origin_country": [
    "US"
],
"original_language": "en",
"original_name": "The Flash",
"overview": "After a particle accelerator causes a freak storm, CSI Investigator Barry Allen is struck by lightning and falls into a coma. Months later he awakens with the power of super speed, granting him the ability to move through Central City like an unseen guardian angel. Though initially excited by his newfound powers, Barry is shocked to discover he is not the only \"meta-human\" who was created in the wake of the accelerator explosion -- and not everyone is using their new powers for good. Barry partners with S.T.A.R. Labs and dedicates his life to protect the innocent. For now, only a few close friends and associates know that Barry is literally the fastest man alive, but it won't be long before the world learns what Barry Allen has become...The Flash.",
"popularity": 50.611816,
"poster_path": "/lUFK7ElGCk9kVEryDJHICeNdmd1.jpg",
"production_companies": [
    {
        "name": "Warner Bros. Television",
        "id": 1957
    },
    {
        "name": "DC Entertainment",
        "id": 9993
    },
    {
        "name": "Berlanti Productions",
        "id": 27711
    }
],
"seasons": [
    {
        "air_date": "2016-04-19",
        "episode_count": 5,
        "id": 79954,
        "poster_path": null,
        "season_number": 0
    },
    {
        "air_date": "2014-10-07",
        "episode_count": 23,
        "id": 60523,
        "poster_path": "/hJysBrladxYuP5065vCAf91KcyB.jpg",
        "season_number": 1
    },
    {
        "air_date": "2015-10-06",
        "episode_count": 23,
        "id": 66922,
        "poster_path": "/8xWZPVX1cv9V5YD1RPeLj9QZDE9.jpg",
        "season_number": 2
    },
    {
        "air_date": "2016-10-04",
        "episode_count": 19,
        "id": 77888,
        "poster_path": "/6F8v0n37xbGY4syGcW6pRcB9BcY.jpg",
        "season_number": 3
    }
],
"status": "Returning Series",
"type": "Scripted",
"vote_average": 6.7,
"vote_count": 984
}

以下是应用程序显示内容的屏幕截图: Click here to see the image

请注意,主海报、背景和所有其他内容(包括 tabLayout)都是 MainActivity 的一部分,viewPager 由 5 个 fragment 组成,其中 2 个在此 Activity 中工作正常;一个应该可以工作,并且当我将它与另一个 Activity 一起使用时正在工作,但在这里不起作用,另外两个根本不起作用。

MainActivity 能够正常加载数据。在此之前,我试图将一个 Bundle 从该 Activity 发送到其余 fragment ,但在五个 fragment 中,三个结果为空,其余两个仍在加载数据。现在,我在 MainActivity 中使用一个函数,该函数返回数据,然后在 fragment 中使用 getActivity() 方法,我知道我将无法在其他任何地方使用这些 fragment 。现在,我已经检查了所有内容, fragment 正在接收数据,但即使现在,它们也没有显示任何内容。这是解析 JSON 的代码,我使用了 recyclerView,还在 AsyncTask 中使用了 Volley,以便仅在所有内容都设置好后才显示默认消息:

private class connectToTheInternet extends AsyncTask<String, Void, Void> {

    @Override
    protected Void doInBackground(String... strings) {

        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d("receivedData", response);

                        try {
                            JSONObject parentObject = new JSONObject(response);
                            Log.d("receivedData", response);

                            JSONArray genreArray = parentObject.getJSONArray("genres");
                            for (int i = 0; i < genreArray.length(); i++) {
                                JSONObject tempObject = genreArray.getJSONObject(i);
                                if (i < genreArray.length() - 1) {
                                    genreCollector = genreCollector + tempObject.getString("name") + ", ";
                                } else
                                    genreCollector = genreCollector + tempObject.getString("name");
                            }
                            genre.setText(genreCollector);

                            if (genreArray.length() == 1) {
                                genreTag.setText("Genres: ");
                            } else
                                genreTag.setText("Genre: ");

                            JSONArray creatorArray = parentObject.getJSONArray("created_by");
                            for (int i = 0; i < creatorArray.length(); i++) {
                                JSONObject tempObject = creatorArray.getJSONObject(i);

                                if (i < creatorArray.length() - 1) {
                                    creatorName = creatorName + tempObject.getString("name") + ", ";
                                } else {
                                    creatorName = creatorName + tempObject.getString("name");
                                }
                            }
                            createdBy.setText(creatorName);

                            JSONArray runTimeArray = parentObject.getJSONArray("episode_run_time");
                            int arrayLength = runTimeArray.length();

                            for (int i = 0; i < runTimeArray.length(); i++) {
                                //No need for a tempObject, as the values in this array don't have a 'key'.....
                                runTimeCollector += runTimeArray.getInt(i);
                            }
                            runTimeCollector = runTimeCollector / arrayLength;
                            runtime.setText(runTimeCollector);

                            numberOfSeasons.setText(parentObject.getInt("number_of_seasons"));
                            numberOfEpisodes.setText(parentObject.getInt("number_of_episodes"));

                            lastAirDate.setText(convertDate(parentObject.getString("last_air_date")));

                        } catch (JSONException e) {
                            e.printStackTrace();
                            Toast.makeText(getContext(), e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getContext(), "Error Detected", Toast.LENGTH_SHORT).show();
            }
        });

        RequestQueue requestQueue = Volley.newRequestQueue(getContext());
        requestQueue.add(stringRequest);

        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);

        runTimeTag.setText("RunTime:");
        numberOfSeasonsTag.setText("Number Of Seasons:");
        numberOfEpisodesTag.setText("Number Of Episodes:");
        lastAirDateTag.setText("Last Air Date:");
        createdByTag.setText("Created By:");
        overViewTag.setText("OVERVIEW:");
    }
}

这是 logcat 跟踪:

    04-01 09:23:54.292 1503-1503/com.example.android.jsontutorial W/System.err: org.json.JSONException: No value for credits
    04-01 09:23:54.292 1503-1503/com.example.android.jsontutorial W/System.err:     at org.json.JSONObject.get(JSONObject.java:389)
    04-01 09:23:54.292 1503-1503/com.example.android.jsontutorial W/System.err:     at org.json.JSONObject.getJSONObject(JSONObject.java:609)
    04-01 09:23:54.292 1503-1503/com.example.android.jsontutorial W/System.err:     at com.example.android.jsontutorial.credits$1.onResponse(credits.java:109)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at                                         com.example.android.jsontutorial.credits$1.onResponse(credits.java:103)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at android.os.Handler.handleCallback(Handler.java:751)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at android.os.Looper.loop(Looper.java:154)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6077)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
    04-01 09:23:54.293 1503-1503/com.example.android.jsontutorial W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
    04-01 09:24:09.710 1503-1682/com.example.android.jsontutorial D/Volley: [132] BasicNetwork.logSlowRequests: HTTP response for request=<[ ] https://api.themoviedb.org/3/tv/top_rated?api_key=43630259102f25bfa2d21a3039b&language=en-US&page=1 0x89bd75e7 NORMAL 1> [lifetime=22435], [size=18147], [rc=200], [retryCount=1]
    04-01 09:36:07.024 1503-1510/com.example.android.jsontutorial W/art: Suspending all threads took: 5.062ms
    04-01 09:39:12.493 1503-1510/com.example.android.jsontutorial W/art: Suspending all threads took: 26.896ms

请帮忙,因为我是新人,不知道该怎么办......

附注“Credits”是另一个 java 类的名称,该类应该显示在该特定电影中表演的所有名人的列表。这不应该妨碍其他两个不显示任何数据的类的功能。

最佳答案

您正在访问 json 中不存在的 credits 键值。所以请尝试像这样获取credits值,如果它以json形式存在,它将获取credits键值,否则将跳过。

如果您的信用值是字符串,请尝试使用类似

String credit = jsonObject.optString("credits")

如果您的信用值是 JSONObject 那么请尝试使用类似

JSONObject credit = jsonObject.optJSONObject("credits")

如果您的信用值是 JSONArray 那么请尝试使用类似

JSONArray credit = jsonObject.optJSONArray("credits")

关于java - Android:无法显示 JSON 数据,原因未知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43157661/

相关文章:

javascript - 修改 Geonames 的 JSON Ajax 请求

java - 为新的 Spring MVC 项目选择 Thymeleaf 和 A​​ngular

java - Google App Engine DataNucleus 3.1.1 意外异常错误

java - XSD 断言可以用于指定 WSDL 文件吗

java - MPAndroidChart 在图表的水平线上显示标签

javascript - JSON 响应打印 HTML 而不是消息

json - 在配置单元数据类型中, map 比 JSON 字符串快多少?

java - @value 注释返回错误的值

android - 带有 Android Webview 的 Google 图表

Android 工具栏中心标题和自定义字体