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

时间:2017-04-01 13:45:44

标签: 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个片段组成,其中2个在此活动中正常工作;一个人应该工作,当我在另一个活动中使用它时工作,但在这里工作并且其他两个人根本不工作。

MainActivity能够正确加载数据。在此之前,我试图将一个Bundle从这个活动发送到其余的片段,但是在五个中,三个结果是null,其余两个仍然正在加载数据。现在,我在MainActivity中使用了一个返回数据的函数,然后在片段中使用了getActivity()方法,我知道我无法在其他任何地方使用这些片段。现在,我检查了所有内容并且片段正在接收数据,但即使是现在,它们也没有显示任何内容。这是解析JSON的代码,我使用了recyclelerView,我也在AsyncTask中使用Volley,这样只有在设置完所有内容后才显示默认的messgaes:

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

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

P.S。 &#39;现金&#39;是另一个java类的名称,它应该显示在该特定电影中所有名人的列表。这并不妨碍其他两个没有显示任何数据的类的功能。

2 个答案:

答案 0 :(得分:2)

重要的一点似乎是org.json.JSONException: No value for credits。您是否尝试获取名为credit的标记(JSON数据中不存在)?如果是这样,请进行检查,如

if(jsonObject.has("credits")) {
    ...
}

答案 1 :(得分:2)

您正在访问未在json中退出的credits键值。所以请尝试获得这样的信用值,如果它在[{1}}中退出,它将获得credits键值,否则它将跳过。

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

json

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

String credit = jsonObject.optString("credits")

如果您的信用值是JSONArray,请尝试使用

JSONObject credit = jsonObject.optJSONObject("credits")