/**
*
* @param jsonArr = Input your json array
* @param sortBy = column name which needs to sort
* @return required sorted jsonarray
*/
public static JSONArray sortArray(JSONArray jsonArr, final String sortBy) {
JSONArray sortedJsonArray = new JSONArray();
try {
List < JSONObject > jsonValues = new ArrayList < JSONObject > ();
for (int i = 0; i < jsonArr.length(); i++) {
jsonValues.add(jsonArr.getJSONObject(i));
}
Collections.sort(jsonValues, new Comparator < JSONObject > () {
@Override
public int compare(JSONObject a, JSONObject b) {
String valA = new String();
String valB = new String();
try {
valA = (String) a.get(sortBy);
valB = (String) b.get(sortBy);
} catch (JSONException e) {
//do something
}
return valA.compareTo(valB);
//if you want to change the sort order, simply use the following:
//return -valA.compareTo(valB);
}
});
for (int i = 0; i < jsonArr.length(); i++) {
sortedJsonArray.put(jsonValues.get(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
return sortedJsonArray;
}
Hello everyone, The purpose of this blog is to give you all kind of technical support in simple manner. Find latest technology support every time so as to keep you updated on daily basis. Exact source code snippet will help you understand more and integrate same in difficult situation. Note: Blog is maintained by Nikhil Lotke.
Tuesday, January 31, 2017
How to sort JSONArray in Android?
Labels:
android
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment