Note that there are some explanatory texts on larger screens.

plurals
  1. PODisplay a JSONArray with a JSONObject inside into an Android listview
    primarykey
    data
    text
    <p>I have this this jsonArray with a jsonArray that has a jsonobject (alergenos) and I want to parse it into an android listview but I always get NullPointerException when I try listview.setAdapter(JsonAdapter);</p> <p>This is my json response:</p> <pre><code>{"valor": [{ "barcode":"8416400610992", "nombre":"Chicles Trident", "foto":"alood-52224273e4b90-foto1.jpg", "revision":{ "date":"2013-08-31 21:22:27","timezone_type":3,"timezone":"Europe\/Paris"}, "alergenos":[ {"id":4,"alergeno":"Melocoton","valor":0}, {"id":3,"alergeno":"Cacahuetes","valor":1} ], "calorias":250, "puntos":0, "fabricante":"Sonia" }] } </code></pre> <p>I get the alergenos data correctly, like this:</p> <pre><code>JSONArray jArray = respJSON.getJSONArray("alergenos"); for (int n = 0; n &lt; jArray.length(); n++) { JSONObject str_value = jArray.getJSONObject(n); String id = str_value.getString("id"); String name = str_value.getString("alergeno"); int value = str_value.getInt("valor"); } AlergProdAdapter jSONAdapter = new AlergProdAdapter(Scan_Result.this, jArray); listview.setAdapter(jSONAdapter); </code></pre> <p>This is my adapter:</p> <pre><code> class AlergProdAdapter extends BaseAdapter { private final Activity activity; private final JSONArray jsonArray; final static ArrayList&lt;AlergenosProducto&gt; alergProd = new ArrayList&lt;AlergenosProducto&gt;(); AlergProdAdapter(Activity activity, JSONArray jsonArray) { assert activity != null; assert jsonArray != null; this.jsonArray = jsonArray; this.activity = activity; String name = null; int value = 0; String id = null; String image = null; for (int position = 0; position &lt; jsonArray.length(); position++) { JSONObject json_data = getItem(position); if (null != json_data) { try { id = json_data.getString("id"); Log.i("da", id); name = json_data.getString("alergeno"); Log.i("da", name); value = json_data.getInt("valor"); if(value == 1){ image = "imagenroja"; }else{ image = "imagenverde"; } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } AlergenosProducto alerg = new AlergenosProducto(id, name, value); alergProd.add(alerg); } } @Override public int getCount() { if (null == jsonArray) return 0; else return jsonArray.length(); } @Override public JSONObject getItem(int position) { if (null == jsonArray) return null; else return jsonArray.optJSONObject(position); } @Override public long getItemId(int position) { JSONObject jsonObject = getItem(position); return jsonObject.optLong("id"); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) convertView = activity.getLayoutInflater().inflate( R.layout.allergy_listitems, null); TextView text = (TextView) convertView.findViewById(R.id.secondLine); text.setText(alergProd.get(position).getAlergeno()); Log.i("value", alergProd.get(position).getAlergeno()); return convertView; } </code></pre> <p>Does anyone have a clue on how can i solve this?</p> <p>Thank you!</p> <p>EDIT:</p> <p>Added log cat.</p> <pre><code>09-05 00:23:18.217: E/AndroidRuntime(26828): FATAL EXCEPTION: main 09-05 00:23:18.217: E/AndroidRuntime(26828): java.lang.NullPointerException 09-05 00:23:18.217: E/AndroidRuntime(26828): at com.example.alood.Scan_Result$algResultados.onPostExecute(Scan_Result.java:230) 09-05 00:23:18.217: E/AndroidRuntime(26828): at com.example.alood.Scan_Result$algResultados.onPostExecute(Scan_Result.java:1) 09-05 00:23:18.217: E/AndroidRuntime(26828): at android.os.AsyncTask.finish(AsyncTask.java:631) 09-05 00:23:18.217: E/AndroidRuntime(26828): at android.os.AsyncTask.access$600(AsyncTask.java:177) 09-05 00:23:18.217: E/AndroidRuntime(26828): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644) 09-05 00:23:18.217: E/AndroidRuntime(26828): at android.os.Handler.dispatchMessage(Handler.java:99) 09-05 00:23:18.217: E/AndroidRuntime(26828): at android.os.Looper.loop(Looper.java:137) 09-05 00:23:18.217: E/AndroidRuntime(26828): at android.app.ActivityThread.main(ActivityThread.java:4898) 09-05 00:23:18.217: E/AndroidRuntime(26828): at java.lang.reflect.Method.invokeNative(Native Method) 09-05 00:23:18.217: E/AndroidRuntime(26828): at java.lang.reflect.Method.invoke(Method.java:511) 09-05 00:23:18.217: E/AndroidRuntime(26828): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006) 09-05 00:23:18.217: E/AndroidRuntime(26828): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773) 09-05 00:23:18.217: E/AndroidRuntime(26828): at dalvik.system.NativeStart.main(Native Method) </code></pre> <p>Edited to add the hole asynctask:</p> <pre><code> public class algResultados extends AsyncTask&lt;Void, Void, String&gt; { HttpResponse response; BufferedReader reader; StringBuilder builder; String barcode; public algResultados(String data) { super(); this.barcode = data; } @Override protected String doInBackground(Void... arg0) { HttpClient httpClient = new DefaultHttpClient(); String logusuario = SaveSharedPreference .getUserName(getApplicationContext()); String logpass = SaveSharedPreference .getPassword(getApplicationContext()); // Petition get HttpGet httpGet = new HttpGet("http://www.alood.es/api/resultado/" + barcode + '/'); httpGet.addHeader(BasicScheme.authenticate( new UsernamePasswordCredentials(logusuario, logpass), "UTF-8", false)); // Execute Get and get Response response = null; try { response = httpClient.execute(httpGet); reader = new BufferedReader(new InputStreamReader(response .getEntity().getContent(), "UTF-8")); builder = new StringBuilder(); for (String line = null; (line = reader.readLine()) != null;) { builder.append(line).append("\n"); } } catch (Exception e) { e.printStackTrace(); alert("Error de protocolo", "Lo sentimos, ha ocurrido un error"); } // Return code (exit, fail, error, etc) return builder.toString(); } @Override protected void onPostExecute(String result) { String nombre = null; String fabricante = null; String barcode = null; String calorias = null; String fech = null; JSONArray jArray = null; Log.i("GET RESPONSE", "POSTTTTT"); Log.i("GET RESPONSE", result); JSONTokener tokener = new JSONTokener(result); try { String cca = ((JSONObject) tokener.nextValue()) .getString("valor"); Log.i("GET CCA", cca); JSONArray resparray = new JSONArray(cca); List&lt;AlergenosProducto&gt; objList = new ArrayList&lt;AlergenosProducto&gt;(); for (int i = 0; i &lt; resparray.length(); i++) { JSONObject respJSON = resparray.getJSONObject(i); nombre = respJSON.getString("nombre"); fabricante = respJSON.getString("fabricante"); String foto = respJSON.getString("foto"); calorias = respJSON.getString("calorias"); int puntos = respJSON.getInt("calorias"); barcode = respJSON.getString("barcode"); String fecha = respJSON.getJSONObject("revision").getString("date"); fech = fecha.substring(0, 10); jArray = respJSON.getJSONArray("alergenos"); for (int n = 0; n &lt; jArray.length(); n++) { JSONObject str_value = jArray.getJSONObject(n); String id = str_value.getString("id"); String name = str_value.getString("alergeno"); int value = str_value.getInt("valor"); Log.i("GET CCA", id); AlergenosProducto setAlerg = new AlergenosProducto(id, name, value); objList.add(setAlerg); } } TextView nombText = (TextView) findViewById(R.id.titleTxt); nombText.setText(nombre); TextView fabText = (TextView) findViewById(R.id.fabricanteTxt); fabText.setText("Fabricante: " + fabricante); TextView codText = (TextView) findViewById(R.id.codigoTxt); codText.setText("Código: " + barcode); TextView calText = (TextView) findViewById(R.id.caloriasTxt); calText.setText("Calorías: " + calorias + "Kcal"); TextView revisText = (TextView) findViewById(R.id.revisadoTxt); revisText.setText("Revisado: " + fech); listview = (ListView) findViewById(R.id.alProdList); AlergProdAdapter jSONAdapter = new AlergProdAdapter(Scan_Result.this, jArray); listview.setAdapter(jSONAdapter); //ArrayList&lt;AlergenosProducto&gt; alergenos = AlergProdAdapter.alergProd; } catch (JSONException e) { Log.i("EX", e.toString()); alert("Ups!", "Lo sentimos, pero no estás registrado como usuario"); } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload