android-studio JSON ERROR [空对象引用上的java.util.List.size()']

时间:2015-12-28 12:13:44

标签: json android-studio

我有一个很大的错误.. 我不知道为什么我有这个......

我的代码:

  public class MainActivity extends ListActivity {

    // URL to get contacts JSON
    private static String url = "https://jordyruiz.herokuapp.com/clubs.json";

    // JSON Node names
    private static final String TAG_Allclub = "Allclub";
    private static final String TAG_ID = "id";
    private static final String TAG_NAME = "NomClub";
    private static final String TAG_LIGUE = "Ligue";
    private static final String TAG_DISTRICT = "District";
    private static final String TAG_NOMBREEQUIPE = "NombreEquipe";
    private static final String TAG_CORRESPONDANT = "Correspondant";
    private static final String TAG_ADRESSE = "Adresse";
    private static final String TAG_EMAIL = "Email";
    private static final String TAG_TELEPHONE = "Telephone";
    private static final String TAG_LATITUDE = "Latitude";
    private static final String TAG_LONGITUDE = "Longitude";
    private static final String TAG_URL = "url";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Calling async task to get json
        new GetClubs().execute();
    }

    /**
     * Async task class to get json by making HTTP call
     */
    private class GetClubs extends AsyncTask<Void, Void, Void> {

        // Hashmap for ListView
        ArrayList<HashMap<String, String>> clubList;
        ProgressDialog pDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Chargement...");
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            WebRequest webreq = new WebRequest();

            // Making a request to url and getting response
            String jsonStr = webreq.makeWebServiceCall(url, WebRequest.GET);

            Log.d("Response: ", "> " + jsonStr);

            clubList = ParseJSON(jsonStr);

            return null;
        }


        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    MainActivity.this, clubList,
                    R.layout.list_item, new String[]{TAG_NAME, TAG_LIGUE,
                    TAG_DISTRICT, TAG_NOMBREEQUIPE}, new int[]{R.id.name,
                    R.id.Ligue, R.id.district, R.id.nombreequipe});

            setListAdapter(adapter);
        }

    }


    private ArrayList<HashMap<String, String>> ParseJSON(String json) {
        if (json != null) {
            try {
                // Hashmap for ListView
                ArrayList<HashMap<String, String>> clubList = new ArrayList<HashMap<String, String>>();

                JSONObject jsonObj = new JSONObject(json);

                // Getting JSON Array node
                JSONArray clubs = jsonObj.getJSONArray(TAG_Allclub);

                // looping through All clubs
                for (int i = 0; i < clubs.length(); i++) {
                    JSONObject c = clubs.getJSONObject(i);

                    String id = c.getString(TAG_ID);
                    String name = c.getString(TAG_NAME);
                    String ligue = c.getString(TAG_LIGUE);
                    String district = c.getString(TAG_DISTRICT);
                    String nombreequipe = c.getString(TAG_NOMBREEQUIPE);
                    String correspondant = c.getString(TAG_CORRESPONDANT);
                    String adresse = c.getString(TAG_ADRESSE);
                    String email = c.getString(TAG_EMAIL);
                    String telephone = c.getString(TAG_TELEPHONE);
                    String latitude = c.getString(TAG_LATITUDE);
                    String longitude = c.getString(TAG_LONGITUDE);
                    String urlweb = c.getString(TAG_URL);

                    // Phone node is JSON Object
                //    JSONObject phone = c.getJSONObject(TAG_PHONE);
                //    String mobile = phone.getString(TAG_PHONE_MOBILE);
                //    String home = phone.getString(TAG_PHONE_HOME);

                    // tmp hashmap for single club
                    HashMap<String, String> club = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    club.put(TAG_ID, id);
                    club.put(TAG_NAME, name);
                    club.put(TAG_LIGUE, ligue);
                    club.put(TAG_DISTRICT, district);
                    club.put(TAG_NOMBREEQUIPE, nombreequipe);
                    // adding club to clubs list
                    clubList.add(club);
                }
                return clubList;
            } catch (JSONException e) {
                e.printStackTrace();
                return null;
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
            return null;
        }
    }
}

和我的json:

