简体   繁体   中英

Parse JSON data into a ListView

I know that there are several similar questions already answered, but because the fact that I'm very new to Android development, I couldn't figure out how to solve this on my own. The question is pretty self-explanatory. I'm fetching data from the database over HTTP request and want to adapt that data into a listview. I'm using Volley for my HTTP requests and underneath is my onResponse -method.

Everything else works perfectly, I just haven't found a way to adapt that data into a listview.

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

And here's an example of JSON I get back from the server:

{
  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"
  }
]
}

create array Variables for each key value pairs of Json . and pass all those variable to a listview . new Listadapter(this,id[],starting_at[],ending_at[],user_id[],course[],username[]);

or There is a concept called Gson . which will allow you to write data to Serializable class without using array. And after assigning data to these class you can pass the Serializable class to adapter and used it inside adapter getView method.

There is a simple tutorial on this which I wrote to assign data to serializable class, think it will give you an idea.

hope it helps.

Create a class of each key value pairs of Json and the map your json to that class using Jackson and the add generic list of that class to your List Adapter . Like

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

Map your response through Jackson to ArrayList and then ListAdapter(ArrayList) https://w2davids.wordpress.com/android-json-parsing-made-easy-using-jackson/

and you are ready to go.......you can use gson also but jackson is a bit faster so you can go for anyone according to ur need......

hope it helps.

You can have a POJO consisting of all the keys a lecture has.

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

Inside your 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM