如何在listview中显示JSON对象?

时间:2016-03-08 07:03:32

标签: android json listview

主要课程 使用volley库从URL获取JSON数据。

   public class MyActivity extends Activity {   

ListView listView;
List<Details> rowItems;

RequestQueue requestQueue;

 @Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.details2);
    url = getIntent().getStringExtra("key");
    if(savedInstanceState!=null){
        Log.d("STATE",savedInstanceState.toString());
    }


    requestQueue = Volley.newRequestQueue(this);

    JsonObjectRequest jor = new  JsonObjectRequest(url, null,
            new Response.Listener<JSONObject>()  {
                @Override
                public void onResponse(JSONObject response) {

                    try {


                        JSONArray ja = response.getJSONArray("results");

                        ArrayList<Details> myModelList = new     ArrayList<Details>();
                        Details mymodel = null;
                        for (int i = 0; i < ja.length(); i++) {

                            JSONObject jsonObject = ja.getJSONObject(i);
                            mymodel = new Details();
                            mymodel.id = Integer.parseInt(jsonObject.optString("id").toString());
                            mymodel.url = jsonObject.getString("resLink");
                            mymodel.resType = jsonObject.getString("resType");
                            mymodel.name = jsonObject.getString("resName");

                            myModelList.add(mymodel);
                              setData();
                        }


                    }catch(JSONException e){e.printStackTrace();}
                }

            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("Volley","Error");

                }
            }
    );
    requestQueue.add(jor);
}

private void setData() {

    listView = (ListView) findViewById(R.id.list);
    CustomListViewAdapter adapter = new CustomListViewAdapter(this,
            R.layout.list_item, rowItems);
    listView.setAdapter(adapter);
    //listView.setOnItemClickListener(this);
}



@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

我的CustomListViewAdapter claas位于

之下
 public class CustomListViewAdapter extends ArrayAdapter<Details> {

Context context;

public CustomListViewAdapter(Context context, int resourceId,
                             List<Details> items) {
    super(context, resourceId, items);
    this.context = context;
}

/*private view holder class*/
private class ViewHolder {

    TextView txtTitle;
    TextView txtDesc;
}

public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder = null;
    Details rowItem = getItem(position);

    LayoutInflater mInflater = (LayoutInflater) context
            .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.list_item, null);
        holder = new ViewHolder();
        holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
        holder.txtTitle = (TextView) convertView.findViewById(R.id.title);

        convertView.setTag(holder);
    } else
        holder = (ViewHolder) convertView.getTag();

    holder.txtDesc.setText(rowItem.getResType());
    holder.txtTitle.setText(rowItem.getName());

    return convertView;
}

我的详细信息课程            公共类详细信息扩展结果{

String name;
String resType;
String url;
int id;
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getResType() {
    return resType;
}
public void setResType(String resType) {
    this.resType = resType;
}
public String getUrl() {
    return url;
}
public void setUrl(String url) {
    this.url = url;
}

*想要显示我在列表视图中收到的数据*

我的XML

    <ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    />

list_item.xml

       <LinearLayout       xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">


<TextView
    android:id="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toRightOf="@+id/icon"
    android:paddingBottom="10dp"
    android:textColor="#CC0033"
    android:textSize="16dp" />

<TextView
    android:id="@+id/desc"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/title"
    android:layout_toRightOf="@+id/icon"
    android:paddingLeft="10dp"
    android:textColor="#3399FF"
    android:textSize="14dp" />

4 个答案:

答案 0 :(得分:1)

在适配器类getView()

中使用以下行

Details rowItem = (Details) getItem(position);

而不是

Details rowItem = getItem(position);

答案 1 :(得分:1)

你正在做的一切正确,但没有传递包含数据的myModelList并传递空的rowItems列表。获取所有数据并创建myModelList后,请调用

             setData(myModelList);

并按如下所示更改setData方法

private void setData(List<Details> mList) {
      listView = (ListView) findViewById(R.id.list);
      CustomListViewAdapter adapter = new CustomListViewAdapter(this,
        R.layout.list_item, mList);
      listView.setAdapter(adapter);
}

答案 2 :(得分:1)

更新您的setData方法,因为您没有获得设置数据的列表。

 private void setData(List<Details> list) {
          listView = (ListView) findViewById(R.id.list);
          CustomListViewAdapter adapter = new CustomListViewAdapter(this,
            R.layout.list_item, list);
          listView.setAdapter(adapter);
    }

同时将setData();更改为setData(myModelList);

答案 3 :(得分:1)

在适配器中,您正在使用List rowItems;

因此onResponse方法的代码应如下所示

 JSONArray ja = response.getJSONArray("results");
 rowItems = new     ArrayList<Details>();
 Details mymodel = null;
 for (int i = 0; i < ja.length(); i++) {
    JSONObject jsonObject = ja.getJSONObject(i);
    mymodel = new Details();
    mymodel.id = Integer.parseInt(jsonObject.optString("id").toString());
    mymodel.url = jsonObject.getString("resLink");
    mymodel.resType = jsonObject.getString("resType");
    mymodel.name = jsonObject.getString("resName");
    rowItems.add(mymodel);
    }
    setData();

为了简化json解析,您可以使用Gson库,如此处所述 http://www.mysamplecode.com/2013/07/android-json-stream-data-parsing.html