notifyDataSetChanged在排序后不会更新自定义对象的listView

时间:2012-03-08 21:33:42

标签: android listview filter

我正在尝试在自定义arrayadapter中对集合进行排序,并调用更新视图。但是,视图不会更新。

我想对两个值进行排序(日期和金额),并为它们设置自定义比较器。

我可以看到数据本身已经发生了变化(例如,如果列表项在排序后已经超出视图范围,当它获得视图时,它显示的数据是排序后应该存在的正确数据。)

第二个问题是关于过滤器。现在实现过滤器的方式,它也不会更新视图。

这是代码

public class SearchActivity extends BListActivity {

private Bundle sessionInfo;
private TransactionDetailsHandler transactionDetailsHandler = new TransactionDetailsHandler();
private static boolean ascDate = false;
private static boolean ascAmount = false;

private ArrayList<TransactionDetails> transactionDetails;
private ArrayList<TransactionDetails> filterResults;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    sessionInfo = getIntent().getExtras();
    final String sessionId = sessionInfo.getString("sessionId");
    final String transactionResponse = sessionInfo
            .getString(C.TRN_DETAIL_KEY);

    try {
        Xml.parse(transactionResponse, transactionDetailsHandler);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    final ArrayAdapter<TransactionDetails> adapter = getArrayAdapter();

    findViewById(R.id.amount_btn).setOnClickListener(
            new View.OnClickListener() {
                public void onClick(View v) {

                    if (ascDate) {
                        adapter.sort(new TransactionDetailAmountComparatorAsc());
                        ascDate = false;
                    } else {
                        adapter.sort(new TransactionDetailAmountComparatorDesc());
                        ascDate = true;
                    }

                    adapter.notifyDataSetChanged();
                }
            });

    findViewById(R.id.date_btn).setOnClickListener(
            new View.OnClickListener() {
                public void onClick(View v) {
                    if (ascAmount) {
                        adapter.sort(new TransactionDetailDateComparatorAsc());
                        ascAmount = false;
                    } else {
                        adapter.sort(new TransactionDetailDateComparatorDesc());
                        ascAmount = true;
                    }

                    adapter.notifyDataSetChanged();
                }
            });

    findViewById(R.id.search_btn).setOnClickListener(
            new View.OnClickListener() {
                public void onClick(View v) {
                    findViewById(R.id.buttonLL).setVisibility(View.GONE);
                    findViewById(R.id.searchLL).setVisibility(View.VISIBLE);

                }
            });

    findViewById(R.id.cancel_btn).setOnClickListener(
            new View.OnClickListener() {
                public void onClick(View v) {
                    findViewById(R.id.searchLL).setVisibility(View.GONE);
                    findViewById(R.id.buttonLL).setVisibility(View.VISIBLE);

                }
            });

    TextWatcher filterTextWatcher = new TextWatcher() {
        public void afterTextChanged(Editable s) {
        }

        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            System.out.println("XXXX Constraint = " + s);
            adapter.getFilter().filter(s);
        }
    };

    EditText et = (EditText) findViewById(R.id.edit_box);
    et.addTextChangedListener(filterTextWatcher);

}

protected ArrayAdapter<TransactionDetails> getArrayAdapter() {
    transactionDetails = transactionDetailsHandler
            .getTransactionDetailsList();
    filterResults = transactionDetails;
    return new SearchListAdapter(this,
            (List<TransactionDetails>) transactionDetails);
}

protected class SearchListAdapter extends ArrayAdapter<TransactionDetails> {
    private int rId;
    private List<TransactionDetails> data;
    private Filter filter;

    public SearchListAdapter(Context context, List<TransactionDetails> data) {
        super(context, R.layout.search_list_item, data);
        this.rId = R.layout.search_list_item;
        this.data = data;
    }

