0

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);

This is my json response:

{"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"
    }]
}

I get the alergenos data correctly, like this:

JSONArray jArray = respJSON.getJSONArray("alergenos");

for (int n = 0; n < 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);

This is my adapter:

 class AlergProdAdapter extends BaseAdapter {

private final Activity activity;
private final JSONArray jsonArray;
final static ArrayList<AlergenosProducto> alergProd = new ArrayList<AlergenosProducto>();

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 < 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;
}

Does anyone have a clue on how can i solve this?

Thank you!

EDIT:

Added log cat.

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)

Edited to add the hole asynctask:

 public class algResultados extends AsyncTask<Void, Void, String> {

    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<AlergenosProducto> objList = new ArrayList<AlergenosProducto>();

            for (int i = 0; i < 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 < 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<AlergenosProducto> alergenos = AlergProdAdapter.alergProd;


        } catch (JSONException e) {
            Log.i("EX", e.toString());
            alert("Ups!",
                    "Lo sentimos, pero no estás registrado como usuario");
        }
    }
}
4
  • listview.setAdapter(jSONAdapter); Commented Sep 4, 2013 at 22:34
  • logcat says you're passing a null there ? Commented Sep 4, 2013 at 22:36
  • Yes! and I don't know what else to try, I don't know if I'm doing AlergProdAdapter or jArray wrong O.o Commented Sep 4, 2013 at 23:02
  • The code you have posted has nothing to do with the error you posted - there is not a single async task reference in the given code. post the async task code. Post the code you have in sub class algResultados which is located in class Scan_Result, on line 230 Commented Sep 5, 2013 at 8:55

2 Answers 2

2

good that you did it by yourself.... :)

Sign up to request clarification or add additional context in comments.

2 Comments

This is a comment, isn't it?
yes....i wanted to appreciate him..i wasnt able to comment, so i posted it as an answer
0

I solved it by changing the following lines into my adapter, from this:

@Override
public long getItemId(int position) {
   JSONObject jsonObject = getItem(position);

   return jsonObject.optLong("id");
}

to this:

 @Override
 public long getItemId(int position) {
    return position;
 }

Thanks anyway! :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.