Run CountDownTimer on array of dates - android

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);
}
}

Related

duplicate list is adding to gridview in android

Hi in the below I am displaying calendarview.In calendarview I am selecting date and passing that date to GetAppointmentDate(selecteddate) if selecteddate and my date matches I am displaying gridview layout.but it is give multiple list with below .
Can any one help y duplicate list is displaying evrytime.
CalendarViewActivity.java:
public class CalendarViewActivity extends Activity implements DatetimeAdapter.MyItemClickListener{
private CalendarView mCalendarView;
private ProgressDialog progressDialog = null;
private ArrayList<GetData> getDataArrayList;
private ArrayList<GetSlots> getSlotsArrayList;
private GridView gridLayout;
private GetData getData2;
private GetSlots getSlots2;
private String Id,StartTime,SlotBooked,SlotDate,EndTime,SloteTime;
private DatetimeAdapter datetimeAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calendar_view);
gridLayout=findViewById(R.id.gridlayout);
getDataArrayList=new ArrayList<>();
getSlotsArrayList=new ArrayList<>();
mCalendarView = (CalendarView) findViewById(R.id.calendarView);
mCalendarView.setMinDate(System.currentTimeMillis() - 1000);
datetimeAdapter = new DatetimeAdapter(getApplicationContext(), getSlotsArrayList,this);
mCalendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
Calendar calendar = Calendar.getInstance();
int year1 = calendar.get(Calendar.YEAR);
int month1 = calendar.get(Calendar.MONTH);
int dayOfMonth1 = calendar.get(Calendar.DAY_OF_MONTH);
#Override
public void onSelectedDayChange(CalendarView CalendarView, int year1, int month1, int dayOfMonth1) {
String date = new SimpleDateFormat("MM", Locale.getDefault()).format(new Date());
SimpleDateFormat sdf = new SimpleDateFormat(date);
String selecteddate = (sdf.format(month1 + 1)) + "/" + dayOfMonth1 + "/" + year1;
GetAppointmentDate(selecteddate);
Toast.makeText(getApplicationContext(),selecteddate,Toast.LENGTH_LONG).show();
}
});
}
private void GetAppointmentDate(String outputcurrentdate) {
// progressDialog = new ProgressDialog(getApplicationContext());
// progressDialog.setIndeterminate(true);
// progressDialog.setMessage("Loading...");
// progressDialog.setCanceledOnTouchOutside(false);
// progressDialog.setCancelable(false);
// progressDialog.show();
String doctor_ids="13";
String HospitalId="PH:193";
final APIService service = RetroClass.getRetrofitInstance().create(APIService.class);
Call<GetAppointmentDateModel> call = service.GetAppointmentDate(doctor_ids,HospitalId);
Log.wtf("URL Called", call.request().url() + "");
call.enqueue(new Callback<GetAppointmentDateModel>() {
#Override
public void onResponse(Call<GetAppointmentDateModel> call, Response<GetAppointmentDateModel> response) {
Log.e("response", new Gson().toJson(response.body()));
if (response.isSuccessful()) {
Log.e("response", new Gson().toJson(response.body()));
GetAppointmentDateModel getAppointmentDateModel = response.body();
ArrayList<GetData> getData = getAppointmentDateModel.getGetAppointmentList();
for (GetData getData1 : getData) {
String date1 = getData1.getDate();
String id=getData1.getId();
DateFormat inputFormatter = new SimpleDateFormat("dd MMM yyyy HH:mm-HH:mm");
Date date = null;
try {
date = inputFormatter.parse(date1);
DateFormat outputFormatter = new SimpleDateFormat("MM/dd/yyyy");
String output = outputFormatter.format(date);
getData2=new GetData(id,output);
getDataArrayList.add(getData2);
Log.d("dateString",output);
ArrayList<GetSlots> getSlots = getData1.getData();
for (GetSlots getSlots1 : getSlots) {
Id=getSlots1.getId();
SlotDate=getSlots1.getDate();
StartTime=getSlots1.getStartTime();
EndTime=getSlots1.getEndTime();
SloteTime=getSlots1.getSlotTime();
SlotBooked=getSlots1.getSlotBooked();
getSlots2=new GetSlots(Id,SlotDate,StartTime,EndTime,SlotBooked,SloteTime);
getSlotsArrayList.add(getSlots2);
}
} catch (ParseException e) {
e.printStackTrace();
}
}
String current_date=getData2.getDate();
if(current_date.equals(outputcurrentdate)) {
gridLayout.setAdapter(datetimeAdapter);
datetimeAdapter.notifyDataSetChanged();
}
}
// progressDialog.dismiss();
}
#Override
public void onFailure(Call<GetAppointmentDateModel> call, Throwable t) {
Log.d("error", t.getMessage());
// progressDialog.dismiss();
}
});
}
#Override
public void myItemClick(int position) {
}
}
Your list - getSlotsArrayList is addding new values each time and it is not clearing anywhere. This is the same list that is passed to the adapter. so it is displaying multiple values.
Call clear method before this
getSlotsArrayList.clear();
GetAppointmentDate(selecteddate);