    @Override
    public View getView(int position, View cv, ViewGroup parent) {
        cv = getLayoutInflater().inflate(rId, parent, false);
        TransactionDetails item = data.get(position);

        ((TextView) cv.findViewById(R.id.t_id)).setText(item.getTrnId());
        ((TextView) cv.findViewById(R.id.date)).setText(item
                .getTrnDatetime());
        ((TextView) cv.findViewById(R.id.amount)).setText(item
                .getTrnAmount());
        ((TextView) cv.findViewById(R.id.card_num))
                .setText("XXXX XXXX XXXX " + item.getTrnMaskedCard());

        try {
            if (item.getTrnCardType() != null
                    && item.getTrnCardType().trim().length() > 0)
                ((ImageView) cv.findViewById(R.id.card_img))
                        .setImageResource(Integer.parseInt(item
                                .getTrnCardType()));
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        ((TextView) cv.findViewById(R.id.result)).setText(item
                .getTrnStatus());
        return cv;
    }

    @Override
    public Filter getFilter() {
        if (filter == null)
            filter = new TransactionDetailFilter();
        return filter;
    }

    private class TransactionDetailFilter extends Filter {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            System.out.println("XXXX Started filtering with Constraint = "
                    + constraint);
            FilterResults results = new FilterResults();
            String prefix = constraint.toString().toLowerCase();

            if (prefix == null || prefix.length() == 0) {
                ArrayList<TransactionDetails> list = new ArrayList<TransactionDetails>(
                        transactionDetails);
                results.values = list;
                results.count = list.size();
            } else {
                final ArrayList<TransactionDetails> list = new ArrayList<TransactionDetails>(
                        transactionDetails);
                final ArrayList<TransactionDetails> nlist = new ArrayList<TransactionDetails>();
                int count = list.size();
                System.out
                        .println("XXXX List to be search size = " + count);
                for (int i = 0; i < count; i++) {
                    final TransactionDetails details = list.get(i);
                    System.out.println("XXXX List to be searched = "
                            + details.toString());
                    if (details.getTrnId().startsWith(prefix)
                            || details.getTrnDatetime().startsWith(prefix)
                            || details.getTrnAmount().startsWith(prefix)
                            || details.getTrnMaskedCard()
                                    .startsWith(prefix)
                            || details.getTrnStatus().startsWith(prefix)) {
                        System.out.println("XXXX Adding result "
                                + details.toString());
                        nlist.add(details);
                    }
                }
                results.values = nlist;
                results.count = nlist.size();
            }
            System.out.println("XXXX Ended filtering with Constraint = "
                    + constraint + " . Result size = " + results.count);
            return results;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint,
                FilterResults results) {
            System.out.println("XXXX Preparing to publish results. Result size = "+ results.count);
            ArrayList<TransactionDetails> fitems = (ArrayList<TransactionDetails>) results.values;

            clear();
            int count = fitems.size();

            for (int i = 0; i < count; i++) {
                TransactionDetails details = (TransactionDetails) fitems
                        .get(i);
                add(details);
            }
            notifyDataSetChanged();
            System.out.println("XXXX Finished publishing results.");

        }

    }

    @Override
    public void add(TransactionDetails item) {
        System.out.println("XXXX Adding items to be published." + item.toString());
        filterResults.add(item);
    }
}

// -------------------------------------------------------------------------------------------------------------------------------------------------
class TransactionDetailAmountComparatorAsc implements
        Comparator<TransactionDetails> {
    public int compare(TransactionDetails detail1,
            TransactionDetails detail2) {
        float f = Float.parseFloat(detail1.getTrnAmount())
                - Float.parseFloat(detail2.getTrnAmount());
        if (f > 0)
            return 1;
        if (f < 1)
            return -1;

        return 0;
    }
}

class TransactionDetailAmountComparatorDesc implements
        Comparator<TransactionDetails> {
    public int compare(TransactionDetails detail1,
            TransactionDetails detail2) {
        float f = Float.parseFloat(detail1.getTrnAmount())
                - Float.parseFloat(detail2.getTrnAmount());
        if (f > 0)
            return -1;
        if (f < 1)
            return 1;

        return 0;
    }
}

class TransactionDetailDateComparatorAsc implements
        Comparator<TransactionDetails> {
    public int compare(TransactionDetails detail1,
            TransactionDetails detail2) {
        detail1.getTrnDatetime();
        detail2.getTrnDatetime();
        String pattern = "MM/dd/yy HH:mm";
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        try {
            Date date1 = format.parse(detail1.getTrnDatetime());
            Date date2 = format.parse(detail2.getTrnDatetime());
            return date1.compareTo(date2);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return 0;
    }
}

class TransactionDetailDateComparatorDesc implements
        Comparator<TransactionDetails> {
    public int compare(TransactionDetails detail1,
            TransactionDetails detail2) {
        detail1.getTrnDatetime();
        detail2.getTrnDatetime();
        String pattern = "MM/dd/yy HH:mm";
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        try {
            Date date1 = format.parse(detail1.getTrnDatetime());
            Date date2 = format.parse(detail2.getTrnDatetime());
            return -(date1.compareTo(date2));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return 0;
    }
}

@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
    position -= ((ListView) parent).getHeaderViewsCount();
    TransactionDetails details = (TransactionDetails) parent.getAdapter()
            .getItem(position);

    Bundle b = new Bundle(sessionInfo);
    b.putSerializable(C.TRN_DETAIL_KEY, details);
    Util.openView(SearchActivity.this, TransDetailActivity.class, b);
}

@Override
protected int getContentView() {
    return R.layout.search_layout;
}

@Override
protected int getStringArrayID() {
    return 0;
}

@Override
protected Class<?>[] getDestinations() {
    return null;
}

@Override
protected int getTitleId() {
    return R.string.search;
}

}

0 个答案:

没有答案