Search code examples
javaandroidjsonbubble-sort

How to sort the string ArrayList?


I am parsing the JSON array successfully. But I have a String which has numbers. So I want to sort all the data according to the numbers. I had been checked so many examples but I couldn't implement them in my code.So please help me. Here is my code. here the "count" is the, string threw which I want to sort the data.

a.java

    @Override
    protected Void doInBackground(Void... params) {
        ServiceHandler serviceHandler = new ServiceHandler();
        String jsonStr = serviceHandler.makeServiceCall(
                JSONUrl.categoriesUrl, ServiceHandler.GET);
        Log.d("Response Categories:", ">" + jsonStr);
        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);
                categoriesJSONArray = jsonObj
                        .getJSONArray(JSONUrl.TAG_DATA);

                for (int i = 0; i < categoriesJSONArray.length(); i++) {
                    JSONObject c = categoriesJSONArray.getJSONObject(i);

                    GridViewItem gridCategoriesItem = new GridViewItem();
                    gridCategoriesItem.setSlug(c
                            .getString(JSONUrl.TAG_CATEGORIES_SLUG));
                    gridCategoriesItem.setImage(c
                            .getString(JSONUrl.TAG_CATEGORIES_IMAGE));
                    gridCategoriesItem.setCount(c
                            .getString(JSONUrl.TAG_CATEGORIES_COUNT));

                    mGridArrayCategories.add(gridCategoriesItem);

                    }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.d("ServiceHandler", "Couldn't get any data from the url");
        }
        return null;
    }

GridViewItem.java

public class GridViewItem {
String image;
String slug;
String count;
String name;

public GridViewItem() {
    super();
}

public GridViewItem(String image, String slug, String count,
        String name) {
    super();
    this.image = image;
    this.slug = slug;
    this.count = count;
    this.name = name;
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

public String getSlug() {
    return slug;
}

public void setSlug(String slug) {
    this.slug = slug;
}

public String getCount() {
    return count;
}

public void setCount(String count) {
    this.count = count;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}
}

Solution

  • You can use Collection.sort().

    for sorting any kind of ArrayLsit Object.

     Collections.sort(listOfStringArrays,new Comparator<String[]>() {
                public int compare(String[] strings, String[] otherStrings) {
                    return strings[1].compareTo(otherStrings[1]);
                }
            });