{
"Allclub":[{
"id": ​1,
"NomClub": "Alfortville US",
"Ligue": " LIGUE DE PARIS ILE DE FRANCE",
"District": "DISTRICT VAL DE MARNE",
"NombreEquipe": ​23,
"Correspondant": "SAMIR ABDELAZIZ",
"Adresse": "COMPLEXE VAL DE SEINE-Parc Sport, 4 allée Jean Baptiste Preux, - 94140 - ALFORTVILLE",
"Email": "usalfortville@lpiff.fr",
"Telephone": ​148935240,
"Latitude": ​48.7781247,
"Longitude": ​2.42247699999996,
"url": "https://jordyruiz.herokuapp.com/clubs/1.json"},
    {   "id": ​2,
        "NomClub": "PEROU UNI F.C.",
        "Ligue": "LIGUE DE PARIS ILE DE FRANCE",
        "District": "DISTRICT DES HAUTS-DE-SEINE",
        "NombreEquipe": ​1,
        "Correspondant": "CLAVO DIAZ HUGO",
        "Adresse": "2 RUE LOUIS ARMAND - 75015 - PARIS 15",
        "Email": "clavodiaz15@hotmail.com",
        "Telephone": ​672803527,
        "Latitude": ​48.8325026,
        "Longitude": ​2.2759969,
        "url": "https://jordyruiz.herokuapp.com/clubs/2.json"
    }
]}

错误日志:

  

12-28 12:36:41.751 32074-32074 /? E / SELinux:[DEBUG] get_category:变量seinfo:默认灵敏度:NULL,cateogry:NULL   12-28 12:36:46.0​​41 32074-32074 / org.esiea.jordy_ruiz_elisabeth_duong.footballclub E / AndroidRuntime:FATAL EXCEPTION:main   12-28 12:36:46.0​​41 32074-32074 / org.esiea.jordy_ruiz_elisabeth_duong.footballclub E / AndroidRuntime:流程:org.esiea.jordy_ruiz_elisabeth_duong.footballclub,PID:32074   12-28 12:36:46.0​​41 32074-32074 / org.esiea.jordy_ruiz_elisabeth_duong.footballclub E / AndroidRuntime:java.lang.NullPointerException:尝试在空对象上调用接口方法'int java.util.List.size()'参考   12-28 12:36:46.0​​41 32074-32074 / org.esiea.jordy_ruiz_elisabeth_duong.footballclub E / AndroidRuntime:at android.widget.SimpleAdapter.getCount(SimpleAdapter.java:93)   12-28 12:36:46.0​​41 32074-32074 / org.esiea.jordy_ruiz_elisabeth_duong.footballclub E / AndroidRuntime:在android.widget.ListView.setAdapter(ListView.java:502)   12-28 12:36:46.0​​41 32074-32074 / org.esiea.jordy_ruiz_elisabeth_duong.footballclub E / AndroidRuntime:at android.app.ListActivity.setListAdapter(ListActivity.java:265)   12-28 12:36:46.0​​41 32074-32074 / org.esiea.jordy_ruiz_elisabeth_duong.footballclub E / AndroidRuntime:at org.esiea.jordy_ruiz_elisabeth_duong.footballclub.MainActivity $ GetClubs.onPostExecute(MainActivity.java:97)   12-28 12:36:46.0​​41 32074-32074 / org.esiea.jordy_ruiz_elisabeth_duong.footballclub E / AndroidRuntime:at org.esiea.jordy_ruiz_elisabeth_duong.footballclub.MainActivity $ GetClubs.onPostExecute(MainActivity.java:50)   12-28 12:36:46.0​​41 32074-32074 / org.esiea.jordy_ruiz_elisabeth_duong.footballclub E / AndroidRuntime:at android.os.AsyncTask.finish(AsyncTask.java:636)   12-28 12:36:46.0​​41 32074-32074 / org.esiea.jordy_ruiz_elisabeth_duong.footballclub E / AndroidRuntime:at android.os.AsyncTask.access $ 500(AsyncTask.java:177)   12-28 12:36:46.0​​41 32074-32074 / org.esiea.jordy_ruiz_elisabeth_duong.footballclub E / AndroidRuntime:at android.os.AsyncTask $ InternalHandler.handleMessage(AsyncTask.java:653)   12-28 12:36:46.0​​41 32074-32074 / org.esiea.jordy_ruiz_elisabeth_duong.footballclub E / AndroidRuntime:at android.os.Handler.dispatchMessage(Handler.java:102)   12-28 12:36:46.0​​41 32074-32074 / org.esiea.jordy_ruiz_elisabeth_duong.footballclub E / AndroidRuntime:在android.os.Looper.loop(Looper.java:145)   12-28 12:36:46.0​​41 32074-32074 / org.esiea.jordy_ruiz_elisabeth_duong.footballclub E / AndroidRuntime:在android.app.ActivityThread.main(ActivityThread.java:6837)   12-28 12:36:46.0​​41 32074-32074 / org.esiea.jordy_ruiz_elisabeth_duong.footballclub E / AndroidRuntime:at java.lang.reflect.Method.invoke(Native Method)   12-28 12:36:46.0​​41 32074-32074 / org.esiea.jordy_ruiz_elisabeth_duong.footballclub E / AndroidRuntime:at java.lang.reflect.Method.invoke(Method.java:372)   12-28 12:36:46.0​​41 32074-32074 / org.esiea.jordy_ruiz_elisabeth_duong.footballclub E / AndroidRuntime:at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1404)   12-28 12:36:46.0​​41 32074-32074 / org.esiea.jordy_ruiz_elisabeth_duong.footballclub E / AndroidRuntime:at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)

