As addition to my comment and answer of @Kushal here is a way how to calculate total time. I skip the way to get JSONObject
, because it described already and give an example with given String[]
which you get while parsing JSON
. In this example I made ALL of possible scenarios with given response, so you may use it without modifying:
String[] timeItems = {"4 days 1 hour 12 mins", "5 hours 9 mins"}; // as example for visibility
int[] total = {0, 0, 0}; // days, hours, minutes
for(int i = 0; i < timeItems.length; i++){
if(timeItems[i].contains("day ")){
total[0]++;
}else if(timeItems[i].contains("days")){
total[0] += Integer.valueOf(timeItems[i].substring(0, timeItems[i].indexOf(" days")));
}
if(timeItems[i].contains("hour ")){
total[1]++;
}else if(timeItems[i].contains("hours")){
if(timeItems[i].indexOf(" hours") <= 3){
total[1] += Integer.valueOf(timeItems[i].substring(0, timeItems[i].indexOf(" hours")));
}else{
if(timeItems[i].contains("days")){
total[1] += Integer.valueOf(timeItems[i].substring(timeItems[i].lastIndexOf("days ")) + 5, timeItems[i].indexOf(" hours"));
}else{
total[1] += Integer.valueOf(timeItems[i].substring(timeItems[i].lastIndexOf("day ")) + 4, timeItems[i].indexOf(" hours"));
}
}
}
if(timeItems[i].contains("min ")){
total[2]++;
}else if(timeItems[i].contains("mins")){
if(timeItems[i].indexOf(" mins") <= 3){
total[2] += Integer.valueOf(timeItems[i].substring(0, timeItems[i].indexOf(" mins")));
}else{
if(timeItems[i].contains("hours")){
total[2] += Integer.valueOf(timeItems[i].substring(timeItems[i].indexOf("hours ") + 6, timeItems[i].indexOf(" mins")));
}else{
total[2] += Integer.valueOf(timeItems[i].substring(timeItems[i].indexOf("hour ") + 5, timeItems[i].indexOf(" mins")));
}
}
}
}
Log.d("LOG", total[0] + " days " + total[1] + " hours " + total[2] + " mins.");
This got to be a little bit more complex than I thought, maybe it is possible to simplify somehow or use similar ideas, but the main point is to show you working example. I debugged this code. It gives correct output:
05-19 23:00:38.687 14251-14251/whatever.com.myapplication D/LOG﹕ 4 days 6 hours 21 mins.
I hope this is helpful.
Let me know if it either fits you or not.