How to get last object from a JSONArray

Issue

I have a listView and I am showing students attendance for each subject, I am parsing JSON till secondlast place for that. For that, in get count I did return attendanceBeanList.size()-1. See below code.
I have done this:

 private List<TotalAttendance_Bean> attendanceBeanList;
 public TotalAttendanceAdapter(Activity activity, List<TotalAttendance_Bean> attendanceBeanList)
{
    super();
    this.activity = activity;
    this.attendanceBeanList = attendanceBeanList;
}

@Override
public int getCount() {
   return attendanceBeanList.size()-1;
}

Now when I am going to get last object I am stuck. I have to get Total attendance for every student. For that I have to get Last Object from below JSONArray.

This is my JSON:

[
  {
    "subject_name": "English-I",
    "total_classes": "2",
    "total_attended": "2",
    "percentage": "100"
  },
  {
    "subject_name": "English-I",
    "total_classes": "2",
    "total_attended": "2",
    "percentage": "100"
  },
  {
      "subject_name": "English-I",
      "total_classes": "2",
      "total_attended": "2",
      "percentage": "100"
  },
  {
     "subject_name": "English-I",
     "total_classes": "2",
     "total_attended": "2",
     "percentage": "100"
 },
  {
      "total_attendance": 90%
  }
]

This is my XML.
In this layout I am showing Every Subject Attendance in List View, and I have to show Total percentage in TextView in Blue Colour.
layout

Solution

You can fetch your total_attendance after parsing all students records

JSONArray obj = new JSONArray(yourStringResponse);

// get the last object
JSONObject tot_obj = obj.getJSONObject(obj.length()-1);

// get String from last object
String tot_str = tot_obj.optString("total_attendance");

Note : optString will convert your data to String otherwise it will give an empty string like "".

Now you can display the data in your Activity‘s TextView like

yourTextView.setText(tot_str);

you can pass your tot_str to Adapter if you need

public TotalAttendanceAdapter(Activity activity
                        , List<TotalAttendance_Bean> attendanceBeanList
                        , String tot)
{
    super();
    this.activity = activity;
    this.attendanceBeanList = attendanceBeanList;
    this.tot = tot;
}

Answered By – Pavneet_Singh

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published