RSS

How to sort JSONArray in Android?

22 Sep
/**
	 * 
	 * @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;
	}
Advertisements
 
Leave a comment

Posted by on September 22, 2015 in Android Source Code

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: