简体   繁体   中英

How to sort groups and children Expandable listview in Android?

I have two tables in mysql which bind 'Categories' and 'products' through ids 'id_catprods' and 'ID_Cat'. So far so good, I'm working on Android with "ExpandableListView" with a custom adapter and everything works fine but can not find the solution to sort the categories with their products. Can anyone help me?

Json results:

{
"productos": [{
    "id_catprods": "1",
    "id_oferta": "197",
    "id_producto": "1",
    "nombr_cat": "Bocatas",
    "id_cat": "1",
    "nombre_producto": "Lomo",
    "precio": "4",
    "actions": []
}, {
    "id_catprods": "2",
    "id_oferta": "197",
    "id_producto": "2",
    "nombr_cat": "Pizzas",
    "id_cat": "2",
    "nombre_producto": "Serranito",
    "precio": "4",
    "actions": []
}],
"errorCode": 0,
"errorString": "Todo correcto"
}

Main code:

// DownloadJSON AsyncTask
        private class DownloadJSON extends AsyncTask<Void, Void, Void> {
            String givemeurl;

            public DownloadJSON(String url) {
                this.givemeurl = id_oferta;
            }


            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                mProgressDialog = new ProgressDialog(Category.this);
                mProgressDialog.setMessage("Cargando...");
                mProgressDialog.setIndeterminate(false);
                mProgressDialog.show();
            }

            @Override
            protected Void doInBackground(Void... params) {
                // Create an array
                arraylist = new ArrayList<HashMap<String, String>>();
                // Retrieve JSON Objects from the given URL address
                jsonobject = JSONfunctions
                        .getJSONfromURL("http://file.php");

                if(jsonobject != null){         
                    try {
                        // Locate the array name in JSON
                        jsonarray = jsonobject.getJSONArray("productos");

                        for (int i = 0; i < jsonarray.length(); i++) {
                            HashMap<String, String> map = new HashMap<String, String>();
                            jsonobject = jsonarray.getJSONObject(i);
                            // Retrive JSON Objects
                            map.put("nombr_cat", jsonobject.getString("nombr_cat"));
                            map.put("nombre_producto", jsonobject.getString("nombre_producto"));
                            map.put("id_cat", jsonobject.getString("id_cat"));
                            arraylist.add(map);
                        }

                    } catch (JSONException e) {
                        Log.e("Error", e.getMessage());
                        //e.printStackTrace();
                    } catch (Exception e) {
                        Log.e("Error", e.getMessage());         
                    }
                }else{
                    //Log.e("Response","No data");
                }

                return null;
            }

            @Override
            protected void onPostExecute(Void args) {
                ExpandableListView = (ExpandableListView) findViewById(R.id.expandableListView1);

                /*if(listview.getCount() == 0){
                    listview.setVisibility(View.GONE); // ERROR A CORREGIR, DOBLE CAPA?
                    listview.setEmptyView(findViewById(givemeempty));
                    TextView bottom = new TextView(Category.this);
                    bottom.setHeight(50); //50dp
                    bottom.setText("");
                    // Adding bottom
                    listview.addFooterView(bottom);
                }else{
                }*/
                adapter = new ListViewAdapterCat(Category.this, arraylist);
                ExpandableListView.setAdapter(adapter);
                mProgressDialog.dismiss();
            }
        }