你能帮帮我吗... 感谢

的Jordy

2 个答案:

答案 0 :(得分:0)

对于解析JSON字符串,我建议使用优秀的JsonReader

它是Google创建的API的一部分,名为GSON,自Android 3.0起即可使用。如果您需要在早期的Android版本上使用它,您可以使用独立的JAR文件。更多详情:https://stackoverflow.com/a/10174066/3535408

至于代码,这是使用GSON的json解析器的简短示例:

private static final String TAG_Allclub = "Allclub";
    private static final String TAG_ID = "id";
    private static final String TAG_NAME = "NomClub";
    private static final String TAG_LIGUE = "Ligue";
    private static final String TAG_DISTRICT = "District";
    private static final String TAG_NOMBREEQUIPE = "NombreEquipe";
    private static final String TAG_CORRESPONDANT = "Correspondant";
    private static final String TAG_ADRESSE = "Adresse";
    private static final String TAG_EMAIL = "Email";
    private static final String TAG_TELEPHONE = "Telephone";
    private static final String TAG_LATITUDE = "Latitude";
    private static final String TAG_LONGITUDE = "Longitude";
    private static final String TAG_URL = "url";

    public final static ArrayList<HashMap<String, String>> parseClubJson(final String json) {
        if (TextUtils.isEmpty(json)) // checks if string is null or empty
            throw new IllegalArgumentException("json MUST NOT be NULL or EMPTY!");
        try {
            final InputStreamReader inputStreamReader = new InputStreamReader(new ByteArrayInputStream(json.getBytes("UTF-8")));
            final JsonReader jsonReader = new JsonReader(inputStreamReader);

            final ArrayList<HashMap<String, String>> allClubs = new ArrayList<HashMap<String, String>>();

            jsonReader.beginObject(); // if the json starts with a JSON Object
            while (jsonReader.hasNext()){

                // declare the values here, they will be initialized later
                String id;
                String name;
                String ligue;
                String district;
                String nombreequipe;
                String correspondant;
                String adresse;
                String email;
                String telephone;
                String latitude;
                String longitude;
                String urlweb;

                final String node = jsonReader.nextName(); // get the next available JSON node

                if (node.equals(TAG_Allclub)) {// according to your JSON this looks like an array of JSON Object
                    jsonReader.beginArray(); // so we begin a new array
                    while (jsonReader.hasNext()) { // while there are nodes inside this array
                        jsonReader.beginObject(); // we know it's an array of json objects

                        final String subNode = jsonReader.nextName();
                        if (subNode.equals(TAG_ID))
                            id = jsonReader.nextString(); // we retrieve the value of this node as a String
                        else if (subNode.equals(TAG_NAME))
                            name = jsonReader.nextString();
                        else if (subNode.equals(TAG_LIGUE))
                            ligue = jsonReader.nextString();
                        // etc -> keep checking for each single possible value
                        // don't forget to add an else in case of an unexpected node ...
                        else
                            jsonReader.skipValue(); // ... that we can safely skip

                        jsonReader.endObject(); //once we are over with this object, we close it
                    }
                    jsonReader.endArray(); // never forget to close the array
                }

                // Once done parsing through current club :
                final HashMap<String, String> currentClub = new HashMap<>();
                // put values here
                allClubs.add(currentClub);
            }
            jsonReader.endObject(); // never forget to close an object

            // Once you are done with parsing the json you can build your return your ArrayList of HasMap here


            // Exception Catching requiered
        } catch (final UnsupportedEncodingException uee) { // in case json.getBytes fails
            Log.e(TAG, "Error while parsing JSON - Wrong Encoding! ->\n" + uee.getMessage());
            Log.getStackTraceString(uee);
            return null;
        } catch (final IOException ioe) { // might VERY RARELY occur while reading the current stream.
            Log.e(TAG, "Error while converting from JSON ->\n" + ioe.getMessage());
            return null;
        }
    }

不要忘记在compile 'com.google.code.gson:gson:2.3.1'文件中添加build.gradle或使用import android.util.JsonReader

注意:使用HasMap资源非常昂贵且ArrayList使用大量内存,具体取决于要保留的对象数量(此处为HashMaps)。你最好使用POJO,以便最终得到Club[];

希望它有所帮助!

来自IN&#39; TECH的干杯; - )

答案 1 :(得分:0)

1)在“Void doInBackground”clublist = pareJson(jsonStr)doesent work.Do可以在doInBackground中更改?

2)在“onPostExecute”中它是正确的吗?

