将JSON数组读取到listview

时间:2016-03-24 00:16:07

标签: android json listview android-adapter

我对Android dev很新,我需要一些帮助。

我正在构建一个从JSON加载信息的议程,然后使用自定义适配器对ListView进行充气。我做到了这一点并且工作得很好。

当我点击一个联系人时,我的问题如下,另一个Activity加载了有关用户的更多信息,使用相同的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

/ **主要活动onclick listener * /

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

/ ** JSONRequest * /

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

1 个答案:

答案 0 :(得分:1)

您的代码:

requestComplete(arrayMain);

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

requestComplete()使用this.listInfo个实例,但this.listInfo为空,因为它是在requestComplete()之后设置的。所以你需要切换他们的订单。

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

最好是在调用setContentView()后立即将其放好,以确保this.listInfo保留有效的ListView个实例。