Error showing data from a JSON in a listview

1

I am trying to show a query where I show a JSON of an external database, but when I run the application it does not show me anything.

This is the part of the code where I think the error is:

    @Override
    protected String doInBackground(String... params) {
        return readURL(params[0]);
    }

    @Override
    protected void onPostExecute(String content) {
        try {
            JSONObject jsonObject = new JSONObject(content);
            JSONArray jsonArray =  jsonObject.getJSONArray("products");

            for(int i =0;i<jsonArray.length(); i++){
                JSONObject productObject = jsonArray.getJSONObject(i);
                arrayList.add(new Product(
                        productObject.getString("nombre"),
                        productObject.getString("contenido"),
                        productObject.getString("extra1")
                ));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        CustomListAdapter adapter = new CustomListAdapter(
                getApplicationContext(), R.layout.custom_list_layout, arrayList
        );
        lv.setAdapter(adapter);
    }
}

and these errors are jumping on me

  

W / System.err: org.json.JSONException: Value   [{"nid": "1", "id": "1", "date": "2016-11-02", "name": "IMPROVEMENT OF LIGHTING IN JARDÍN DE EMILIANO ZAPATA.", "lugar": "Emiliano Zapata", "content": "It began with the installation of sodium vapor lamps, for the garden of Emiliano Zapata.", "Extra1": "14876639.jpg"},   {"nid": "2", "id": "2", "date": "2016-11-02", "name": "TERMINATION OF WORKS MUNICIPAL PANTHEON", "place": "La Huerta, Jal . "," content ":" Within the framework of the Day of the Dead celebrations. "," extra1 ":" 14882280.jpg "}]   of type org.json.JSONArray can not be converted to JSONObject

     

W / System.err: at org.json.JSON.typeMismatch (JSON.java:111)

     

W / System.err: at org.json.JSONObject. (JSONObject.java:160)

     

W / System.err: at org.json.JSONObject. (JSONObject.java:173)

     

W / System.err: at mx.gob.lahuerta.listas.MainActivity $ ReadJSON.onPostExecute (MainActivity.java:49)

     

W / System.err: at mx.gob.lahuerta.listas.MainActivity $ ReadJSON.onPostExecute (MainActivity.java:39)

     

W / System.err: at android.os.AsyncTask.finish (AsyncTask.java:667)

     

W / System.err: at android.os.AsyncTask.-wrap1 (AsyncTask.java)

     

W / System.err: at android.os.AsyncTask $ InternalHandler.handleMessage (AsyncTask.java:684)

     

W / System.err: at android.os.Handler.dispatchMessage (Handler.java:102)

     

W / System.err: at android.os.Looper.loop (Looper.java:154)

     

W / System.err: at android.app.ActivityThread.main (ActivityThread.java:6119)

     

W / System.err: at java.lang.reflect.Method.invoke (Native Method)

     

W / System.err: at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run (ZygoteInit.java:886)   W / System.err: at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:776)

Example of the JSON I'm receiving:

[  {"nid":"1","id":"1","fecha":"2016-11-02","nombre":"MEJORAMIENTO DE ALUMBRADO EN JARD\u00cdN DE EMILIANO ZAPATA.","lugar":"Emiliano Zapata","contenido":"Se comenz\u00f3 con la instalaci\u00f3n de lamparas de vapor de sodio, para el jard\u00edn de Emiliano Zapata. Al mismo tiempo, informo el jefe del departamento que en pr\u00f3ximos d\u00edas se comenzar\u00e1 a instalar l\u00e1mparas de alumbrado p\u00fablico en calles, as\u00ed como el pr\u00e9stamo de reflectores para la plaza de toros de la localidad para lucimiento de sus fiestas taurinas tradicionales pr\u00f3ximas a realizar.","extra1":"14876639.jpg"}
 , {"nid":"2","id":"2","fecha":"2016-11-02","nombre":"TERMINACI\u00d3N DE OBRAS PANTE\u00d3N MUNICIPAL","lugar":"La Huerta, Jal.","contenido":"En el marco de las celebraciones del D\u00eda de Muertos en que las familias visitan el Pante\u00f3n Municipal para honrar la memoria de los suyos, el H. Ayuntamiento se dio la tarea de realizar obras de mejoras y conservaci\u00f3n, as\u00ed se culmina con los trabajos de las obra del pante\u00f3n municipal donde se construy\u00f3 puerta de acceso principal en el pante\u00f3n Municipal con un costo de $ 56 mil 615.22 pesos y la obra del descanso donde se realiz\u00f3 una remodelaci\u00f3n integral del \u00e1rea con una inversi\u00f3n de $ 51 mil 569.15 pesos.","extra1":"14882280.jpg"}
]
    
