I check a webside if new items have been posted and if yes a string value "new" is added to these items.
Now the long value "date" always stays on -1, as a result the string value "new" is added after every item, also for items added for example yesterday.
"new" should not be shown for values older then today, please help.
Thank you.
public class TopicView extends LinearLayout implements LoadTopicImageCallback {
private LoadTopicImageTask topicImageTask = null;
private boolean newItem = false;
private long date = -1;
public TopicView(final Context context, final Topic topic) {
super(context);
init(topic);
}
public TopicView(final Context context, final Topic topic, final String suffix) {
super(context);
init(topic);
final long latest = new Settings(context).getLatest(suffix);
try {
final Date d = Util.parseDate(topic.getTime());
date = d.getTime();
} catch (final ParseException e) {
}
//String new gets added//
if (latest == -1 || date > latest) {
findViewById(R.id.topic_view_new).setVisibility(View.VISIBLE);
newItem = true;
}
}
public boolean isNewItem() {
return newItem;
}
public long getDate() {
return date;
}
EDIT:
public static String formatDate(final long dt) {
return formatDate(new Date(dt));
}
public static String formatDate(final Date date) {
final DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
return df.format(date);
}
public static final Date parseDate(final String date) throws ParseException {
final String pattern = "EEE MMM dd, yyyy h:mm a";
return parseDate(date, pattern);
}
public static final Date parseDate(final String date, final String pattern)
throws ParseException {
final SimpleDateFormat format = new SimpleDateFormat(pattern, Locale.US);
return format.parse(date);
}
Unless you're sure that you're calling the second constructor, you never initialise the date here:
public TopicView(final Context context, final Topic topic) {
super(context);
init(topic);
// add some initialisation for "date" here
}
And even if you are, it would've been helpful to see that small part of code too.
As an aside, can I point out that it's fine to consume exceptions, but even a shred of debug output can help you in the long run. Maybe change
try {
final Date d = Util.parseDate(topic.getTime());
date = d.getTime();
} catch (final ParseException e) {
}
to:
try {
final Date d = Util.parseDate(topic.getTime());
date = d.getTime();
} catch (final ParseException e) {
e.printStackTrace(); // Or some log that your define yourself.
}
Related
I need to format date and time in the RemoteViewsFactory class. I know how to use DateFormat/SimpleDate Format. I'm doing it like in the thread below but the app keeps stopping when pressing on the widget on a physical device: remoteViews.setTextViewText(R.id.tvTaskDay, DateFormat.getDateInstance().format(task.getDay()));
Android - ListView items inside app widget not selectable
I'm also formatting in the parent activity and it works. Is it possible to reference the SimpleDateFormat code from there? Thank you in advance.
P.S. Error message.
My RemoteViewsFactory class:
public class ScheduleWidgetViewFactory implements RemoteViewsService.RemoteViewsFactory
{
private ArrayList<Schedule> mScheduleList;
private Context mContext;
public ScheduleWidgetViewFactory(Context context)
{
mContext = context;
}
#Override
public void onCreate()
{
}
#Override
public void onDataSetChanged()
{
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(mContext);
Gson gson = new Gson();
Type type = new TypeToken<List<Schedule>>() {}.getType();
String gsonString = sharedPreferences.getString("ScheduleList_Widget", "");
mScheduleList = gson.fromJson(gsonString, type);
}
#Override
public int getCount()
{
return mScheduleList.size();
}
#Override
public RemoteViews getViewAt(int position)
{
Schedule schedule = mScheduleList.get(position);
RemoteViews itemView = new RemoteViews(mContext.getPackageName(), R.layout.schedule_widget_list_item);
itemView.setTextViewText(R.id.schedule_widget_station_name, schedule.getStationScheduleName());
itemView.setTextViewText(R.id.schedule_widget_arrival, DateFormat.getDateInstance().format(schedule.getExpectedArrival()));
itemView.setTextViewText(R.id.schedule_widget_towards, schedule.getDirectionTowards());
Intent intent = new Intent();
intent.putExtra(ScheduleWidgetProvider.EXTRA_ITEM, schedule);
itemView.setOnClickFillInIntent(R.id.schedule_widget_list, intent);
return itemView;
}
#Override
public int getViewTypeCount()
{
return 1;
}
Parent Activity:
#Override
public void returnScheduleData(ArrayList<Schedule> simpleJsonScheduleData)
{
if (simpleJsonScheduleData.size() > 0)
{
scheduleAdapter = new ScheduleAdapter(simpleJsonScheduleData, StationScheduleActivity.this);
scheduleArrayList = simpleJsonScheduleData;
mScheduleRecyclerView.setAdapter(scheduleAdapter);
scheduleAdapter.setScheduleList(scheduleArrayList);
stationArrival = scheduleArrayList.get(0);
stationShareStationName = stationArrival.getStationScheduleName();
stationShareArrivalTime = stationArrival.getExpectedArrival();
stationShareDirection = stationArrival.getDirectionTowards();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Date date = null;
try {
date = simpleDateFormat.parse(stationArrival.getExpectedArrival());
date.toString();
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat newDateFormat = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss");
String finalDate = newDateFormat.format(date);
stationShareArrivalTime = finalDate;
//Store Schedule Info in SharedPreferences
SharedPreferences appSharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(scheduleArrayList);
prefsEditor.putString("ScheduleList_Widget", json);
prefsEditor.apply();
}
else
{
emptySchedule.setVisibility(View.VISIBLE);
}
In case anyone else has is stuck on this. As Mike M. pointed out in the comments, the DateFormat code structure in RemoteViewsFactory is the same as everywhere else.
private String stationWidgetArrivalTime;
#Override
public RemoteViews getViewAt(int position)
{
Schedule schedule = mScheduleList.get(position);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Date date = null;
try {
date = simpleDateFormat.parse(schedule.getExpectedArrival());
date.toString();
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat newDateFormat = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss");
String finalDate = newDateFormat.format(date);
stationWidgetArrivalTime = finalDate;
RemoteViews itemView = new RemoteViews(mContext.getPackageName(), R.layout.schedule_widget_list_item);
itemView.setTextViewText(R.id.schedule_widget_station_name, schedule.getStationScheduleName());
itemView.setTextViewText(R.id.schedule_widget_arrival, stationWidgetArrivalTime);
itemView.setTextViewText(R.id.schedule_widget_towards, schedule.getDirectionTowards());
Intent intent = new Intent();
intent.putExtra(ScheduleWidgetProvider.EXTRA_ITEM, schedule);
itemView.setOnClickFillInIntent(R.id.schedule_widget_list, intent);
return itemView;
}
I am creating event App, which lists all events.
I have a problem, that when event is over, it still stays up because it was sorted by time if next event is after a week. Like this:
So, the event which was end, is need to go down and also be sorted by date.
How can I do this?
I tried to sort seperately by date and boolean, but it failed.
Or does I need to create two arraylists for ended events and upcoming?
If someone knows how to do this, please tell me, you save my day.
My code, which sorts right now:
Collections.sort(eventsList, new Comparator<TimetableEvent>() {
#Override
public int compare(TimetableEvent arg0, TimetableEvent arg1) {
SimpleDateFormat format = new SimpleDateFormat(
"dd.MM.yyyy' klo 'HH.mm");
int compareResult = 0;
try {
Date arg0Date = format.parse(arg0.getDateTime());
Date arg1Date = format.parse(arg1.getDateTime());
compareResult = arg0Date.compareTo(arg1Date);
} catch (ParseException e) {
e.printStackTrace();
compareResult = arg0.getDateTime().compareTo(arg1.getDateTime());
}
return compareResult;
}
});
Simply adapt your compare() method so that, if an event is over and the other one is not, it returns without comparing date:
#Override
public int compare(TimetableEvent arg0, TimetableEvent arg1) {
SimpleDateFormat format = new SimpleDateFormat(
"dd.MM.yyyy' klo 'HH.mm");
int compareResult = 0;
if (arg0.isOver() && !arg1.isOver()) {
return 1;
}
if (!arg0.isOver() && arg1.isOver()) {
return -1;
}
try {
Date arg0Date = format.parse(arg0.getDateTime());
Date arg1Date = format.parse(arg1.getDateTime());
compareResult = arg0Date.compareTo(arg1Date);
} catch (ParseException e) {
e.printStackTrace();
compareResult = arg0.getDateTime().compareTo(arg1.getDateTime());
}
return compareResult;
}
I have two datepickers in my activity.
I want startdate of datePickerB dialog to be updated automatically based on date selected in datePickerA dialog.
I use setMinDate for datePickerB. setMinDate works fine for the very first time. But couldn't update or reset the mindate of datePickerB for consecutive updates in datePickerA. Kindly help.
Searched for all possible solutions but of no use. Kindly help
Below is my code. The code used in oncreate gets executed , but further setMinDate function called in HandleResponse ( this is the function that gets called once datepickerA is set )
//On OnCreate
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, 1);
Date tomorrow = calendar.getTime();
long t = tomorrow.getTime();
fromDatePicker.getDatePicker().setMinDate(t);
//
toDatePicker.getDatePicker().setMinDate(t);
public void HandleResponse(Response response)
{
String sqlRes = "";
try {
String sResJson = response.body().string();
JSONObject jReader = new JSONObject(sResJson);
JSONObject jRes = jReader.getJSONObject("Result");
sqlRes = jRes.getString("res");
final int sqlMilkQty = jRes.getInt("qty");
String enddate = jRes.getString("date");
Date d = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
d = sdf.parse(enddate);
} catch (ParseException e) {
e.printStackTrace();
}
if (d != null && fromDate!= null) {
long t = d.getTime();
long t1 = fromDate.getTime();
toDatePicker.getDatePicker().setMinDate(t1);
toDatePicker.getDatePicker().setMaxDate(t);
}
Handler mainHandler = new Handler(Looper.getMainLooper());
if (sqlRes.equals("PASS"))
{
mainHandler.post(new Runnable() {
#Override
public void run() {
milkQuantity = sqlMilkQty;
txtMilkQuantity.setText(String.valueOf(milkQuantity));
}
});
}
else {
}
} catch (IOException e) {
DisplayError();
}
catch (JSONException e) {
DisplayError();
}
}
I have the array of objects that look like this:
public class Time {
public String start_time;
public String finish_time;
public Time(String start_time, String finish_time) {
this.start_time = start_time;
this.finish_time = finish_time;
}
}
I need to implement a timer in my Fragment in the following way:
it should start counting down from the first element in array in a way that on one single Time element it should first start counting down to the time left to reach start_time, then when the timer reaches start_time, it should start counting down to finish_time and, eventually, when it reaches finish_time it should do the same previous actions for the next element in the array. And when the whole array is finished, it should display 00:00:00.
PS: start_time and finish_time are formatted like this: HH:mm however the timer should be HH:mm:ss
Can anybody help with implementing that or at least give an idea?
Finally, found the appropriate answer. Thanks a lot to the guy who helped me with it:
class Clazz {
private Timer dateTimer;
private Timer remainderTimer;
private Date nextDate;
private boolean remainderTimerStarted;
private static final long REMINDER_UPDATE_INTERVAL = 1000;
private static final String[] DATES = { "12.04.2015 22:21", "12.04.2015 22:22", "12.04.2015 22:23" };
private int currentIndex;
public Clazz() {
dateTimer = new Timer();
}
public static void main(String[] args) {
Clazz instance = new Clazz();
instance.run();
}
private void run() {
nextDate = parseDate(DATES[currentIndex]);
schedule();
}
public void schedule() {
runSecondsCounter();
dateTimer.schedule(new TimerTask() {
#Override
public void run() {
System.out.println("Current date is:" + new Date());
currentIndex++;
if (currentIndex < DATES.length) {
nextDate = parseDate(DATES[currentIndex]);
System.out.println("Next date is:" + nextDate);
schedule();
} else {
remainderTimer.cancel();
}
}
}, nextDate);
}
private Date parseDate(String nextDate) {
Date date = null;
DateFormat format = new SimpleDateFormat("dd.MM.yyyy HH:mm",
Locale.ENGLISH);
try {
date = format.parse(nextDate);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
private void runSecondsCounter() {
if (remainderTimerStarted) {
remainderTimer.cancel();
}
remainderTimer = new Timer();
remainderTimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
remainderTimerStarted = true;
long remains = nextDate.getTime() - new Date().getTime();
System.out.println("Remains: " + (remains / 1000) + " seconds");
}
}, REMINDER_UPDATE_INTERVAL, REMINDER_UPDATE_INTERVAL);
}
}
I have a DateTimehelper.class in which i have performed some date related operation and the code was working fine until i get issue from customer that they are getting date in wrong format.following is my class:
public class DateTimeHelper {
private static Calendar cal;
public static DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static DateFormat shortDateFormatter = new SimpleDateFormat("yyyy-MM-dd");
public static DateFormat shortDateFormatterWithSlash = new SimpleDateFormat("dd/MM/yyyy");
public static DateFormat dateFormat_dd_MM_yyyy = new SimpleDateFormat("dd-MM-yyyy");
DateTimeHelper helper;
/**
* set UTC Date to the calendar instance
*
* #param strDate
* date to set
*/
public static void setDate(String strDate) {
try {
Date date = (Date) formatter.parse(strDate);
cal = Calendar.getInstance();
cal.setTime(date);
updateDateTime();
}
catch (ParseException e) {
e.printStackTrace();
}
}
/**
* update date every 1 second
*/
private static void updateDateTime() {
final Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
try {
cal.add(Calendar.SECOND, 1);
handler.postDelayed(this, 1000);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
/***
* get updated date from calendar in custom date format
*
* #return date
*/
public static String getDate() {
String strDate = null;
try {
strDate = formatter.format(cal.getTime());
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return strDate;
}
}
When See the logs I found date in format:2014-0011-25 04:45:38 which is completely wrong I guess because month should be 11 instead of 0011.
But when I tried to validate this date using the below function;it says that date is valid.
public static boolean isValidDate(String inDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
try {
dateFormat.parse(inDate.trim());
} catch (ParseException pe) {
return false;
}
return true;
}
How can it be a valid date?
Why I am getting date in wrong format?
This issue is very random as it is reported by only user but I am very surprised by the behavior of SimpleDateFormater and Calendar API
Please help.
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try this see if it works