Search code examples
javaandroidsqlitesimpledateformatandroid-cursorloader

How to do Date parsing and formating inside a bindview of cursor adapter in android


I have saved my dates in my sqlite table like 2016-04-20 and I want my listview display them as 20/4/2016 and I use the following inside the bindview of a cursor adapter

String InitialDate=cursor.getString(cursor.getColumnIndex(cursor.getColumnName(2)));

SimpleDateFormat curFormater = new SimpleDateFormat("yyyy-MM-dd");
Date dateObj = curFormater.parse(InitialDate);
SimpleDateFormat postFormater = new SimpleDateFormat("dd/MM/yyyy");
String newDateStr = postFormater.format(dateObj);
textViewDate.setText(newDateStr);

but before I do anything the part of parse says Unhandled Exception java.text.ParseException I have import of

import java.text.SimpleDateFormat;
import java.util.Date;

Solution

  • you should use try/catch block for parse method call because it can produce checked exception:

    Date dateObj = null;
    try {
        dateObj = curFormater.parse(InitialDate);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    

    or you can just rethrow this exception from your method (you should use throws ParseException clause in method signature)

    via documentation:

    Checked exceptions are subject to the Catch or Specify Requirement. All exceptions are checked exceptions, except for those indicated by Error, RuntimeException, and their subclasses.