How to get Native Module return value?

I want this promise value in App.js class with button click. Please help me in finding out the solution.
#ReactMethod
public void initTimerService(Promise promise)
{
TimerService timerService = App42API.buildTimerService();
String timerName = "<Enter_your_timer_name>";
long timeInSeconds= 120;
timerService.createOrUpdateTimer(timerName, timeInSeconds, new App42CallBack() {
public void onSuccess(Object r)
{
Log.e(TAG,"response = " + r);
Timer timer = (Timer)response;
promise.resolve(timer.getName());
System.out.println("Timer Name is: " + timer.getName());
System.out.println("Time is: " + timer.getTimeInSeconds());
}
});
}
public void initTimerService(Callback callback)
{
TimerService timerService = App42API.buildTimerService();
String timerName = "<Enter_your_timer_name>";
long timeInSeconds= 120;
timerService.createOrUpdateTimer(timerName, timeInSeconds, new
App42CallBack() {
public void onSuccess(Object r)
{
Log.e(TAG,"response = "+r);
Timer timer = (Timer)response;
promise.resolve(timer.getName());
System.out.println("Timer Name is: "+timer.getName());
System.out.println("Time is: "+timer.getTimeInSeconds());
callback.invoke(true);
}
});
}

How to get swimming data using samsung health app

I want to get swimming data from Samsung Health App but not get any proper solution.
Below is my code.
public class SwimmingReport {
private final HealthDataStore mStore;
private SwimObserver swimObserver;
private static final long ONE_DAY_IN_MILLIS = 24 * 60 * 60 * 1000L;
public SwimmingReport(HealthDataStore store) {
mStore = store;
}
public void start(SwimObserver listener, String strDate, JSONObject jsonObject) {
swimObserver = listener;
HealthDataObserver.addObserver(mStore, HealthConstants.Exercise.HEALTH_DATA_TYPE, new HealthDataObserver(null) {
#Override
public void onChange(String s) {
readTodaySwimData(strDate,jsonObject);
}
});
readTodaySwimData(strDate,jsonObject);
}
private void readTodaySwimData(String strDate,JSONObject jsonObject) {
HealthDataResolver resolver = new HealthDataResolver(mStore, null);
long startTime = GlobalMethods.getEpochTime(strDate);
long endTime = startTime + ONE_DAY_IN_MILLIS;
HealthDataResolver.ReadRequest request = new HealthDataResolver.ReadRequest.Builder()
.setDataType(HealthConstants.Exercise.HEALTH_DATA_TYPE)
.setProperties(new String[]{HealthConstants.Exercise.EXERCISE_TYPE})
.setLocalTimeRange(HealthConstants.Exercise.START_TIME, HealthConstants.Exercise.TIME_OFFSET,
startTime, endTime)
.build();
try {
resolver.read(request).setResultListener(result ->{
double distance = 0.0;
try {
for (HealthData data : result) {
distance += data.getFloat(HealthConstants.Exercise.DISTANCE);
}
} finally {
result.close();
}
if (swimObserver != null) {
swimObserver.onChanged(distance,strDate,jsonObject);
}
});
} catch (Exception e) {
Log.e("=> ", "Getting step count fails.", e);
}
}
public interface SwimObserver {
void onChanged(Double distance, String date, JSONObject jsonObject);
}
}
Here is my whole source code this
I figured out on your code that you want to read distance value from the read result.
distance += data.getFloat(HealthConstants.Exercise.DISTANCE);
But you described absolutely not related property. Maybe that is the problem.
.setProperties(new String[]{HealthConstants.Exercise.EXERCISE_TYPE})
Try this.
.setProperties(new String[]{HealthConstants.Exercise.DISTANCE})

Getting server time freezes and crashes my application

