我有一个 listView
,我正在显示每个科目的 students attendance
,我正在解析 JSON
直到 secondlast
那个地方。为此,在 get count 中我确实返回了 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;
}
现在,当我要获取最后一个对象时,我被卡住了。我必须得到每个学生的总出勤率。为此,我必须从 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%
}
]
这是我的 XML。 在此布局中,我在 ListView 中显示每个主题出勤率,并且我必须在 TextView 中以蓝色显示总百分比。
最佳答案
解析所有students
记录后,您可以获取您的total_attendance
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");
注意:optString
会将您的数据转换为String
,否则它会给出一个空的string
,如""
.
现在您可以在Activity
的TextView
中显示数据
yourTextView.setText(tot_str);
如果需要,您可以将tot_str
传递给Adapter
public TotalAttendanceAdapter(Activity activity
, List<TotalAttendance_Bean> attendanceBeanList
, String tot)
{
super();
this.activity = activity;
this.attendanceBeanList = attendanceBeanList;
this.tot = tot;
}
关于java - 如何从 JSONArray 中获取最后一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42037254/