2017-02-04 1019 views
1

我有一個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中做什麼 –

回答

1

您可以獲取您的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; 
} 
相關問題