Reputation: 1709
The time value I get from JSON response is of format "sun dd/mm/yyyy - HH:mm"
and I want to convert it to a time span instead (10 min ago, 2 days ago...). For that I made a method converts given String of dataTimeFormant into "X Hours Ago
" format and returns x hours ago
in a string format then I can put in a textView.
Everything seems correct, I think, but the app crashes on start with a NullPonterException to a line of my code, so probably I have made things wrong.
@RequiresApi(api = Build.VERSION_CODES.N)
public String dateConverter(String dateStringFormat) {
Date date = null;
SimpleDateFormat currentDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z");
try {
date = currentDateFormat.parse(dateStringFormat);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat requireDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDate = requireDateFormat.format(date);
long currentTimeInMilis = 0;
try {
Date currentDateObject = requireDateFormat.parse(currentDate);
currentTimeInMilis = currentDateObject.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
CharSequence timeSpanString = DateUtils.getRelativeTimeSpanString(currentTimeInMilis, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS);
return timeSpanString.toString();
}
My adapter onBindView method:
@Override
public void onBindViewHolder(ViewHolder viewHolder, final int i) {
//...
//...
//...
DateConvert converter = new DateConvert();
String postTime = converter.dateConverter(this.news.get(i).getCreated());
viewHolder.articleCreatedDate.setText(postTime);
}
The logcat error points to:
String currentDate = requireDateFormat.format(date);
and :
String postTime = converter.dateConverter(this.post.get(i).getCreated());
I'm unable to find the cause because if I remove the call to that function everything works perfectly, probably there are better ways to achieve this?
Thanks.
Upvotes: 0
Views: 367
Reputation: 56
I am new here, hopefully I can help.
The first thing I notice is there is no closing single quotation after 'Z:
SimpleDateFormat currentDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
Besides, the problem is the "currentDateFormat" does not portray the proper date input format which causes it not to be able to parse properly. If the input is "sun dd/MM/yyyy - HH:mm" then the format should be:
SimpleDateFormat currentDateFormat = new SimpleDateFormat("EEE MM/dd/yyyy '-' HH:mm");
Or
SimpleDateFormat currentDateFormat = new SimpleDateFormat("EEE MM/dd/yyyy - HH:mm");
Then date = currentDateFormat.parse(dateStringFormat);
should be able to parse properly and the "date" will not have "null" value.
Hope this helps.
Upvotes: 2