【发布时间】:2017-11-06 05:50:02
【问题描述】:
我有一个包含 97 个元素的列表,我需要根据日期进行排序,其中包含格式为 DD/MM/YYYY 的日期,它仅是字符串类型,空对象和字符串类型的对象,即它具有这样的元素作为
我的日期字段中的数据示例:
12/02/2014
11/07/2017
null
India
现在我想根据日期字段对列表中的元素进行排序。
我想要的是所有带有日期的条目应该首先按升序出现,然后是所有带有字符串的条目,例如印度,然后是日期字段中为空的条目,然后是日期字段为空的条目,所以我应该如何在 compareTo 中对其进行编码方法
我已经看到了很多这方面的例子,但没有得到想要的结果。 怎么做?请帮帮我?
ListAdapter.java
public class ListAdapter1 extends BaseAdapter {
static int c=0;
Context context;
List<ListViewRow> l=new ArrayList<>();
List<String> lv=new ArrayList<String>();
ListAdapter1(Context context, String[] getid,String name[], String[] email, String[] mobile, String[] pass, String[] date) {
this.context=context;
for(int i=0;i<getid.length;i++)
{
l.add(new ListViewRow(getid[i],name[i],email[i],mobile[i],pass[i],date[i]));
}
Collections.sort(l, new ListRowComparator());
}
@Override
public int getCount() {
return l.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.list_view_row, parent, false);
TextView textView1 = (TextView) rowView.findViewById(R.id.name);
TextView textView2 = (TextView) rowView.findViewById(R.id.email);
TextView textView3 = (TextView) rowView.findViewById(R.id.mobile);
TextView textView4 = (TextView) rowView.findViewById(R.id.pass);
TextView textView5 = (TextView) rowView.findViewById(R.id.date);
ListViewRow lvr=l.get(position);
textView1.setText(lvr.name);
textView2.setText(lvr.email);
textView3.setText(lvr.mobile);
textView4.setText(lvr.pass);
textView5.setText(lvr.date);
return rowView;
}
}
ListViewRow.java
public class ListViewRow {
String getid,name,email,mobile,pass,date;
ListViewRow( String getid, String name, String email, String mobile, String pass, String date)
{
this.getid = getid;
this.name = name;
this.email = email;
this.mobile = mobile;
this.pass = pass;
this.date= date;
}
}
ListRowComparator.java
public class ListRowComparator implements Comparator<ListViewRow> {
@Override
public int compare(ListViewRow o1, ListViewRow o2) {
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
int compareResult = 0;
try {
if (o1.date== null || o2.date== null)
{
return 0;
}
else {
compareResult = format.parse(o1.date).compareTo(format.parse(o2.date));
System.out.println("compare:" + compareResult);
}
} catch (ParseException e) {
e.printStackTrace();
}
return compareResult;
}
}
【问题讨论】:
-
将
new SimpleDateFormat("dd-MM-yyyy");更改为new SimpleDateFormat("dd/MM/yyyy"); -
@chandil03 同意。
标签: java android sorting date listview