0

我有这个 jsonArray 和一个 jsonArray 有一个 jsonobject(alergenos),我想把它解析成一个 android listview 但是当我尝试 listview.setAdapter(JsonAdapter); 时我总是得到 NullPointerException;

这是我的 json 回复:

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

我正确获得了过敏原数据,如下所示:

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

这是我的适配器:

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

有谁知道我该如何解决这个问题?

谢谢!

编辑:

添加了日志猫。

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)

编辑添加孔异步任务:

 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

2 回答 2

2

很好,你自己做的...... :)

于 2013-09-10T13:32:18.380 回答
0

我通过将以下几行更改为我的适配器来解决它:

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

   return jsonObject.optLong("id");
}

对此:

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

不管怎么说,还是要谢谢你!:)

于 2013-09-05T19:46:59.987 回答