列表视图帮助 JSON



我有这个JSON数组,当我实现HTTPGET请求时,我会收到它。然后,这将显示在文本视图中,如下所示:

if(inputStream != null) {
            JSONArray reps = new JSONArray(convertInputStreamToString(inputStream));
            for (int i = 0; i < reps.length(); i++) {
                JSONObject item = (JSONObject) reps.get(i);
                result.append("n(" + (i + 1) + ") " + item.get("name") + ":n" + item.get("url") + "n" + "Stars:" + item.get("stargazers_count") + "n" + item.get("forks_count") + "n");
            }

我想在列表视图中查看它,但多次尝试做同样的事情都失败了。我无法为它创建一个可行的适配器,因此非常感谢这方面的帮助。

创建一个非常基本的列表适配器:

public class ListAdapter extends BaseAdapter {
private JSONArray array;
private LayoutInflater inflater;
private ViewHolder holder;
public ListAdapter(Context context, JSONArray array) {
    this.array = array;
    inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
static class ViewHolder {
    private TextView itemTV;
}
public int getCount() {
    return array.length();
}
public JSONObject getItem(int position) {
    try {
        return array.getJSONObject(position);
    } catch (JSONException e) {
        e.printStackTrace();
        return new JSONObject();
    }
}
public long getItemId(int position) {
    return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
    holder = new ViewHolder();
    View view = convertView;
    if (view == null) {
        view = inflater.inflate(R.layout.list_item, null);
        holder.itemTV = (TextView) view.findViewById(R.id.itemTextView);
        view.setTag(holder);
    } else {
        holder = (ViewHolder) view.getTag();
    }
    holder.itemTV.setText(getItem(position).get("name").toString());
    return view;
}

在布局 xml 中,添加列表视图,例如:

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

创建列表项布局文件。对于此示例,我们将创建一个具有一个文本视图的简单布局,并将其另存为"item_layout.xml"...

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/itemTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

在您的活动中,声明您的列表视图和适配器,并在获得 JSON 响应后设置适配器...

private ListAdapter listAdapter;
private ListView listView;
...
listView = (ListView) view.findViewById(R.id.listView);
...
// do whatever you need to get your JSON response, then pass it to your adapter
// JSONArray reps = ....
listAdapter = new ListAdapter(context, reps);
listView.setAdapter(listAdapter);

最新更新