【问题标题】:Parse JSON data into a ListView将 JSON 数据解析为 ListView
【发布时间】:2016-03-03 18:19:01
【问题描述】:

我知道已经回答了几个类似的问题,但是因为我对 Android 开发非常陌生,所以我无法自己解决这个问题。这个问题是不言自明的。我正在通过 HTTP 请求从数据库中获取数据,并希望将这些数据调整为列表视图。我将 Volley 用于我的 HTTP 请求,下面是我的 onResponse -方法。

其他一切都完美无缺,我只是还没有找到一种方法将这些数据调整到列表视图中。

@Override
public void onResponse(String response) {
    Log.d(TAG, response.toString());
    // If we are getting success from server

    try {
      JSONObject jObject = new JSONObject(response);
      int count = jObject.getInt("count");

      if(count == 0) {
        noEventsTextView.setText(jObject.getString("msg").toString());
        noEventsTextView.setGravity(Gravity.CENTER);
        noEventsImageView.setVisibility(View.VISIBLE);

      } else {
        JSONArray childArray = jObject.getJSONArray("lectures");

        for(int i = 0; i < childArray.length(); i++) {
          JSONObject finalObject = childArray.getJSONObject(i);

          // TODO Adapt data to listView
        }
      }
    } catch(JSONException e) {
      e.printStackTrace();
    }
  }
}

这是我从服务器返回的 JSON 示例:

{
  count: 2,
  msg: "",
lectures: [
  {
    id: "1",
    starting_at: "2015-11-30 13:00:00",
    ending_at: "2015-11-30 15:00:00",
    user_id: "1",
    course: "Course #1",
    user_name: "John Doe"
  },
  {
    id: "2",
    starting_at: "2015-11-30 13:00:00",
    ending_at: "2015-11-30 15:00:00",
    user_id: "1",
    course: "Course #2",
    user_name: "John Doe"
  }
]
}

【问题讨论】:

标签: android json listview android-listview


【解决方案1】:

为 Json 的每个键值对创建一个类,并使用 Jackson 将您的 json 映射到该类,并将该类的通用列表添加到您的 List Adapter 。 喜欢

Custom Class{
    String id;
    String starting_at;
    String ending_at;
    String user_id;
    String course ;
    String username;
}

将您通过 Jackson 的响应映射到 ArrayList 然后 列表适配器(数组列表) https://w2davids.wordpress.com/android-json-parsing-made-easy-using-jackson/

你准备好了......你也可以使用gson,但杰克逊有点快,所以你可以根据你的需要去找任何人......

希望对你有帮助。

【讨论】:

    【解决方案2】:

    Json 的每个键值对创建数组变量。 并将所有这些变量传递给listview。 新Listadapter(this,id[],starting_at[],ending_at[],user_id[],course[],username[]);

    或者有一个概念叫做Gson。 这将允许您在不使用数组的情况下将数据写入Serializable 类。 在将数据分配给这些类之后,您可以将Serializable 类传递给适配器并在适配器getView 方法中使用它。

    我写了一个简单的tutorial 来将数据分配给可序列化的类,认为它会给你一个想法。

    希望对您有所帮助。

    【讨论】:

      【解决方案3】:

      你可以有一个 POJO,它包含一个讲座的所有键。

      DataPOJO.java

      public class DataPOJO {
          private int id;
          private String starting_at;
          private String ending_at;
          private String user_id;
          private String course;
          private String user_name;
      }
      

      在你的 onResponse 中:

      @Override
      public void onResponse(String response) {
          Log.d(TAG, response.toString());
          // If we are getting success from server
      
          try {
            JSONObject jObject = new JSONObject(response);
            int count = jObject.getInt("count");
      
            if(count == 0) {
              noEventsTextView.setText(jObject.getString("msg").toString());
              noEventsTextView.setGravity(Gravity.CENTER);
              noEventsImageView.setVisibility(View.VISIBLE);
      
            } else {
              JSONArray childArray = jObject.getJSONArray("lectures");
              ArrayList<DataPOJO> datas = new ArrayList<DataPOJO>();
              for(int i = 0; i < childArray.length(); i++) {
                JSONObject finalObject = childArray.getJSONObject(i);
                DataPOJO data = new DataPOJO;
                data.id = finalObject.getInt("id");
                data.starting_at = finalObject.getString("starting_at");
      
                //so on
      
                //add data to arraylist......
                datas.add(data);
      
              }
      
              //set adapter of your listview here, you have to have an instance of your list view
             listView.setAdapter(new MyAdapter(datas, context));
            }
          } catch(JSONException e) {
            e.printStackTrace();
           }
        }
      }
      

      MyAdapter.java

      public class MyAdapter extends BaseAdapter {
          private Context mContext;
          private ArrayList<DataPOJO> listItem;
      
          public MyAdapter(Context mContext, ArrayList<DataPOJO> listItem) {
              this.mContext = mContext;
              this.listItem = listItem;
          }
      
          @Override
          public int getCount() {
              return listItem.size();
          }
      
          @Override
          public Object getItem(int position) {
              return listItem.get(position);
          }
      
          @Override
          public long getItemId(int position) {
              return 0;
          }
      
          @Override
          public View getView(final int position, View convertView, ViewGroup parent) {
              if (convertView == null)
                  convertView =   LayoutInflater.from(mContext).inflate(R.layout.list_items, null);
      
                   ((TextView) convertView.findViewById(R.id.name)).setText(listItem.get(position).user_name);
              return convertView;
          }
      }
      

      list_items.xml

      <?xml version="1.0" encoding="utf-8"?>
      <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent">
      
          <TextView android:id="@+id/name"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:gravity="center"
              android:textColor="#000"
              android:textSize="18sp"/>
      
      </RelativeLayout>
      

      【讨论】:

      • 我在 MyAdapter.Java 中收到 Cannot resolve method 'getId()',在 onResponse 中收到 Cannot resolve symbol context,但无法测试这个:/ 有什么想法吗?
      • 没关系,让它工作。谢谢 :) 还有一个问题,我可以为自定义列表视图创建onClickListeneners 吗?点击每门课程后我需要打开一个新的 Intent
      • 在listview上设置适配器后可以使用listView.setOnItemClickListener()
      猜你喜欢
      • 1970-01-01
      • 2020-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-03
      • 1970-01-01
      相关资源
      最近更新 更多