如何从 JSONArray 中获取最后一个对象

Arj*_*ngh 2 java android json loops

我有一个listView,我正在students attendance为每个主题展示,我正在解析JSON直到它的secondlast位置。为此,在 get count 我确实 return attendanceBeanList.size()-1。见下面的代码。我已经这样做了:

 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;
}
Run Code Online (Sandbox Code Playgroud)

现在,当我要获得最后一个对象时,我被卡住了。我必须得到每个学生的总出勤率。为此,我必须从下面获取 Last Object JSONArray

这是我的 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%
  }
]
Run Code Online (Sandbox Code Playgroud)

这是我的 XML。

在这个布局中,我在列表视图中显示每个科目的出勤率,我必须在 TextView 中以蓝色显示总百分比。

Pav*_*ngh 6

您可以total_attendance在解析所有students记录后获取您的

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");
Run Code Online (Sandbox Code Playgroud)

注意:optString将您的数据转换为String否则它会给出一个空的stringlike ""

现在,你可以在你的显示数据ActivityTextView

yourTextView.setText(tot_str);
Run Code Online (Sandbox Code Playgroud)

如果你需要,你可以把你的tot_str传给Adapter

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