Code of Adapter:

 public class ListViewAdapterCat extends BaseExpandableListAdapter {

    Context context;
    ArrayList<HashMap<String, String>> data;
    //ImageLoader imageLoader;
    HashMap<String, String> resultp = new HashMap<String, String>();

    public ListViewAdapterCat(Context context,
            ArrayList<HashMap<String, String>> arraylist) {
        this.context = context;
        data = arraylist;    
        //imageLoader = new ImageLoader(context);
    }

    @Override
    public Object getChild(int arg0, int arg1) {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public long getChildId(int arg0, int arg1) {
        // TODO Auto-generated method stub
        return 0;
    }
    @Override
    public View getChildView(int arg0, int arg1, boolean arg2, View arg3,
            ViewGroup arg4) {   
        TextView tv = null;
        for (int i = 0; i < data.size(); i++) {
            tv = new TextView(context);
            tv.setTextSize(20);
            tv.setPadding(50, 0, 0, 0);
            System.out.println(data.get(i).get("id_cat"));
            if(data.get(i).get("id_cat").equals("1")){
                tv.setText(resultp.get(Category.nombre_producto));
            }else if (data.get(i).get("id_cat").equals("2")){
                tv.setText(resultp.get(Category.nombre_producto));
            }else if (data.get(i).get("id_cat").equals("3")){
                tv.setText(resultp.get(Category.nombre_producto));
            }

        }
        return tv;
    }
    @Override
    public int getChildrenCount(int arg0) {
        // TODO Auto-generated method stub
        return 1;
    }
    @Override
    public Object getGroup(int arg0) {
        // TODO Auto-generated method stub
        return arg0;
    }
    @Override
    public int getGroupCount() {
        // TODO Auto-generated method stub
        return data.size();
    }
    @Override
    public long getGroupId(int arg0) {
        // TODO Auto-generated method stub
        return arg0;
    }
    @Override
    public View getGroupView(int arg3, boolean arg1, View convertView, ViewGroup arg4) {

        ViewHolder holder;
        if(convertView == null){

            LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.category_item, null);

            holder = new ViewHolder();

            holder.nombr_cat = (TextView) convertView.findViewById(R.id.nombree);
            Log.e("ID DEL GRUPO", ""+arg3);
            convertView.setTag(holder);
        }else{
            holder = (ViewHolder) convertView.getTag();
        }

        resultp = data.get(arg3);

        holder.nombr_cat.setText(resultp.get(Category.nombr_cat));
        holder.nombr_cat.setTextSize(20);
        return convertView;
    }
    @Override
    public boolean hasStableIds() {
        // TODO Auto-generated method stub
        return false;
    }
    @Override
    public boolean isChildSelectable(int arg0, int arg1) {
        // TODO Auto-generated method stub
        return true;
    }
    private static class ViewHolder {
        public TextView nombr_cat;
        public TextView nombre_producto;
    }
}

Sort them when querying in MySql if possible. Otherwise, here is one suggestion. Store the categories in a ArrayList<String> . You can easily sort them using one of Collection.sort() . Then, store your products in a Hashtable<String, ArrayList<Product>> where the key is the category name and the data is a Product class that stores your product details. You can sort your Product class using an Comparator<Product> . You will need to modify the adapter accordingly.

Use

 Collections.sort(arraylist); 

or

list.sort(String::compareToIgnoreCase);

This will sort your arraylist and If you have Expandable list you have to use

        Collections.sort(arraylist, new Comparator<Modelclass>(){
            @Override
            public int compare(Modelclass o1, Modelclass o2) {

                Collections.sort(o1.getsubarraylist(), new Comparator<Modelclass>(){
                    @Override
                    public int compare(Modelclass o1, Modelclass o2) {
                    return o1.getName().compareToIgnoreCase(o2.getName());
                       }
                    });

               Collections.sort(o2.getsubarraylist(), new Comparator<Modelclass>(){
                    @Override
                    public int compare(Modelclass o1, Modelclass o2) {
                    return o1.getName().compareToIgnoreCase(o2.getName());
                       }
                    });

             return o1.getName().compareToIgnoreCase(o2.getName()); 
// *This Sorts The Group's if you don't wanna sort group simply return 0*;
          }
        });

NOTE:- o1.getsubarraylist() & o2.getsubarraylist() is Child list's of a expandable list, Just add inner Collections.sort() for sorting expandable list's

or if you have Simple String arraylist

         Collections.sort(arraylist, new Comparator<String>(){
            @Override
            public int compare(String o1, String o2) {
             return o1.compareToIgnoreCase(o2);
              }
           });

I hope this helps someone in need....

Better and easy way to sort Categories with product is from mysql query. You can use inner join or any other which fits on your case to sort and make relation between products and categories .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM