简体   繁体   中英

How to sort the arraylist with two different model class in android?

I'm creating the grid view with array list of category and un categorized product model class. Now I want to sort the list by date or name. See below my code.

Here this is my adapter.

public class CommonAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater inflator = null;
private List<Object> list;

public CommonAdapter(Context mContext, List<Object> list) {
    super();
    this.mContext = mContext;
    this.list = list;
    inflator = LayoutInflater.from(mContext);
}


@Override
public int getCount() {
    return list.size();
}

@Override
public Object getItem(int position) {
    return list.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    ViewHolder holder;
    if (convertView == null) {
        convertView = inflator.inflate(R.layout.row_categories, null);
        holder = new ViewHolder();
        holder.layout_bg = (RelativeLayout) convertView.findViewById(R.id.grid_bg);
        holder.titleTextView = (TextView) convertView.findViewById(R.id.grid_item_title);
        holder.txt_price = (TextView) convertView.findViewById(R.id.txt_price);
        holder.img_notifier = (ImageView) convertView.findViewById(R.id.img_notifier);
        holder.titleTextView.setTextColor(Color.WHITE);
        holder.titleTextView.setTextSize(27);
        holder.titleTextView.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD);
        holder.titleTextView.setLayoutParams(new RelativeLayout.LayoutParams(200, 200));
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }
    if (list.get(position) instanceof Product) {
        holder.titleTextView.setText(((Product) list.get(position)).getShortCode());
        holder.img_notifier.setVisibility(ImageView.GONE);
        holder.txt_price.setVisibility(TextView.VISIBLE);
        NumberFormat format = NumberFormat.getCurrencyInstance();
        double amount = Double.parseDouble(((Product) list.get(position)).getPrice()toString());
        String formatAmount = NumberFormat.getCurrencyInstance().format(amount / 100);
        holder.txt_price.setText(formatAmount);
    }
    if (list.get(position) instanceof Category) {
        holder.titleTextView.setText(((CategoryWithProduct) list.get(position)).getShortCode());
        holder.img_notifier.setVisibility(ImageView.VISIBLE);
        holder.txt_price.setVisibility(TextView.GONE);
        if (((Category) list.get(position)).getColor() != null) {
            holder.layout_bg.setBackgroundColor(Color.parseColor(((Category) list.get(position)).getColor()));
        } else {
        }
    }
    return convertView;
}

static class ViewHolder {
    RelativeLayout layout_bg;
    TextView titleTextView, txt_price;
    ImageView img_notifier;
}

This is product model classes

public class Product {
String id;
String name;
String price;
String createAt;

public Product(String id, String name, String price, String createAt) {
    this.id = id;
    this.name = name;
    this.price = price;
    this.createAt = createAt;
}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getName() {
    return name;
}

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

public String getPrice() {
    return price;
}

public void setPrice(String price) {
    this.price = price;
}

public String getCreateAt() {
    return createAt;
}

public void setCreateAt(String createAt) {
    this.createAt = createAt;
}
}

This is Category Model

public class Category {
String id;
String name;
String createAt;

public Category(String id, String name, String createAt) {
    this.id = id;
    this.name = name;
    this.createAt = createAt;
}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getName() {
    return name;
}

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

public String getCreateAt() {
    return createAt;
}

public void setCreateAt(String createAt) {
    this.createAt = createAt;
}
}

In MainActivity.java

CommonAdapter commonAdapter = new CommonAdapter(getActivity(), commonArrayList);
grid_common.setAdapter(commonAdapter);

Here I tried with comparator, it's comes with object only!

Collections.sort(commonArrayList, new Comparator<Object>() {
                    @Override
                    public int compare(Object o1, Object o2) {
                        return 0;
                    }
                });

See here both models have createAt and name fields, So I want to sort by createAt or by name in this ArrayList.

Create another object model class and add all method and variable there is in two separate class... and set data manually then... using for loop and any other ..that suitable for you...

and you this third created object model for sorting your data...

Edited

Eg: first class

class first{
    String f_name,l_name;

    public String getF_name() {
        return f_name;
    }

    public void setF_name(String f_name) {
        this.f_name = f_name;
    }

    public String getL_name() {
        return l_name;
    }

    public void setL_name(String l_name) {
        this.l_name = l_name;
    }
}

Second class

public class second {

String f_name,l_name,m_name;

public String getF_name() {
    return f_name;
}

public void setF_name(String f_name) {
    this.f_name = f_name;
}

public String getL_name() {
    return l_name;
}

public void setL_name(String l_name) {
    this.l_name = l_name;
}


public String getM_name() {
    return m_name;
}

public void setM_name(String m_name) {
    this.m_name = m_name;
}
}

third class

