Чтение массива JSON в список

Я новичок в разработке Android, и мне нужна помощь.

Я создаю повестку дня, которая загружает информацию из JSON, а затем ListView расширяется с помощью специального адаптера. Я сделал это и работает нормально.

Моя проблема заключается в следующем, когда я нажимаю на контакт, другая активность загружается с дополнительной информацией о пользователе, используя тот же JSON. Я отлаживаю его, и он получает такую ​​​​информацию:

Example Item: [{"id":1,"name":"Leanne Graham","hobby":"Play soccer","address":"Kulas Light, Gwenborough","phone":"1-770-736-8031 x56442"}]

Поскольку я отправил информацию как JSONObject, я преобразовал ее в JSONArray, но когда я передаю этот массив в мой requestComplete, мое приложение прерывается.

Ошибка:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference

/**Основная активность прослушивателя кликов*/

 @Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    System.out.println("POSITION: " + position);
    JSONObject jsonObject = (JSONObject)JSONadapter.getItem(position);


    Intent intent = new Intent(this, InfoActivity.class);
    String pos_json = jsonObject.toString();
    intent.putExtra("pos_json",pos_json);


    startActivity(intent);

}

/**Информационная активность*/

public class InfoActivity extends AppCompatActivity implements JSONRequest.JSONCallback {

AdapterInfo JSONAdapter;
private ListView listInfo;
private JSONObject json_object;
private JSONArray arrayMain;

private ArrayList<String> jsonarray;



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

    JSONArray array = new JSONArray();

    try {
        json_object = new JSONObject(getIntent().getStringExtra("pos_json"));
        arrayMain = array.put(json_object);


        System.out.println("Example Item: "+ arrayMain.toString());
        System.out.println(arrayMain.getClass().getName());
    } catch (JSONException e) {
        e.printStackTrace();
    }
    requestComplete(arrayMain);


    this.listInfo = (ListView) findViewById(R.id.listView2);


}



@Override
public void requestComplete(JSONArray array) {
    JSONAdapter = new AdapterInfo(InfoActivity.this,array);
    this.listInfo.setAdapter(JSONAdapter);


}

/**Адаптер*/

public class AdapterInfo extends BaseAdapter{

private JSONArray array;
private Activity infoAct;

public AdapterInfo(Activity infoAct, JSONArray array){
    this.array = array;
    this.infoAct = infoAct;
}


@Override
public int getCount() {
    if(array == null){
        return 0;
    }else{
        return array.length();
    }
}

@Override
public JSONObject getItem(int position) {
    if(array == null){
        return null;
    }else{
        return array.optJSONObject(position);
    }

}

@Override
public long getItemId(int position) {
    JSONObject object = getItem(position);
    return object.optLong("id");
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if(convertView==null){
        convertView = infoAct.getLayoutInflater().inflate(R.layout.row,null);

    }

    TextView name = (TextView)convertView.findViewById(R.id.infoName);
    TextView hobby = (TextView)convertView.findViewById(R.id.infoHobby);
    TextView address = (TextView)convertView.findViewById(R.id.infoAddress);
    TextView phone = (TextView)convertView.findViewById(R.id.infoPhone);

    JSONObject json_data = getItem(position);
    if(json_data != null){
        try {
            String nombre = json_data.getString("name");
            String pasatiempo = json_data.getString("hobby");
            String direccion = json_data.getString("address");
            String telefono = json_data.getString("phone");

            name.setText(nombre);
            hobby.setText(pasatiempo);
            address.setText(direccion);
            phone.setText(telefono);
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
    return convertView;
}}

/**JSONЗапрос*/

public class JSONRequest extends AsyncTask<String, Void, JSONArray> {

private JSONCallback callback;

public JSONRequest(JSONCallback callback){
    this.callback = callback;
}


@Override
protected JSONArray doInBackground(String... params) {

    URLConnection connection = null;
    BufferedReader br = null;
    JSONArray result = null;

    try{
        URL url = new URL(params[0]);
        connection = (URLConnection) url.openConnection();


        InputStream is = connection.getInputStream();
        br = new BufferedReader(new InputStreamReader(is));
        StringBuilder builder = new StringBuilder();
        String line = "";

        while((line = br.readLine()) != null){

            builder.append(line);
        }

        result = new JSONArray(builder.toString());

    }catch (Exception e) {

        e.printStackTrace();
    } finally {


        try{


            if(br != null) br.close();

        }catch(Exception e) {

            e.printStackTrace();
        }
    }

    return result;
}

@Override
protected void onPostExecute(JSONArray jsonArray) {
    super.onPostExecute(jsonArray);
    callback.requestComplete(jsonArray);
}


public interface JSONCallback{

    void requestComplete(JSONArray array);
}}

person user2737948    schedule 24.03.2016    source источник
comment
Ошибка не имеет ничего общего с JSONObject. Это связано с тем, что объект listInfo имеет значение null, и вы пытаетесь вызвать для него метод. Кроме того, избегайте вызовов System.out на Android; вместо этого используйте журнал.   -  person chRyNaN    schedule 24.03.2016


Ответы (1)


Ваш код:

requestComplete(arrayMain);

this.listInfo = (ListView) findViewById(R.id.listView2);

requestComplete() использует экземпляр this.listInfo, но this.listInfo имеет значение null, поскольку оно установлено после requestComplete(). Поэтому вам нужно переключить их порядок.

this.listInfo = (ListView) findViewById(R.id.listView2);
requestComplete(arrayMain);

Лучше, если вы просто поместите его сразу после вызова setContentView(), просто чтобы убедиться, что this.listInfo содержит действительный экземпляр ListView.

person Zamrony P. Juhara    schedule 24.03.2016