3)对于put值,其代码为:“currentClub.put(TAG_ID,id);” ?

4)在“Log.e(TAG,...)doesent work:Error:(165,19)error:找不到符号变量TAG。

public class MainActivity extends ListActivity {

// URL to get contacts JSON
private static String url = "https://jordyruiz.herokuapp.com/clubs.json";

// JSON Node names
private static final String TAG_Allclub = "Allclub";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "NomClub";
private static final String TAG_LIGUE = "Ligue";
private static final String TAG_DISTRICT = "District";
private static final String TAG_NOMBREEQUIPE = "NombreEquipe";
private static final String TAG_CORRESPONDANT = "Correspondant";
private static final String TAG_ADRESSE = "Adresse";
private static final String TAG_EMAIL = "Email";
private static final String TAG_TELEPHONE = "Telephone";
private static final String TAG_LATITUDE = "Latitude";
private static final String TAG_LONGITUDE = "Longitude";
private static final String TAG_URL = "url";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Calling async task to get json
    new GetClubs().execute();
}

/**
 * Async task class to get json by making HTTP call
 */
private class GetClubs extends AsyncTask<Void, Void, Void> {

    ProgressDialog pDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Chargement...");
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        WebRequest webreq = new WebRequest();

        // Making a request to url and getting response
        String jsonStr = webreq.makeWebServiceCall(url, WebRequest.GET);

        Log.d("Response: ", "> " + jsonStr);

      //  clubList = ParseJSON(jsonStr);

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(
                MainActivity.this, parseClubJson(TAG_ID),
                R.layout.list_item, new String[]{TAG_NAME, TAG_LIGUE,
                TAG_DISTRICT, TAG_NOMBREEQUIPE}, new int[]{R.id.name,
                R.id.Ligue, R.id.district, R.id.nombreequipe});

        setListAdapter(adapter);
    }
}
public final static ArrayList<HashMap<String, String>> parseClubJson(final String json) {
    if (TextUtils.isEmpty(json)) // checks if string is null or empty
        throw new IllegalArgumentException("json MUST NOT be NULL or EMPTY!");
    try {
        final InputStreamReader inputStreamReader = new InputStreamReader(new ByteArrayInputStream(json.getBytes("UTF-8")));
        final JsonReader jsonReader = new JsonReader(inputStreamReader);

        final ArrayList<HashMap<String, String>> allClubs = new ArrayList<HashMap<String, String>>();

        jsonReader.beginObject(); // if the json starts with a JSON Object
        while (jsonReader.hasNext()){

            // declare the values here, they will be initialized later
            String id;
            String name;
            String ligue;
            String district;
            String nombreequipe;
            String correspondant;
            String adresse;
            String email;
            String telephone;
            String latitude;
            String longitude;
            String urlweb;

            final String node = jsonReader.nextName(); // get the next available JSON node

            if (node.equals(TAG_Allclub)) {// according to your JSON this looks like an array of JSON Object
                jsonReader.beginArray(); // so we begin a new array
                while (jsonReader.hasNext()) { // while there are nodes inside this array
                    jsonReader.beginObject(); // we know it's an array of json objects

                    final String subNode = jsonReader.nextName();
                    if (subNode.equals(TAG_ID))
                        id = jsonReader.nextString(); // we retrieve the value of this node as a String
                    else if (subNode.equals(TAG_NAME))
                        name = jsonReader.nextString();
                    else if (subNode.equals(TAG_LIGUE))
                        ligue = jsonReader.nextString();
                        // etc -> keep checking for each single possible value
                        // don't forget to add an else in case of an unexpected node ...
                    else
                        jsonReader.skipValue(); // ... that we can safely skip

                    jsonReader.endObject(); //once we are over with this object, we close it
                }
                jsonReader.endArray(); // never forget to close the array
            }

            // Once done parsing through current club :
            final HashMap<String, String> currentClub = new HashMap<>();
            // put values here
            currentClub.put(TAG_ID, id);
            currentClub.put(TAG_ID, name);
            currentClub.put(TAG_ID, ligue);
            allClubs.add(currentClub);
        }
        jsonReader.endObject(); // never forget to close an object

        // Once you are done with parsing the json you can build your return your ArrayList of HasMap here

        // Exception Catching requiered
    } catch (final UnsupportedEncodingException uee) { // in case json.getBytes fails
        Log.e(TAG, "Error while parsing JSON - Wrong Encoding! ->\n" + uee.getMessage());
        Log.getStackTraceString(uee);
        return null;
    } catch (final IOException ioe) { // might VERY RARELY occur while reading the current stream.
        Log.e(TAG, "Error while converting from JSON ->\n" + ioe.getMessage());
        return null;
    }
}}

非常感谢!

来自ESIEA的欢呼声

的Jordy