public class third{

String f_name,l_name,m_name;

public String getF_name() {
    return f_name;
}

public void setF_name(String f_name) {
    this.f_name = f_name;
}

public String getL_name() {
    return l_name;
}

public void setL_name(String l_name) {
    this.l_name = l_name;
}


public String getM_name() {
    return m_name;
}

public void setM_name(String m_name) {
    this.m_name = m_name;
}
}

set all value of first and second into third...

and use third class for setup data and sorting data

Here is my advice:

public class Category {
    String id;
    String name;
    String createAt;
       ...
}
public class Product extends Category{
    String price;
     ....
}

Collections.sort(commonArrayList, new Comparator<Category>() {
                    @Override
                    public int compare(Category o1, Category o2) {
                        if(o1.getCreateAt()>o2.getCreateAt()){
                           return 1;
                         }else{
                            ...
                         }
                        return 0;
                    }
                });

Create an abstract class, put fields common in Product and Category and compare that class.

public abstract class BaseClass {
private String id;
private String name;

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getName() {
    return name;
}

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

Your Public class:

public class Product extends BaseClass {
    ...

    public Product(String id, String name, String price, String createAt) {
        setId(id);
        setName(name);
        this.price = price;
        this.createAt = createAt;
    }
}

Category class:

public class Category extends BaseClass {
...

public Category(String id, String name, String createAt) {
    setId(id);
    setName(name);
    this.createAt = createAt;
}
}

And compare like this:

Collections.sort("ArrayList<BaseClass>()", new Comparator<BaseClass>() {
        @Override
        public int compare(BaseClass baseClass, BaseClass t1) {
            return baseClass.getName().compareTo(t1.getName());
        }
    });

If you wanna sort by date put date field to BaseClass .

Thanks for your advice. I found the answer. I just make class casting on the object inside the comparator.

See the code below,

Collections.sort(commonArrayList, new Comparator<Object>() {
                    @Override
                    public int compare(Object o1, Object o2) {
                        int res = 0;
                        if (o1 instanceof Category && o2 instanceof Category) {
                            res = (((Category) o1).getName().compareTo(((Category) o2).getName()));
                        } else if (o1 instanceof Product && o2 instanceof Product) {
                            res = (((Product) o1).getName().compareTo(((Product) o2).getName()));
                        } else if (o1 instanceof Category && o2 instanceof Product) {
                            res = (((Category) o1).getName().compareTo(((Product) o2).getName()));
                        } else if (o1 instanceof Product && o2 instanceof Category) {
                            res = (((Product) o1).getName().compareTo(((Category) o2).getName()));
                        }
                        return res;
                    }
                });

If you have any simplified ideas, kindly post here..

Hope this sample solution in java may help :

Create an interface let say Data as follows

public interface Data {

}

Create the model classes as follows :

Product

public class Product implements Data{
    String id;
    String name;
    String price;
    String createAt;

    public Product(String id, String name, String price, String createAt) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.createAt = createAt;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getCreateAt() {
        return createAt;
    }

    public void setCreateAt(String createAt) {
        this.createAt = createAt;
    }

}

Category

public class Category implements Data{
    String id;
    String name;
    String createAt;

    public Category(String id, String name, String createAt) {
        this.id = id;
        this.name = name;
        this.createAt = createAt;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getCreateAt() {
        return createAt;
    }

    public void setCreateAt(String createAt) {
        this.createAt = createAt;
    }
    }

Now in main class of the project

public class TestSorting {
    public static void main(String args[]) {
        ArrayList<Data> categories = new ArrayList<>();
        ArrayList<Data> products = new ArrayList<Data>();
        // For Product
        for (int i = 0; i < 10; i++) {
            Product product = new Product("Prod" + i, "Product " + i, "" + i, System.currentTimeMillis() + "");
            products.add(product);
        }
        // For category
        for (int i = 10; i >=0; i--) {
            Category category = new Category("Cat" + i, "Category " + i, System.currentTimeMillis() + "");
            categories.add(category);
        }
        Collections.sort(categories, new Comparator<Data>() {
            @Override
            public int compare(Data data, Data data2) {

                if(data instanceof Category)
                {
                     int result=(((Category) data).getId().compareTo((((Category) data2).getId())));


                     return result;


                }else if(data instanceof Product)
                {
                    int result= (((Product) data).getId().compareTo(((Product) data2).getId()));
                    return result;

                }else {
                    return 0;
                }

            }
        });

        System.out.println("******PRODUCT****************");
        // For Product
                for (int i = 0; i < products.size(); i++) {
                    Product product=((Product)products.get(i));
                    System.out.println(product.id+ "   "+product.name);
                }
                System.out.println("\n\n"+"******Caterogy****************");
                // For category
                for (int i = 0; i < categories.size(); i++) {
                    Category category=((Category)categories.get(i));
                    System.out.println(category.id+ "   "+category.name);
                }
    }
}

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