0

In my app, the class below receives a JSONArray and use its data to populate a ListView. I want the fields in this ListView to appear in an Alphabetical order. So I want to sort my JSONArray before using its data.

I've saw some topics suggesting to use GSON or Jackson, but I'm trying to do this in a simpler way. I don't understand well these libraries and did't find what I need in their tutorials.

An example of the JSON:

{"0":["1","Alimentos e Bebidas","Y"],"1":["6","Beleza e Cosm\u00e9ticos","Y"],"2":
["11","Cama, Mesa e Banho","Y"],"3":["3","CDs, DVDs e Games","Y"],"4":["2","Convites 
e Cortesias","Y"],"5":["23","Cursos","Y"],"6":["8","Eletr\u00f4nicos","Y"],"7":
["16","Esporte e Lazer","Y"],"8":["14","Inform\u00e1tica e Acess\u00f3rios","Y"],
"9":["10","Limpeza","Y"],"10":["4","Livros","Y"],"11":["21","Livros no Sebo","Y"],
"12":["5","Outros","Y"],"13":["12","Roupas e Acess\u00f3rios","Y"]}

The class' method where I populate the list and wait for user:

public void proccess(){
    listview = (ListView) findViewById(R.id.include3);

    int qtdCategorias = json.length();
    categorias = new String[qtdCategorias];
    itens = new ArrayList<ItemListView>();
    for (int i=0; i<qtdCategorias; i++){
        c = json.optJSONArray(i);
        String nomeCategoria = null;
        try {
            nomeCategoria = c.getString(1); //A consulta SQL do php retorna somente categorias habilitadas
        } catch (JSONException e) {
            Log.e("CategoriasShoppingActivity", e.toString());
            e.printStackTrace();
        }
        categorias[i] = nomeCategoria;
        //ItemListView item = new ItemListView(nomeCategoria);
        //itens.add(item);
    }

    Arrays.sort(categorias);

    for (int i=0; i<qtdCategorias; i++){
        ItemListView item = new ItemListView(categorias[i]);
        itens.add(item);
    }


    adapterListView = new AdapterListView(this, itens);
    listview.setAdapter(adapterListView);


    listview.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v,
                int position, long id) {
            c = json.optJSONArray(position);
            String name = null;
            String idt = null;
            try {
                name = c.getString(1);
                idt = c.getString(0);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            Intent in = new Intent(getApplicationContext(), ProdutosActivity.class);
            in.putExtra(TAG_NAME, name);
            in.putExtra(TAG_ID, idt);
            startActivity(in);
        }
    });




    }

[EDIT] To request data from server, I use this JSONParser class ():

public class JSONParser{

static InputStream is = null;
static JSONArray jArr = null;
static JSONStringer jArrString = null;
static String json = "";
private static Context context;
private ProgressDialog loader;

// static HttpEntity httpEntity = null;

// constructor
public JSONParser() {


}



public JSONArray getJSONFromUrl(String url, List<NameValuePair> params) {

    // Making HTTP request
    try {
        // defaultHttpClient
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));



        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();



        // json = EntityUtils.toString(httpEntity);
        // HttpEntity httpEntity2 = httpEntity;
        json = EntityUtils.toString(httpEntity);
        // is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        Log.e("JSONParser", "IOException "+e.toString());
        e.printStackTrace();
    } 

    try {

        char[] c = new char[json.length()];
        json.getChars(0, json.length(), c, 0);
        int i = 0;
        while (c[i] == '\u00EF' || c[i] == '\u00BB' || c[i] == '\u00BF') { // remove
                                                                            // utf-8
                                                                            // BOM
            i++;
        }
        json = json.substring(i);


        Log.e("JSON", json);
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        JSONObject json_data = new JSONObject(json);
        JSONArray hashMap_names = json_data.names();
        JSONArray hashMap_names2 = new JSONArray();
        Map hashMap = new HashMap(json_data.length());
        for (int i = 0; i != hashMap_names.length(); i++) {
            hashMap.put(String.valueOf(i), json_data.get(String.valueOf(i)));
            hashMap_names2.put(String.valueOf(i));
        }
        JSONObject hashMap_obj = new JSONObject(hashMap);

        jArr = hashMap_obj.toJSONArray(hashMap_names2);

        // jArr = new JSONArray(json);
        Log.e("JSON Parser", "succesful parsing data " + jArr.toString());
    } catch (Exception e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
        jArr = null;
    }

    // return JSON String
    return jArr;

}

And here I receive the JSON in my class

protected void onActivityResult(int requestCode, int resultCode, Intent data){
    if (requestCode == 1){
        if (resultCode == RESULT_OK){
            try {
                json = new JSONArray(data.getStringExtra(TAG_JSON));
                Log.e("CategoriasShoppingActivity", "JSON: "+json);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            proccess();
        }else{ // resultCode == RESULT_CANCELED
            Log.d("CategoriasJogarActivity", "AsyncTaskActicity retornou RESULT_CANCELED");
            finish();
        }
    }
}
Lucas Jota
  • 1,863
  • 4
  • 24
  • 43

2 Answers2

1

If you have access to server-side code, it will be easier to sort the list there. If not, your only way to do so, is to parse it to ArrayList and simply sort it using any known algorithm.

Michal
  • 15,429
  • 10
  • 73
  • 104
  • But im my sql query on server I already have a "order by: description"... I guess JSON doesn't guarantees the order of its elements, and that's why I receive it out of order in my app. Ma I wrong about that? – Lucas Jota Sep 11 '12 at 15:54
  • @Lucas Jota: JSON array is surely sorted, like any other array (in any sane language). What's not sorted are the items in your object. You may be right that there's no such guarantee. In your code I can't see how you generated it... can't you write a short self-contained example? – maaartinus Sep 11 '12 at 16:06
  • I've edited my questions with more code, maybe now it's more clear – Lucas Jota Sep 11 '12 at 16:43
0

Why don't you sort it before serializing ? Use Comparator interface and sort it using Collections.sort. Pass the comparator as as the parameter when sorting

Chris
  • 5,584
  • 9
  • 40
  • 58
  • I've saw some topics that suggests this approach ( http://stackoverflow.com/questions/4277715/how-to-sort-json-object-in-java http://stackoverflow.com/questions/11121570/how-can-i-sort-nested-json-array ) But I could't understand their code. Could you show me an example of how to use the Collections? – Lucas Jota Sep 11 '12 at 15:59
  • I've edited my questions with more code, maybe now it's more clear – Lucas Jota Sep 11 '12 at 16:37
  • 1
    Look at section 4 of http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/ – Chris Sep 11 '12 at 17:26