Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Milliseconds String to formatted date String in SimpleCursorAdapter

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());
}
like image 343
user1617102 Avatar asked Jun 02 '26 04:06

user1617102


1 Answers

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);
    }
}
like image 126
Cat Avatar answered Jun 03 '26 19:06

Cat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!