asked by Sharly Infinitywars 26.11.2016 в 00:33
source

2 answers

1

Your response is a JSONArray, change

JSONObject jsonObject = new JSONObject(content);

by:

JSONArray jsonarray = new JSONArray(content);

[Represents an arrangement

{Represents an object

    for(int i=0; i < jsonarray.length(); i++) {
      JSONObject jsonobject = jsonarray.getJSONObject(i);
      String id       = jsonobject.getString("id");
      String title    = jsonobject.getString("title");
      String company  = jsonobject.getString("company");
      String category = jsonobject.getString("category");
    }

Source:

link

I hope it serves you.

Greetings

    
answered by 26.11.2016 / 00:55
source
1

According to your .json file, it's actually a JSONArray :

[{"nid":"1","id":"1","fecha":"2016-11-02","nombre":"MEJORAMIENTO DE ALUMBRADO EN JARD\u00cdN DE EMILIANO ZAPATA.","lugar":"Emiliano Zapata","contenido":"Se comenz\u00f3 con la instalaci\u00f3n de lamparas de vapor de sodio, para el jard\u00edn de Emiliano Zapata. Al mismo tiempo, informo el jefe del departamento que en pr\u00f3ximos d\u00edas se comenzar\u00e1 a instalar l\u00e1mparas de alumbrado p\u00fablico en calles, as\u00ed como el pr\u00e9stamo de reflectores para la plaza de toros de la localidad para lucimiento de sus fiestas taurinas tradicionales pr\u00f3ximas a realizar.","extra1":"14876639.jpg"},{"nid":"2","id":"2","fecha":"2016-11-02","nombre":"TERMINACI\u00d3N DE OBRAS PANTE\u00d3N MUNICIPAL","lugar":"La Huerta, Jal.","contenido":"En el marco de las celebraciones del D\u00eda de Muertos en que las familias visitan el Pante\u00f3n Municipal para honrar la memoria de los suyos, el H. Ayuntamiento se dio la tarea de realizar obras de mejoras y conservaci\u00f3n, as\u00ed se culmina con los trabajos de las obra del pante\u00f3n municipal donde se construy\u00f3 puerta de acceso principal en el pante\u00f3n Municipal con un costo de $ 56 mil 615.22 pesos y la obra del descanso donde se realiz\u00f3 una remodelaci\u00f3n integral del \u00e1rea con una inversi\u00f3n de $ 51 mil 569.15 pesos.","extra1":"14882280.jpg"}]

Review the answer and depending on that remember that the answer .Json can be of two types:

  
  • If the .json starts with {it is considered as Json object.

  •   
  • If the .json starts with [it is considered as Json Arrangement.

  •   

link

therefore this is incorrect:

JSONObject jsonObject = new JSONObject(content);

you should use:

 JSONArray jsonArray = new JSONArray(content);

code:

     // JSONObject jsonObject = new JSONObject(content);
     // JSONArray jsonArray =  jsonObject.getJSONArray("products");
      JSONArray jsonArray = new JSONArray(content);

        for(int i =0;i<jsonArray.length(); i++){
            JSONObject productObject = jsonArray.getJSONObject(i);
            arrayList.add(new Product(
                    productObject.getString("nombre"),
                    productObject.getString("contenido"),
                    productObject.getString("extra1")
            ));
        }
    
answered by 26.11.2016 в 01:29