I'm currently building my first app for Android. What I'm having trouble with is the storage and localized display of dates in connection with a SimpleCursorAdapter
. I have a class that encapsulates access to an SQLitedatabase
with three tables. This class takes care of storing all dates in ISO format ("yyyy-MM-dd"). When the date values are read from the database and displayed on the screen I want them to be formatted in a localized format. Here's the approach I've come up with. It uses a ViewBinder
to do the formatting:
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
@Override
public boolean setViewValue(View view, Cursor cursor,
int columnIndex) {
if (view.getId() == R.id.text1) {
((TextView) view).setText(getDateFormatView().format(
parseDatabaseDate(cursor.getString(columnIndex))));
return true;
} else if (view.getId() == R.id.text2) {
((TextView)view).setText(
cursor.getString(columnIndex));
return true;
} else {
return false;
}
}
});
getDateFormatView()
creates a SimpleDateFormat
object with a pattern that is read from strings.xml
. parseDatabaseDate()
does the parsing of the date from the database with a SimpleDateFormat
that is constructed using a constant pattern yyyy-MM-dd
.
Although this code works just fine I'm wondering if there is a better way to do that. What I don't like is that I need:
- two
SimpleDateFormat
objects (one is used in parseDatabaseDate()
in order to parse the date string from the SQLiteDatabase
, the other is used to format the value)
- a
java.util.Date
object that is created then thrown away immediately
- quite a lot of (in my opinion) boilerplate code.
So that's why I'm asking: is there a better way to display dates in localized format?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…