Sort DB data and display in list view

两盒软妹~` 提交于 2019-12-01 06:33:33

The easiest suggestion would be to save the date in a different format (but still saved as string) into the database. If you would save the data into SQLite’s default date format (YYYY-MM-DD HH:NN:SS), you can easily sort the dates.

To display the date in your format, you would only just need to reformat the date into the correct format.

Well, i changed my table structure. I added another field "_id" to it. Set the property as AUTO INCREMENT to it, and sorted the list with respect to _id field.

Mayur More

If you r using ORM you can sort the data by timestamp. ORM makes data insertion and data retrieval easier from database. You have to include jar files to your project to use ORM...

since SQLite has no datetime type, store date type as LONG/INT/NUMERIC in SQLite (EPOCH time) it will be easier to sort

then add ViewBinder to Adapter

        /*field in activity/fragment*/
        final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //or other format that you wana to show in ListView
        ...
        mAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {

            @Override
            public boolean setViewValue(View view, Cursor cursor,
                    int columnIndex) {
                final int id = view.getId();
                switch (id) {
                    case R.id.id_of_textview_with_date_data:
                        final Calendar cal = Calendar.getInstance();
                        cal.setTimeInMillis(cursor.getLong(columnIndex));
                        ((TextView) view).setText(sdf.format(cal.getTime()));
                        return true;
                }
                return false;
            }
        });

... or as dennisg pointed store it as STRING/VARCHAR edit: in "yyyy-MM-dd HH:mm:ss" format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!