Converting Milliseconds String to formatted date String in SimpleCursorAdapter

adapter, android

Solution

You can't parse it out until after the value is returned from `new SimpleCursorAdapter`. This means you need to create your own `SimpleCursorAdapter` type and override `setViewText`.

Something like this:

adapter = new MySimpleCursorAdapter(this, R.layout.listrow, cursor,
        new String[] { Database.KEY_DATE , Database.KEY_NAME },
        new int[] {R.id.text1, R.id.text2}, 0);

// ...

public static String getDate(Long milliSeconds, String dateFormat) {
    SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
    return formatter.format(milliSeconds);
}

// In MySimpleCursorAdapter.java:

public class MySimpleCursorAdapter extends SimpleCursorAdapter {
    @Override
    public void setViewText(TextView v, String text) {
        if (v.getId() == R.id.text1) { // Make sure it matches your time field
            // You may want to try/catch with NumberFormatException in case `text` is not a numeric value
            text = WhateverClass.getDate(Long.parseLong(text), "dd. MMMM yyyy hh:mm:ss");
        }
        v.setText(text);
    }
}

Problem

I'm retrieving a milliseconds `String` from my `SQLite` database and want to convert it to a formatted date `String`. It basically works, but not when I'm trying it in an array (see below). It throws a `NumberFormatException`. How can i fix this? ``` adapter = new SimpleCursorAdapter(this, R.layout.listrow, cursor, new String[] { getDate(Long.parseLong(Database.KEY_DATE), "dd. MMMM yyyy hh:mm:ss") , Database.KEY_NAME }, new int[] {R.id.text1, R.id.text2}, 0); public static String getDate(Long milliSeconds, String dateFormat){ SimpleDateFormat formatter = new SimpleDateFormat(dateFormat); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(milliSeconds); return formatter.format(calendar.getTime()); } ```

Original source