Android datepicker setmindate - android

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

Related

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.

Swiperefresh listview, updates but not how you would expect

I have a Listview that is using the swipefresh feature, and I've encountered a weird problem. When I swipe down, I see the animation and my information (updates behind the scenes.) However, I can't see the updated information, UNTIL I physically scroll down and back up again. The moment I scroll back up towards the top the old data is replaced with the new data.
swipe//
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
swipeLayout.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_green_light);
final TextView rndNum = (TextView) findViewById(R.id.timeStamp);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Log.i("Refreshing", " onRefresh called from SwipeRefreshLayout");
initiateRefresh();
}
});
Asynctask//
private void initiateRefresh() {
Log.i("iRefreshing", "initiateRefresh");
/**
* Execute the background task, which uses {#link android.os.AsyncTask} to load the data.
*/
new bgRefresh().execute();
}
private class bgRefresh extends AsyncTask<Void, Void, Boolean> {
static final int TASK_DURATION = 3 * 1000; // 3 seconds
#Override
protected Boolean doInBackground(Void... params) {
// Sleep for a small amount of time to simulate a background-task
try {
Thread.sleep(TASK_DURATION);
} catch (InterruptedException e) {
e.printStackTrace();
}
ArrayList<String> blah = new ArrayList<>();
try {
// Simulate network access
Calendar cal = Calendar.getInstance();
SimpleDateFormat month_date = new SimpleDateFormat("M");
String monthName = month_date.format(cal.getTime());
int lastDayOfMonth =(cal.getActualMaximum(Calendar.DAY_OF_MONTH));
int currentYear = Calendar.getInstance().get(Calendar.YEAR);
int year = Calendar.getInstance().get(Calendar.YEAR); ;
Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH);
cal.set(Calendar.DAY_OF_MONTH,1);
monthName = month_date.format(cal.getTime());
//String test = cal.getTime();
//start_date_monthly_statements=5/1/15&end_date_monthly_statements=5/27/15&activity_detail_type=all&reg_captcha=&display=
String startDateRecentActivity = monthName + "/1/" + currentYear;
String enddateRecentyActivity = monthName + "/" + lastDayOfMonth + "/" + currentYear;
///second calendar
Calendar cal2 = Calendar.getInstance();
cal2 = Calendar.getInstance();
// cal.add(Calendar.DAY_OF_MONTH, -5); //Go back to the previous month
webCreate web = new webCreate();
try {
//Clear and go.
Fields.clear();
Values.clear();
Fields.add("data1");
Values.add(datav1");
cal = Calendar.getInstance();
month_date = new SimpleDateFormat("MM-dd-yyyy hh:mma");
String date = month_date.format(cal.getTime());
date = date.replace("-", "/");
date = date.replace(" ", "\n");
refreshTS = (TextView) findViewById(R.id.timeStamp);
refreshTS.setText(date);
mMainListAdapter = new CustomListViewAdapter(getApplicationContext(), Fields, Values);
mAdapter.n
} catch (Exception e) {
e.printStackTrace();
return false;
}
Thread.sleep(2000);
} catch (InterruptedException e) {
return false;
}
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
mAdapter.notifyDataSetChanged();
// Tell the Fragment that the refresh has completed
onRefreshComplete(result);
}
}
private void onRefreshComplete(Boolean result) {
Log.i("LOG_TAG", "onRefreshComplete");
// Remove all items from the ListAdapter, and then replace them with the new items
//mListAdapter.clear();
//for (String cheese : result) {
// mListAdapter.add(cheese);
//}
// Stop the refreshing indicator
swipeLayout.setRefreshing(false);
}
What would or could cause this?
Looks like from my view of the code you have two adapters? mMainListAdapter and mAdapter? Since the data only appears when you scroll back, this means that you aren't properly notifying the adapter that you have updated the data. Call the notifyDatasetChanged() on the other adapter, since mMainListAdapter appears to be the main adapter.
You have to notify the adapter about the update with notifyDataSetChanged, or create a new adapter. This is on the method SwipeRefreshLayout.setOnRefreshListener. Follow this example:
https://www.bignerdranch.com/blog/implementing-swipe-to-refresh/
Edit
Since your last update I can see that mMainListAdapter is your adapter. Then in your onPostExecute set the adapter to the ListView.
myListView.setAdapter(mMainListAdapter);
Repleace myListView with your ListView

Run CountDownTimer on array of dates

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

SimpleDateFormatter returns date in wrong format

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

Unexpected side effects when parsing dates in Android

In various Android projects, I use the following static function to parse dates such as 1900-12-31. Of course, this function should be deterministic - but it turns out it is not. Why?
Normally, it parses the date 2010-10-30, for example, to the correct Date instance holding that value. But I have noticed that when I have an IntentService running at the same time and parsing some dates, this function parses the same date as above to 1983-01-20, which is one of the dates parsed in the IntentService. How can this happen?
public static Date dateFromString(String dateStr) {
SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
SimpleDateFormat mDateTimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.getDefault());
Date dateOut = null;
try {
if (dateStr != null) {
if (dateStr.length() == 7) {
if (dateStr.startsWith("--")) {
dateStr = "0000"+dateStr.substring(1);
}
}
else if (dateStr.length() == 6) {
if (dateStr.startsWith("-")) {
dateStr = "0000"+dateStr;
}
}
else if (dateStr.length() == 5) {
dateStr = "0000-"+dateStr;
}
else if (dateStr.matches("[0-9]{2}\\.[0-9]{2}\\.[0-9]{4}")) {
dateStr = dateStr.substring(6, 10)+"-"+dateStr.substring(3, 5)+"-"+dateStr.substring(0, 2);
}
else if (dateStr.matches("[0-9]{2}\\/[0-9]{2}\\/[0-9]{4}")) {
dateStr = dateStr.substring(6, 10)+"-"+dateStr.substring(3, 5)+"-"+dateStr.substring(0, 2);
}
else if (dateStr.matches("[0-9]{8}")) {
dateStr = dateStr.substring(0, 4)+"-"+dateStr.substring(4, 6)+"-"+dateStr.substring(6, 8);
}
if (dateStr.length() >= 20) {
String dateTimeStr = dateStr.trim();
if (dateTimeStr.endsWith("Z")) {
dateTimeStr = dateStr.substring(0, dateTimeStr.length()-1)+"+0000";
}
if (dateStr.charAt(10) == ' ') {
dateTimeStr = dateStr.substring(0, 10)+"T"+dateStr.substring(11);
}
try {
dateOut = mDateTimeFormat.parse(dateTimeStr);
}
catch (Exception e2) {
dateOut = mDateFormat.parse(dateStr);
}
}
else {
dateOut = mDateFormat.parse(dateStr);
}
}
}
catch (Exception e) {
dateOut = null;
}
return dateOut;
}
Edit: I do the parsing in my Activity's onCreate() where I start an AsyncTask that does the job. In the Activity's onStop(), a background service is started which does the same job. When I close the app (onStop()) and quickly restart it (onCreate()), both seem to be running simultaneously and the error occurrs.
The documentation of SimpleDateFormat says:
SimpleDateFormat is not thread-safe. Users should create a separate
instance for each thread.
There you go. Just create the SimpleDateFormat object separately in each thread and pass it to the method.

Categories

Resources