如何从一个JSONArray获得最后一个对象

如何从一个JSONArray获得最后一个对象

问题描述:

我有一个listView,我为每个主题显示students attendance,我解析JSON,直到secondlast为止。为此,在计数我确实返回attendanceBeanList.size()-1。见下面的代码。 我已经这样做了:如何从一个JSONArray获得最后一个对象

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

现在,当我要得到最后一个对象,我卡住了。我必须为每位学生提供Total考勤。为此,我必须从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。

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

+0

你张贴的JSON是无效的,检查验证程序并更正代码 – OBX

+2

先生我也检查过,它显示“有效的JSON”。我们不能在这个JSON中做什么 –

您可以获取您的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"); 

注后:optString将您的数据转换为String否则会给空string""

现在你可以在你的ActivityTextView

yourTextView.setText(tot_str); 

显示数据,你可以通过你的tot_strAdapter如果你需要

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