1

I am new. I'm trying to sorting the data that I get from json parse,but nothing work. Not even an error. I try How to Sort JSON Array from JSON Objects in Android?

I don't know what's wrong with my code, because there's no error. But there's a warning "Implicitly using the default locale is common source of bugs: Use toLowerCase(Locale) instead" on here

return (lhs.getString("item_name").toLowerCase().compareTo(rhs.getString("item_name").toLowerCase()));

Is there anyone can help me to solve this problem?

Here's my java code

    @Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

        Log.d("Response: ", "> " + jsonStr);

        if (jsonStr != null) {
            try {
                ArrayList<JSONObject> array = new ArrayList<JSONObject>();
                JSONArray jsonArray = new JSONArray();

                // looping through All Contacts
                for (int i = 0; i < foods.length(); i++) {
                    try {
                    JSONObject c = foods.getJSONObject(i);

                    if(c.getString("category_id").equals("1")) {
                        // Adding to array. Only items with category_id = 1 will be sorted.
                        array.add(foods.getJSONObject(i));  // This line is important

                        String item_id = c.getString(TAG_ITEM_ID);

                        // tmp hashmap for single contact
                        HashMap<String, String> contact = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        contact.put(TAG_ITEM_ID, item_id);  

                        // adding contact to contact list
                        foodslist.add(contact);

                    }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
                Collections.sort(array, new Comparator<JSONObject>() {

                    @Override
                    public int compare(JSONObject lhs, JSONObject rhs) {
                        // TODO Auto-generated method stub

                        try {
                            return (lhs.getString("Name").toLowerCase(Locale.getDefault()).compareTo(rhs.getString("Name").toLowerCase(Locale.getDefault())));
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            return 0;
                        }
                    }
                });
            }
          }      
        else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        return null;
    }

And here's my Json data

[{"id":"201","category_id":"0","category_name":null,"item_name":"","description":"","address":"","area":""}

Thanks before.

Community
  • 1
  • 1
Matthew
  • 95
  • 4
  • 14
  • That is just a warning. You can use @suppresswarnings to avoid it if you feel uncomfortable, provided your app is not meant for multi languages – ngrashia Jul 23 '14 at 03:40

2 Answers2

0

That is just a warning.

  1. You can use @SuppressWarnings to avoid it if you feel uncomfortable, provided your app is not meant for multi languages OR

  2. You can use : toLowerCase(Locale.getDefault()); to avoid this warning. Make sure to import import java.util.Locale;


EDIT

Hope below code will help you:

ArrayList<JSONObject> array = new ArrayList<JSONObject>();
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < jsonArray.length(); i++) {
    try {
     JSONObject c = jsonArray.getJSONObject(i);
    if(c.getString("category_id").equals("1")
    {
         // Adding to array. Only items with category_id = 1 will be sorted.
         array.add(jsonArray.getJSONObject(i));  // This line is important

         // All other stuff here.....
          String item_id = c.getString(TAG_ITEM_ID);
                        // tmp hashmap for single contact
                        HashMap<String, String> contact = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        contact.put(TAG_ITEM_ID, item_id);
                        // adding contact to contact list
                        foodslist.add(contact);
    }


    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Collections.sort(array, new Comparator<JSONObject>() {

    @Override
    public int compare(JSONObject lhs, JSONObject rhs) {
        // TODO Auto-generated method stub

        try {
            return (lhs.getString("Name").toLowerCase(Locale.getDefault()).compareTo(rhs.getString("Name").toLowerCase(Locale.getDefault())));
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return 0;
        }
    }
});

EDIT AGAIN

if (jsonStr != null) {
                try {
                    ArrayList<JSONObject> array = new ArrayList<JSONObject>();
                    JSONArray jsonArray = new JSONArray();

                    // looping through All Contacts
                    for (int i = 0; i < foods.length(); i++) 
                    {
                        try {
                        JSONObject c = foods.getJSONObject(i);

                        if(c.getString("category_id").equals("1")) {
                            // Adding to array. Only items with category_id = 1 will be sorted.
                            array.add(foods.getJSONObject(i));  // This line is important

                            String item_id = c.getString(TAG_ITEM_ID);

                            // tmp hashmap for single contact
                            HashMap<String, String> contact = new HashMap<String, String>();

                            // adding each child node to HashMap key => value
                            contact.put(TAG_ITEM_ID, item_id);  

                            // adding contact to contact list
                            foodslist.add(contact);
                        } // End of if c.getstring

                        } // End of inner try
                        catch (JSONException e) {
                            e.printStackTrace();
                        } // End of inner catch
                     } // End of for loop
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                    Collections.sort(array, new Comparator<JSONObject>() {

                        @Override
                        public int compare(JSONObject lhs, JSONObject rhs) {
                            // TODO Auto-generated method stub

                            try {
                                return (lhs.getString("Name").toLowerCase(Locale.getDefault()).compareTo(rhs.getString("Name").toLowerCase(Locale.getDefault())));
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                                return 0;
                            }
                        }
                    });

            } // End  of if jsonstr
            else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return null;
ngrashia
  • 9,869
  • 5
  • 43
  • 58
  • thanks, but do you know why the sorting is not working? – Matthew Jul 23 '14 at 03:43
  • Its because your code is not the same as the source you are trying with. You have declared `array`, but not assigned any value to it anywhere in your code. – ngrashia Jul 23 '14 at 03:47
  • In the original post, note the line `array.add(jsonArray.getJSONObject(i));` This is necessary for sorting. In your code, this line is missing. – ngrashia Jul 23 '14 at 03:48
  • i'm trying to do what you said, but there's an error "array cannot be resolved to a variable. – Matthew Jul 23 '14 at 04:49
  • Sorry, I forget to add add try { on my code :D But the ask me to add "finally" to complete blockstatements. – Matthew Jul 23 '14 at 05:09
  • What finally? The usual construct for finally is `try - catch - finally`. But in your case, I don't think it is necessary! Finally related docs are here : – ngrashia Jul 23 '14 at 05:17
  • You can check it on my question.I already edit my code. The error is on "}" right before the last else – Matthew Jul 23 '14 at 05:29
  • @Matthew: Refer edit again section. The braces are not closed properly. I have commented against each close brace for your understanding. – ngrashia Jul 23 '14 at 05:40
  • Ok, I try the code that you gave. and there's a new error "array cannot be resolved" in this line Collections.sort(array, new Comparator() {. I think because its not in if statement – Matthew Jul 23 '14 at 06:14
  • i am trying to add catch before else statement. } catch (JSONException e) { e.printStackTrace(); } } else { Log.e("ServiceHandler", "Couldn't get any data from the url"); } And I got error "Unreachable catch block for JSONException. It suggest to remove it, but when I remove it, I got an error on log cat. – Matthew Jul 23 '14 at 06:21
  • Did you try the code i have provided in EDIT AGAIN section? The open and close braces are correct in that section. If you want, try changing the `JSONException e` to only `Exception e` – ngrashia Jul 23 '14 at 06:35
  • Yes, i already try it and I got two errors. First on this line Collections.sort(array, new Comparator() {. It said "array cannot be resolved to a variable". Second on else line. "Sintax error, { expected" – Matthew Jul 23 '14 at 06:49
  • @Matthew: I get it, the collections.sort should be inside the if part. I have re-edited my answer in the edit again part. Check now. – ngrashia Jul 23 '14 at 06:55
  • I don't get it why, Its looks perfect but still there is an error about that array variable. Its gone if I put the collection.sort inside the outer try part. But it'll show another error on JSONException. – Matthew Jul 23 '14 at 07:11
  • @Matthew: You seem to have a very basic issue. Note: Any if should have a corresponding else and any try should have a corresponding catch. Please go thru basic java documentations to sort this error! – ngrashia Jul 23 '14 at 07:24
  • Once solved, accept as answer for the time spent and answer provided! – ngrashia Jul 23 '14 at 07:24
0

Instead of using

.toLowerCase().

change it like this

.toLowerCase(Locale.getDefault())

It will help.

and also check for Null in variables and >0 check for arrays.

Arun Anand
  • 11
  • 4