I am doing an app where I click the START button and get current time, and hitting STOP gets the time again. I´ve been using system time without any errors, recently I changed it to server time, which is in an Asynctask, but the app is unstable since, slowed down and exits without error messages, but on faster connections it can process. Any idea why? This is my code:
class getDST2 extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
try {
TimeTCPClient client = new TimeTCPClient();
try {
client.setDefaultTimeout(60000);
client.connect("time.nist.gov");
simpledate = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
do_casu = simpledate.format(client.getDate());
} finally {
client.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
getDSTdone = true;
}
}
Also doing a graphic timer of the current time since Start was clicked so I need to get server time every second inside a handler.. code:
handler.post(r = new Runnable() {
public void run() {
hasStartedtt2 = true;
calendar = Calendar.getInstance();
simpledate = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
new getDST2().execute(); // THIS IS THE ASynctask, returns the "do_casu" String
zaciatok_hour = zaciatok.substring(11, 13);
zaciatok_minute = zaciatok.substring(14, 16);
koniec_hour = do_casu.substring(11, 13);
koniec_minute = do_casu.substring(14, 16);
zaciatok_sekundy = zaciatok.substring(17, 19);
koniec_sekundy = do_casu.substring(17, 19);
final_hour = ((Integer.parseInt(koniec_hour) - Integer.parseInt(zaciatok_hour)));
final_minute = Integer.parseInt(koniec_minute) - Integer.parseInt(zaciatok_minute);
final_seconds = Integer.parseInt(koniec_sekundy) - Integer.parseInt(zaciatok_sekundy) - 1;
}
});
Handler is called every second.
ServerTimeThread sth = new ServerTimeThread();
sth.start();
from_time = simpledate.format(sth.time);
when you call 'sth.time',the thread just start and is still in progress.
'time' is remain uninitialized,it is init at end of thread
So when accessing 'time',it is null absolutely.
2 way for AsyncTask
Blocking operation:
public class NTPDateTask extends AsyncTask<Void,Void,Date> {
#Override
protected Date doInBackground(Void... voids) {
Date date=fetchYourDate();
//fetch your date here
return date;
}
}
then call
Date result = new NTPDateTask().execute().get();
Non-Blocking operation(Callback pattern):
public class NTPDateTask extends AsyncTask<Void,Void,Date> {
#Override
protected Date doInBackground(Void... voids) {
Date date = fetchYourDate();
//fetch your date here
return date;
}
#Override
protected void onPostExecute(Date date) {
//this is 'callback'
//do the thing you want when task finish
//onPostExecute is called when doInBackground finished,and it runs on UIThread
}
}
then
new NTPDateTask().execute();
EDIT:
class TCPTimeDisplayWorker implements Runnable {
static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
boolean isActive = true;
private Handler targetHandler;
public TCPTimeDisplayWorker(Handler targetHandler) {
//pass the handler ref here
this.targetHandler = targetHandler;
}
#Override
public void run() {
while (isActive) {
long startTime = System.currentTimeMillis();
Date date = fetchDateFromTCPClient();
//fetch Server Date here
String currentDateText = simpleDateFormat.format(date);
targetHandler.sendMessage(Message.obtain(targetHandler, 0, currentDateText));
long endTime = System.currentTimeMillis();
long lapse = endTime - startTime;
if (lapse < 1000) {
try {
Thread.sleep(1000 - lapse);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
Handler:
// Non-static inner class will hold outer-class reference,may risk in memory leak
static class MainHandler extends Handler {
private WeakReference<TextView> textViewWeakReference;
// declare as WeakRef to avoid memory leak
public MainHandler(Looper looper, WeakReference<TextView> textViewWeakReference) {
super(looper);
this.textViewWeakReference = textViewWeakReference;
}
#Override
public void handleMessage(Message msg) {
if (textViewWeakReference.get() != null) {
//handle the message from message queue here
String text = (String) msg.obj;
textViewWeakReference.get().setText(text);
}
}
}
then
// must use the same handler to send msg from Background thread and
// handle at Main Thread
// a handler create on a thread will bound to that thread
mainHandler = new MainHandler(Looper.getMainLooper(), new WeakReference<>(mTextViewSystemTime));
new Thread(new TCPTimeDisplayWorker(mainHandler)).start();
btw,CamelCase is the common naming convention in Java.
Hope these are helpful.

Long always returns -1

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.
}

Categories

Resources