Saving and displaying dates in a list with Android

Trying to clean up some bits that I’ve left sort of hazy. Now it’s time to wrestle with – how do I really get working dates between Java and sqlite and the user? Really two issues: how do I store it in the DB, and how do I get it from the DB and display to the user?

This is always a tad tricky with any DB. In some ways it seems sqlite treats dates like strings; and you can just stuff anything in that column, without it being valid in any sense, and sqlite accepts it without complaint. But it’s useful to notice that if you insert (or select) datetime() it puts it in the useful “YYYY-MM-DD HH:MM:SS” format (useful because at least they compare/sort properly). So I can format times that way to store them – only issue is GMT vs local time.

For displaying to the user, Android has some time formatting functions, but I’m having a heck of a time figuring them out, not being used to the Java idiom I guess. Looks like this blog post has some good pointers. The other tricky point is that I’m currently just handing off the database cursor to be displayed in a ListItem – not sure how to reformat things in between. I tried creating a custom view extending TextView just for the log output (consulting docs here). I’m not sure where I went wrong, but Android simply did not want to use that view; the view builder in ADT had an error about <init> not being defined, and I don’t remember what error I got when trying to run the app. So I asked on IRC and was advised to extend the Adapter instead. Here’s what I ended up with:

public static final String db_DATE_FORMAT = “yyyy-MM-dd HH:mm:ss”;
public static final DateFormat dbDateFormat = new SimpleDateFormat(db_DATE_FORMAT);

@Override
public void setViewText(TextView v, String text) {
if(v.getId() == R.id.ilr_itemLog && text != null && text.length() > 0) {
// try to reformat date text as a local date
try {
Date d = C.dbDateFormat.parse(text.toString());
text = d.toLocaleString();
} catch (ParseException e) {
Log.d(TAG, “Date parsing failed for ” + text);
}
}
super.setViewText(v, text);
}

This seems to work fine. But the real test is later when I let the user modify the log time; we’ll see.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: