CellTable with Date Column - date

I am trying to build a CellTable Widget for time tracking. The first Column must represent all days for current month in following form
Fri, 1
Sat, 2
Sun, 3
Mon, 4
Tue, 5
…
etc. till the end of the month (28 -31 rows).
My code looks like that:
Column<Rec,String> dayColumn = new Column<Rec,String>(new TextCell())
{
#Override
public String getValue(Rec rec)
{
dayNr = DateTimeFormat.getFormat( "EE,d" ).format(new Date());
return dayNr;
}
};
table.addColumn(dayColumn, "Date");
So can I see in this Column only Today-date in all cells.
How can I get all days of the month (1...28/30/31) in this Column each in its own cell?

It would be ideal if you prepared the list of Rec items with a Date variable.
Declaring a Rec pojo with date
Class Rec{
Date date;
//getter and setters.
}
Populate list of Rec items
List<Rec> recItems = new ArrayList<Rec>();
Date now = new Date();
int nowMonth = now.getMonth();
int nowYear = now.getYear();
List<Date> listOfDatesInThisMonth = new ArrayList<Date>();
Date beginningOfMonth = new Date(nowYear,nowMonth,1);
Date beginningOfNextMonth = new Date(nowYear,nowMonth+1,1);
Date start = beginningOfMonth;
while(start.before(beginningOfNextMonth)){
listOfDatesInThisMonth.add(start);
start = new Date(nowYear,nowMonth,start.getDate()+1);
}
for(Date date:listOfDatesInThisMonth){
Rec recItem = new Rec();
recItem.setDate(date);
recItems.add(recItem );
}
Rendering
Column<Rec,String> dayColumn = new Column<Rec,String>(new TextCell())
{
#Override
public String getValue(Rec rec)
{
dayNr = DateTimeFormat.getFormat( "EE,d" ).format(rec.getDate());
return dayNr;
}
};

Something like this ??
private static String getMonthsString() {
StringBuffer buffer = new StringBuffer();
Date date = new Date() ;
int i = date.getMonth();
if(i==2)//feb {
for (int j = 0; j < 28; j++) {
buffer.append(DateTimeFormat.getFormat( "EE,d" ).format( new Date(new Date().getTime() + ((1000 * 60 * 60 * 24*j)))));
}
return buffer.toString();
}

In a Cell Table each row is one record. A month will have atleast 28 days. So you must build atleast 28 records and do setList or setData on the cell Table. A short code snippet is given below -
Date currentDate = new Date();
Map<Integer, String> daysMap = new HashMap<Integer, String>();
daysMap .put(0,"Sunday");
.
.
daysMap .put(6, "Saturday");
Map<Integer, Integer> monthMap = new HashMap<Integer, Integer>();
monthMap.put(0, 31);
.
.
monthMap.put(0, 31);
List<Rec> list = new ArrayList<Rec>();
for(int i=1;i <= monthMap.get(currentDate.getMonth());i++)
{
list.add(new Rec( daysMap.get(currentDate.getDay())+" , "+ i ));
}
Column<Rec,String> dayColumn = new Column<Rec,String>(new TextCell())
{
#Override
public String getValue(Rec rec)
{
return rec.getDayDateString(); // which returns Friday, 1 etc.
}
};
table.addColumn(dayColumn, "Date");
ListDataProvider<Rec> listDataProvider = new ListDataProvider<Rec>();
listDataProvider.addDataDisplay(table);
listDataProvider.setList( list );

You could get the dates of each month on the server side using java.util.Calendar

Showing a scrollable list for dates is horrible usability. I would suggest using a DatePickerCell instead. It uses a date picker, so that the user can just click on the date to choose it.

Related

is there a function to update database based on time

i'm working on an app that help doctors calculate the volume and dosage of drug and save the rest in the database(if there is a rest) and this drug have an expiration date so i want to delete the drug automatically after expiration ,i want help how to implement the function
DatabaseHelper databaseHelper=DatabaseHelper();
List<Medecine> medecineList2 = await databaseHelper.getMedecineList();
int count=medecineList2.length;
for (int i = 0; i < count; i++) {
DateTime now = DateTime.now();
DateTime tempDate = DateFormat("yyyy-MM-dd hh:mm:ss")
.parse(medecineList2[i].date_reliquat);
DateTime x = tempDate.add(Duration(minutes: medecineList2[i].stabilitie));
if(now.isAfter(x) ){
medecineList2[i].reliquat=0;
medecineList2[i].date_reliquat='';
await databaseHelper.updateMedecine(medecineList2[i]);
}
}

How correctly create string with formatted date? [duplicate]

I want a list of dates between start date and end date.
The result should be a list of all dates including the start and end date.
java.time Package
If you are using Java 8, there is a much cleaner approach. The new java.time package in Java 8 incorporates the features of the Joda-Time API.
Your requirement can be solved using the below code:
String s = "2014-05-01";
String e = "2014-05-10";
LocalDate start = LocalDate.parse(s);
LocalDate end = LocalDate.parse(e);
List<LocalDate> totalDates = new ArrayList<>();
while (!start.isAfter(end)) {
totalDates.add(start);
start = start.plusDays(1);
}
Back in 2010, I suggested to use Joda-Time for that.
Note that Joda-Time is now in maintenance mode. Since 1.8 (2014), you should use java.time.
Add one day at a time until reaching the end date:
int days = Days.daysBetween(startDate, endDate).getDays();
List<LocalDate> dates = new ArrayList<LocalDate>(days); // Set initial capacity to `days`.
for (int i=0; i < days; i++) {
LocalDate d = startDate.withFieldAdded(DurationFieldType.days(), i);
dates.add(d);
}
It wouldn't be too hard to implement your own iterator to do this as well, that would be even nicer.
Get the number of days between dates, inclusive.
public static List<Date> getDaysBetweenDates(Date startdate, Date enddate)
{
List<Date> dates = new ArrayList<Date>();
Calendar calendar = new GregorianCalendar();
calendar.setTime(startdate);
while (calendar.getTime().before(enddate))
{
Date result = calendar.getTime();
dates.add(result);
calendar.add(Calendar.DATE, 1);
}
return dates;
}
Streams
Edit: Joda-Time is now deprecated, changed the answer to use Java 8 instead.
Here is the Java 8 way, using streams.
List<LocalDate> daysRange = Stream.iterate(startDate, date -> date.plusDays(1)).limit(numOfDays).collect(Collectors.toList());
please find the below code.
List<Date> dates = new ArrayList<Date>();
String str_date ="27/08/2010";
String end_date ="02/09/2010";
DateFormat formatter ;
formatter = new SimpleDateFormat("dd/MM/yyyy");
Date startDate = (Date)formatter.parse(str_date);
Date endDate = (Date)formatter.parse(end_date);
long interval = 24*1000 * 60 * 60; // 1 hour in millis
long endTime =endDate.getTime() ; // create your endtime here, possibly using Calendar or Date
long curTime = startDate.getTime();
while (curTime <= endTime) {
dates.add(new Date(curTime));
curTime += interval;
}
for(int i=0;i<dates.size();i++){
Date lDate =(Date)dates.get(i);
String ds = formatter.format(lDate);
System.out.println(" Date is ..." + ds);
}
output:
Date is ...27/08/2010
Date is ...28/08/2010
Date is ...29/08/2010
Date is ...30/08/2010
Date is ...31/08/2010
Date is ...01/09/2010
Date is ...02/09/2010
Recommending date streams
In Java 9, you can use following new method, LocalDate::datesUntil:
LocalDate start = LocalDate.of(2017, 2, 1);
LocalDate end = LocalDate.of(2017, 2, 28);
Stream<LocalDate> dates = start.datesUntil(end.plusDays(1));
List<LocalDate> list = dates.collect(Collectors.toList());
The new method datesUntil(...) works with an exclusive end date, hence the shown hack to add a day.
Once you have obtained a stream you can exploit all the features offered by java.util.stream- or java.util.function-packages. Working with streams has become so simple compared with earlier approaches based on customized for- or while-loops.
Or if you look for a stream-based solution which operates on inclusive dates by default but can also be configured otherwise then you might find the class DateInterval in my library Time4J interesting because it offers a lot of special features around date streams including a performant spliterator which is faster than in Java-9:
PlainDate start = PlainDate.of(2017, 2, 1);
PlainDate end = start.with(PlainDate.DAY_OF_MONTH.maximized());
Stream<PlainDate> stream = DateInterval.streamDaily(start, end);
Or even simpler in case of full months:
Stream<PlainDate> februaryDates = CalendarMonth.of(2017, 2).streamDaily();
List<LocalDate> list =
februaryDates.map(PlainDate::toTemporalAccessor).collect(Collectors.toList());
With java 8
public Stream<LocalDate> getDaysBetween(LocalDate startDate, LocalDate endDate) {
return IntStream.range(0, (int) DAYS.between(startDate, endDate)).mapToObj(startDate::plusDays);
}
Something like this should definitely work:
private List<Date> getListOfDaysBetweenTwoDates(Date startDate, Date endDate) {
List<Date> result = new ArrayList<Date>();
Calendar start = Calendar.getInstance();
start.setTime(startDate);
Calendar end = Calendar.getInstance();
end.setTime(endDate);
end.add(Calendar.DAY_OF_YEAR, 1); //Add 1 day to endDate to make sure endDate is included into the final list
while (start.before(end)) {
result.add(start.getTime());
start.add(Calendar.DAY_OF_YEAR, 1);
}
return result;
}
With Lamma it looks like this in Java:
for (Date d: Dates.from(2014, 6, 29).to(2014, 7, 1).build()) {
System.out.println(d);
}
and the output is:
Date(2014,6,29)
Date(2014,6,30)
Date(2014,7,1)
public static List<Date> getDaysBetweenDates(Date startDate, Date endDate){
ArrayList<Date> dates = new ArrayList<Date>();
Calendar cal1 = Calendar.getInstance();
cal1.setTime(startDate);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(endDate);
while(cal1.before(cal2) || cal1.equals(cal2))
{
dates.add(cal1.getTime());
cal1.add(Calendar.DATE, 1);
}
return dates;
}
One solution would be to create a Calendar instance, and start a cycle, increasing it's Calendar.DATE field until it reaches the desired date. Also, on each step you should create a Date instance (with corresponding parameters), and put it to your list.
Some dirty code:
public List<Date> getDatesBetween(final Date date1, final Date date2) {
List<Date> dates = new ArrayList<Date>();
Calendar calendar = new GregorianCalendar() {{
set(Calendar.YEAR, date1.getYear());
set(Calendar.MONTH, date1.getMonth());
set(Calendar.DATE, date1.getDate());
}};
while (calendar.get(Calendar.YEAR) != date2.getYear() && calendar.get(Calendar.MONTH) != date2.getMonth() && calendar.get(Calendar.DATE) != date2.getDate()) {
calendar.add(Calendar.DATE, 1);
dates.add(new Date(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE)));
}
return dates;
}
You can also look at the Date.getTime() API. That gives a long to which you can add your increment. Then create a new Date.
List<Date> dates = new ArrayList<Date>();
long interval = 1000 * 60 * 60; // 1 hour in millis
long endtime = ; // create your endtime here, possibly using Calendar or Date
long curTime = startDate.getTime();
while (curTime <= endTime) {
dates.add(new Date(curTime));
curTime += interval;
}
and maybe apache commons has something like this in DateUtils, or perhaps they have a CalendarUtils too :)
EDIT
including the start and enddate may not be possible if your interval is not perfect :)
List<Date> dates = new ArrayList<Date>();
String str_date = "DD/MM/YYYY";
String end_date = "DD/MM/YYYY";
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date startDate = (Date)formatter.parse(str_date);
Date endDate = (Date)formatter.parse(end_date);
long interval = 1000 * 60 * 60; // 1 hour in milliseconds
long endTime = endDate.getTime() ; // create your endtime here, possibly using Calendar or Date
long curTime = startDate.getTime();
while (curTime <= endTime) {
dates.add(new Date(curTime));
curTime += interval;
}
for (int i = 0; i < dates.size(); i++){
Date lDate = (Date)dates.get(i);
String ds = formatter.format(lDate);
System.out.println("Date is ..." + ds);
//Write your code for storing dates to list
}
Like as #folone, but correct
private static List<Date> getDatesBetween(final Date date1, final Date date2) {
List<Date> dates = new ArrayList<>();
Calendar c1 = new GregorianCalendar();
c1.setTime(date1);
Calendar c2 = new GregorianCalendar();
c2.setTime(date2);
int a = c1.get(Calendar.DATE);
int b = c2.get(Calendar.DATE);
while ((c1.get(Calendar.YEAR) != c2.get(Calendar.YEAR)) || (c1.get(Calendar.MONTH) != c2.get(Calendar.MONTH)) || (c1.get(Calendar.DATE) != c2.get(Calendar.DATE))) {
c1.add(Calendar.DATE, 1);
dates.add(new Date(c1.getTimeInMillis()));
}
return dates;
}
With Joda-Time , maybe it's better:
LocalDate dateStart = new LocalDate("2012-01-15");
LocalDate dateEnd = new LocalDate("2012-05-23");
// day by day:
while(dateStart.isBefore(dateEnd)){
System.out.println(dateStart);
dateStart = dateStart.plusDays(1);
}
It's my solution.... very easy :)
This is simple solution for get a list of dates
import java.io.*;
import java.util.*;
import java.text.SimpleDateFormat;
public class DateList
{
public static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
public static void main (String[] args) throws java.lang.Exception
{
Date dt = new Date();
System.out.println(dt);
List<Date> dates = getDates("2017-01-01",dateFormat.format(new Date()));
//IF you don't want to reverse then remove Collections.reverse(dates);
Collections.reverse(dates);
System.out.println(dates.size());
for(Date date:dates)
{
System.out.println(date);
}
}
public static List<Date> getDates(String fromDate, String toDate)
{
ArrayList<Date> dates = new ArrayList<Date>();
try {
Calendar fromCal = Calendar.getInstance();
fromCal.setTime(dateFormat .parse(fromDate));
Calendar toCal = Calendar.getInstance();
toCal.setTime(dateFormat .parse(toDate));
while(!fromCal.after(toCal))
{
dates.add(fromCal.getTime());
fromCal.add(Calendar.DATE, 1);
}
} catch (Exception e) {
System.out.println(e);
}
return dates;
}
}
As of Java 9, you can use the datesUntil method on LocalDate:
public List<LocalDate> getDatesBetween(
LocalDate startDate, LocalDate endDate) {
return startDate.datesUntil(endDate)
.collect(Collectors.toList());
}
The LocalDateRange class in the ThreeTen-Extra library represents a range of dates, and can be used for this purpose:
LocalDateRange.ofClosed(startDate, endDate).stream().toList();
A tail-recursive version:
public static void datesBetweenRecursive(Date startDate, Date endDate, List<Date> dates) {
if (startDate.before(endDate)) {
dates.add(startDate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
calendar.add(Calendar.DATE, 1);
datesBetweenRecursive(calendar.getTime(), endDate, dates);
}
}
Enhancing one of the above solutions. As adding 1 day to end date sometimes adds an extra day beyond the end date.
public static List getDaysBetweenDates(Date startdate, Date enddate)
{
List dates = new ArrayList();
Calendar startDay = new GregorianCalendar();
calendar.setTime(startdate);
Calendar endDay = new GregorianCalendar();
endDay.setTime(enddate);
endDay.add(Calendar.DAY_OF_YEAR, 1);
endDay.set(Calendar.HOUR_OF_DAY, 0);
endDay.set(Calendar.MINUTE, 0);
endDay.set(Calendar.SECOND, 0);
endDay.set(Calendar.MILLISECOND, 0);
while (calendar.getTime().before(endDay.getTime())) {
Date result = startDay.getTime();
dates.add(result);
startDay.add(Calendar.DATE, 1);
}
return dates;
}
Here is my method for getting dates between two dates, including / w.o. including business days. It also takes source and desired date format as parameter.
public static List<String> getAllDatesBetweenTwoDates(String stdate,String enddate,String givenformat,String resultformat,boolean onlybunessdays) throws ParseException{
DateFormat sdf;
DateFormat sdf1;
List<Date> dates = new ArrayList<Date>();
List<String> dateList = new ArrayList<String>();
SimpleDateFormat checkformat = new SimpleDateFormat(resultformat);
checkformat.applyPattern("EEE"); // to get Day of week
try{
sdf = new SimpleDateFormat(givenformat);
sdf1 = new SimpleDateFormat(resultformat);
stdate=sdf1.format(sdf.parse(stdate));
enddate=sdf1.format(sdf.parse(enddate));
Date startDate = (Date)sdf1.parse( stdate);
Date endDate = (Date)sdf1.parse( enddate);
long interval = 24*1000 * 60 * 60; // 1 hour in millis
long endTime =endDate.getTime() ; // create your endtime here, possibly using Calendar or Date
long curTime = startDate.getTime();
while (curTime <= endTime) {
dates.add(new Date(curTime));
curTime += interval;
}
for(int i=0;i<dates.size();i++){
Date lDate =(Date)dates.get(i);
String ds = sdf1.format(lDate);
if(onlybunessdays){
String day= checkformat.format(lDate);
if(!day.equalsIgnoreCase("Sat") && !day.equalsIgnoreCase("Sun")){
dateList.add(ds);
}
}else{
dateList.add(ds);
}
//System.out.println(" Date is ..." + ds);
}
}catch(ParseException e){
e.printStackTrace();
throw e;
}finally{
sdf=null;
sdf1=null;
}
return dateList;
}
And the method call would be like :
public static void main(String aregs[]) throws Exception {
System.out.println(getAllDatesBetweenTwoDates("2015/09/27","2015/10/05","yyyy/MM/dd","dd-MM-yyyy",false));
}
You can find the demo code : Click Here
List<LocalDate> totalDates = new ArrayList<>();
popularDatas(startDate, endDate, totalDates);
System.out.println(totalDates);
private void popularDatas(LocalDate startDate, LocalDate endDate, List<LocalDate> datas) {
if (!startDate.plusDays(1).isAfter(endDate)) {
popularDatas(startDate.plusDays(1), endDate, datas);
}
datas.add(startDate);
}
Recursive solution
This will add all dates between two dates and It will add current dates and then new dates will be added based on loop condition.
private void onDateSet(){
Calendar endDate = Calendar.getInstance(),startDate = Calendar.getInstance();
startDate.set(currentYear,currentMonthOfYear,currentDayOfMonth);
endDate.set(inputYear,inputMonthOfYear,inputDayOfMonth);
datesToAdd(startDate,endDate);
}
//call for get dates list
private List<Date> datesToAdd(Calendar startDate,Calendar endDate){
List<Dates> datesLists = new List<>();
while (startDate.get(Calendar.YEAR) != endDate.get(Calendar.YEAR) ||
startDate.get(Calendar.MONTH) != endDate.get(Calendar.MONTH) ||
startDate.get(Calendar.DAY_OF_MONTH) != endDate.get(Calendar.DAY_OF_MONTH)) {
datesList.add(new Date(startDate.get(Calendar.YEAR), startDate.get(Calendar.MONTH), startDate.get(Calendar.DATE));
startDate.add(Calendar.DATE, 1);//increas dates
}
return datesList;
}

Calculate time and assign different backgrounds to textview according to time

Can anyone give me any recommendations as to how i should approach this properly?
Heres the problem, grab a beer first. My attempt to explain might require a cold one :)
I have a ListView that is being populated via JSON that its being downloaded from a server.
This listview has a pickup_time (String), I am calculating the difference in time between current time and pickup_time
What I am trying to do is load either a green, yellow or red circle image to the assigned pickup_time according to the difference in time I have calculated by using a textView and using textView.setBackgroundColor. in the ListView.
The ListView WAS working properly and displaying information correctly. I've recently only tried to add the green/yellow/red images to the corresponding pickup_time string and this is where its crashing and I need help.
Now for some Codes!
Heres is where I am populating the listView using an AsyncTask. If you notice, I have parse_ready_at(JobsArray, i1); This is where I am caluclating the time difference.
public class Jobs extends ListActivity {
String NEW_JOB = " ";
Vibrator vib;
boolean reloadOnResume;
TextView assigned;
static ProjectDebug LOGCAT = new ProjectDebug();
ProgressDialogManager pDialog = new ProgressDialogManager();
static String JOB, ON_TIME_PERFORMANCE;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
int PU_time_until_late;
int DEL_time_until_late;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jobs);
getWindow().setLayout (LayoutParams.FILL_PARENT /* width */ , LayoutParams.WRAP_CONTENT /* height */);
vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
assigned = (TextView) findViewById(R.id.assigned);
RELOAD = true;
Jobs.this.setTitle("My Jobs");
reloadOnResume = false;
VerifyDriverCredentials();
// selecting single ListView item
final ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long ide) {
vib.vibrate(40);
// Starting new intent
try { Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra("jobInfo", JOBS.getJSONObject(position).toString());
in.putExtra(pays, JOBS.getJSONObject(position).toString());
in.putExtra(customer_name, JOBS.getJSONObject(position).toString());
in.putExtra(job, JOBS.getJSONObject(position).toString());
in.putExtra(ready_at, JOBS.getJSONObject(position).toString());
in.putExtra(due_by, JOBS.getJSONObject(position).toString());
in.putExtra(customer_reference, JOBS.getJSONObject(position).toString());
in.putExtra(pieces, JOBS.getJSONObject(position).toString());
in.putExtra(weight, JOBS.getJSONObject(position).toString());
in.putExtra(signature_required, JOBS.getJSONObject(position).toString());
in.putExtra(acknowledged, JOBS.getJSONObject(position).toString());
in.putExtra(pickup_actual_datetime, JOBS.getJSONObject(position).toString());
// Pickup Info
in.putExtra(pickup_name, JOBS.getJSONObject(position).toString());
in.putExtra(pickup_addr1, JOBS.getJSONObject(position).toString());
in.putExtra(pickup_city, JOBS.getJSONObject(position).toString());
in.putExtra(pickup_state, JOBS.getJSONObject(position).toString());
in.putExtra(pickup_to_see, JOBS.getJSONObject(position).toString());
in.putExtra(pickup_room, JOBS.getJSONObject(position).toString());
in.putExtra(pickup_phone, JOBS.getJSONObject(position).toString());
in.putExtra(pickup_zip_postal, JOBS.getJSONObject(position).toString());
in.putExtra(pickup_special_instr, JOBS.getJSONObject(position).toString());
// Deliver Info
in.putExtra(deliver_name, JOBS.getJSONObject(position).toString());
in.putExtra(deliver_addr1, JOBS.getJSONObject(position).toString());
in.putExtra(deliver_city, JOBS.getJSONObject(position).toString());
in.putExtra(deliver_state, JOBS.getJSONObject(position).toString());
in.putExtra(deliver_zip_postal, JOBS.getJSONObject(position).toString());
in.putExtra(deliver_to_see, JOBS.getJSONObject(position).toString());
in.putExtra(deliver_room, JOBS.getJSONObject(position).toString());
in.putExtra(deliver_special_instr, JOBS.getJSONObject(position).toString());
in.putExtra(deliver_phone, JOBS.getJSONObject(position).toString());
startActivity(in);
Jobs.this.overridePendingTransition(R.anim.fadein, R.anim.fadeout);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void VerifyDriverCredentials() {
if (jobs_assigned == 0){
assigned.setVisibility(View.VISIBLE);
assigned.setText("You have no jobs assigned");
GetWindowParameters();
}
if (jobs_assigned > 0 && reloadOnResume == false) {
assigned.setVisibility(View.GONE);
new ParseJobs().execute();
}
}
public class ParseJobs extends AsyncTask<Void, Void, Void> {
String DEL_late = "del_late";
String PU_late = " pu_late";
int i1 = 0;
#Override
protected void onPreExecute() {
pDialog.showProgressDialog(Jobs.this, "Performing calculations", "Loading... Please Wait...");
}
#Override
protected Void doInBackground(Void... params) {
contactList = new ArrayList<HashMap<String, String>>();
// looping through All Contacts
try { for (i1 = 0; i1 < JOBS.length(); i1++) {
JobsArray = JOBS.getJSONObject(i1);
JOB = JobsArray.getString(job);
ON_TIME_PERFORMANCE = JobsArray.getString(on_time_performance);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(job, JobsArray.getString(job));
map.put(pays, JobsArray.getString(pays));
map.put(ready_at, JobsArray.getString(ready_at));
map.put(due_by, JobsArray.getString(due_by));
map.put(new_job, JobsArray.getString(new_job));
//map.put(PU_late, Integer.toString(PU_time_until_late));
//map.put(DEL_late, Integer.toString(DEL_time_until_late));
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
}
parse_ready_at(JobsArray, i1);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (JOB != null) { assigned.setText(""); }
else { assigned.setText("You have no jobs assigned"); }
GetWindowParameters();
/** Updating parsed JSON data into ListView */
ListAdapter adapter = new SimpleAdapter(Jobs.this, contactList, R.layout.list_item, new String[] { job, pays, ready_at, due_by, new_job, PU_late, DEL_late},
new int[] { R.id.job1, R.id.pays1, R.id.ready_at1, R.id.due_by1, R.id.newjob1, R.id.imageViewReadyAt, R.id.imageViewDueBy });
TextView imageViewReadyAt = (TextView) findViewById(R.id.imageViewReadyAt);
//Change color/answer/etc for textView_5
if ( PU_time_until_late > 60) { // if more than 60 minutes
imageViewReadyAt.setBackgroundResource(R.drawable.notification);
}
if ( PU_time_until_late < 60) { //if less than 60
imageViewReadyAt.setBackgroundResource(R.drawable.green_light);
}
if ( PU_time_until_late < 30) { // if less than 30
imageViewReadyAt.setBackgroundResource(R.drawable.yellow_light);
}
if ( PU_time_until_late < 1) { // if less than 1 minutes
imageViewReadyAt.setBackgroundResource(R.drawable.red_light);
}
setListAdapter(adapter);
pDialog.dismissProgressDialog(Jobs.this);
}
}
public void parse_ready_at(JSONObject JobsArray, int i1) {
String parse_ready_at_ARRAY;
String tracking_Number;
try { for (i1 = 0; i1 < JOBS.length(); i1++) {
JobsArray = JOBS.getJSONObject(i1);
parse_ready_at_ARRAY = JobsArray.getString(ready_at);
tracking_Number = JobsArray.getString(job);
//Example of ready_at String --> "ready_at": "07/25/2012 08:26:00 PM" we split time from date to get time only
SimpleDateFormat parserSDF = new SimpleDateFormat("M/d/yyyy hh:mm:ss a"); // <--- Correct format to read "lastLatitudeUpdate"
try { parserSDF.parse(parse_ready_at_ARRAY);
}
catch (ParseException e) { LOGCAT.DEBUG("JOBS parse_ready_at", "Error parsing tracking number = " + tracking_Number + " ready_at Array = " + parse_ready_at_ARRAY + " Error = " + e.toString()); }
/* ################################################
* #### DISSECTING READY_AT STRING ARRAY ###
* ################################################
*/
String[] dissect_ready_at_DATE_TIME = parse_ready_at_ARRAY.split(" "); // Splitting space between 07/25/2012 and 08:26:00 and PM
String get_ready_at_DATE = String.valueOf(dissect_ready_at_DATE_TIME[0]); // Set at 0 because we want date. 07-25-2012
String get_ready_at_TIME = String.valueOf(dissect_ready_at_DATE_TIME[1]); // Set at 1 because we want time. 08:26:00
String get_ready_at_AMPM = String.valueOf(dissect_ready_at_DATE_TIME[2]); // Set at 2 because we want AM PM.
/* ########################################################
* #### GETTING DATE FROM READY_AT STRING ARRAY ###
* ########################################################
*/
String[] dissect_ready_at_DATE = get_ready_at_DATE.split("/"); // Splitting the / between 07 and 25 and 2012 from 07/25/2012
int get_ready_at_MONTH = Integer.valueOf(dissect_ready_at_DATE[0]); // Set at 0 because we want month. 07
int get_ready_at_DAY = Integer.valueOf(dissect_ready_at_DATE[1]); // Set at 1 because we want day. 25
int get_ready_at_YEAR = Integer.valueOf(dissect_ready_at_DATE[2]); // Set at 2 because we want yeay. 2012
/* ########################################################
* #### GETTING TIME FROM READY_AT STRING ARRAY ###
* ########################################################
*/
String[] dissect_ready_at_TIME = get_ready_at_TIME.split(":"); // Splitting the : between 08 and 26 and 00
int get_ready_at_HOUR = Integer.valueOf(dissect_ready_at_TIME[0]); // Set at 0 because we want hour. 08
int get_ready_at_MINUTE = Integer.valueOf(dissect_ready_at_TIME[1]); // Set at 1 because we want minute. 26
/* ################################################################
* #### CONVERT HOUR FROM READY_AT STRING TO MILITARY TIME ###
* ################################################################
*/
int convert_ready_at_HOUR_to_military = 0; // By default, ready_at String is in 12 hour format. we need to fix it so it is military time.
if (get_ready_at_AMPM.contentEquals("PM")) { // Checking to see if ready_at String has a PM at the end
convert_ready_at_HOUR_to_military = get_ready_at_HOUR + 12; // If it does, add 12 so we can get military time
}
if (get_ready_at_HOUR == 12 & get_ready_at_AMPM.contentEquals("PM") ) {// If hour is set at 12 PM, leave it at 12
convert_ready_at_HOUR_to_military = 12;
}
if (get_ready_at_AMPM.matches("AM")) { // Do Nothing if its AM
convert_ready_at_HOUR_to_military = get_ready_at_HOUR + 0;
}
/* ############################################################
* #### GET THE CURRENT DATE/TIME FROM USERS DEVICE ###
* ############################################################
*/
int current_MONTH = Calendar.getInstance().get(Calendar.MONTH); // Get todays month
int current_DAY = Calendar.getInstance().get(Calendar.DAY_OF_MONTH); // Get todays date
int current_YEAR = Calendar.getInstance().get(Calendar.YEAR); // Get todays year
int current_HOUR = Calendar.getInstance().get(Calendar.HOUR_OF_DAY); // Get todays Hour in military format
int current_MINUTE = Calendar.getInstance().get(Calendar.MINUTE); // Get todays minute
int current_year_FIXUP = current_YEAR - 1900; // example, this year is 2013, subtract 1900 you get 113 which is what Date parameter is requesting
int get_ready_at_year_FIXUP = get_ready_at_YEAR - 1900;
int get_ready_at_MONTH_FIXUP = // * We dont need to fixup current_MONTH because java has already done so
get_ready_at_MONTH - 1; // <-- we subtract 1 because according to parameters, January starts at 0 and December is 11
/*
* How to use Date(int, int, int)
*
*
* *Parameters*
* - year the year, 0 is 1900.
* - month the month, 0 - 11.
* - day the day of the month, 1 - 31
*/
Date ready_at_time = new Date(get_ready_at_year_FIXUP, get_ready_at_MONTH_FIXUP, get_ready_at_DAY); // (2010, June, 20th) = (110, 5, 20) June is 5 instead of 6 because we start
Date current_time = new Date(current_year_FIXUP, current_MONTH, current_DAY); // January at 0 in Java. As for days, it starts at 1 like normal.
int days_between = Days.daysBetween(new DateTime(current_time), new DateTime(ready_at_time)).getDays(); // Get the difference in days of current date and ready_at date
int minutes_difference_in_days_between = days_between * 1440; // 1440 minutes = 1 day. multiply with the date difference of int days_between to get the minutes between those days.
/* ############################################################################
* #### FINAL OUTPUT OF CALCULATING TIMES FROM CURRENT AND READY_AT ###
* ############################################################################
*/
int current_TOTAL_MINUTES = current_HOUR * 60 + current_MINUTE; // Multiply hour by 60 to get the minutes in the hour = RIGHT NOW'S time in minute format
int ready_at_TOTAL_MINUTES = convert_ready_at_HOUR_to_military * 60 + get_ready_at_MINUTE + minutes_difference_in_days_between;
PU_time_until_late = ready_at_TOTAL_MINUTES - current_TOTAL_MINUTES;
LOGCAT.DEBUG("READY_AT " + tracking_Number,"'" + days_between + "'" + " days between today and when the package is scheduled for pickup");
LOGCAT.DEBUG("READY_AT " + tracking_Number, "ready_at String's time = " + parse_ready_at_ARRAY +
" Time now in Minutes = " + current_TOTAL_MINUTES +
" ready_at time in Minutes = " + ready_at_TOTAL_MINUTES +
" Minutes left to complete pickup = " + PU_time_until_late + "\n" + "\n" + "\n" + " ");
}
}
catch (Exception e) {
LOGCAT.DEBUG("Jobs", "Error Splitting/Converting ready_at Time");
}
}
public void GetWindowParameters() {
WindowManager.LayoutParams params = getWindow().getAttributes();
Jobs.this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
Jobs.this.getWindow().setBackgroundDrawableResource(R.drawable.listviewbackground);
/* params.x = 0;
params.height = 480;
params.width = 480;
params.y = 160; */
params.y = 160;
params.height = 600;
params.dimAmount = .70f;
Jobs.this.getWindow().setAttributes(params);
}
Heres the code to get the time difference **public void parse_ready_at()***WARNING* Im pretty sure there is a MUCH easier way to do this but, I'm new and dont know any better lol
public void parse_ready_at(JSONObject JobsArray, int i1) {
String parse_ready_at_ARRAY;
String tracking_Number;
try { for (i1 = 0; i1 < JOBS.length(); i1++) {
JobsArray = JOBS.getJSONObject(i1);
parse_ready_at_ARRAY = JobsArray.getString(ready_at);
tracking_Number = JobsArray.getString(job);
//Example of ready_at String --> "ready_at": "07/25/2012 08:26:00 PM" we split time from date to get time only
SimpleDateFormat parserSDF = new SimpleDateFormat("M/d/yyyy hh:mm:ss a"); // <--- Correct format to read "lastLatitudeUpdate"
try { parserSDF.parse(parse_ready_at_ARRAY);
}
catch (ParseException e) { LOGCAT.DEBUG("JOBS parse_ready_at", "Error parsing tracking number = " + tracking_Number + " ready_at Array = " + parse_ready_at_ARRAY + " Error = " + e.toString()); }
/* ################################################
* #### DISSECTING READY_AT STRING ARRAY ###
* ################################################
*/
String[] dissect_ready_at_DATE_TIME = parse_ready_at_ARRAY.split(" "); // Splitting space between 07/25/2012 and 08:26:00 and PM
String get_ready_at_DATE = String.valueOf(dissect_ready_at_DATE_TIME[0]); // Set at 0 because we want date. 07-25-2012
String get_ready_at_TIME = String.valueOf(dissect_ready_at_DATE_TIME[1]); // Set at 1 because we want time. 08:26:00
String get_ready_at_AMPM = String.valueOf(dissect_ready_at_DATE_TIME[2]); // Set at 2 because we want AM PM.
/* ########################################################
* #### GETTING DATE FROM READY_AT STRING ARRAY ###
* ########################################################
*/
String[] dissect_ready_at_DATE = get_ready_at_DATE.split("/"); // Splitting the / between 07 and 25 and 2012 from 07/25/2012
int get_ready_at_MONTH = Integer.valueOf(dissect_ready_at_DATE[0]); // Set at 0 because we want month. 07
int get_ready_at_DAY = Integer.valueOf(dissect_ready_at_DATE[1]); // Set at 1 because we want day. 25
int get_ready_at_YEAR = Integer.valueOf(dissect_ready_at_DATE[2]); // Set at 2 because we want yeay. 2012
/* ########################################################
* #### GETTING TIME FROM READY_AT STRING ARRAY ###
* ########################################################
*/
String[] dissect_ready_at_TIME = get_ready_at_TIME.split(":"); // Splitting the : between 08 and 26 and 00
int get_ready_at_HOUR = Integer.valueOf(dissect_ready_at_TIME[0]); // Set at 0 because we want hour. 08
int get_ready_at_MINUTE = Integer.valueOf(dissect_ready_at_TIME[1]); // Set at 1 because we want minute. 26
/* ################################################################
* #### CONVERT HOUR FROM READY_AT STRING TO MILITARY TIME ###
* ################################################################
*/
int convert_ready_at_HOUR_to_military = 0; // By default, ready_at String is in 12 hour format. we need to fix it so it is military time.
if (get_ready_at_AMPM.contentEquals("PM")) { // Checking to see if ready_at String has a PM at the end
convert_ready_at_HOUR_to_military = get_ready_at_HOUR + 12; // If it does, add 12 so we can get military time
}
if (get_ready_at_HOUR == 12 & get_ready_at_AMPM.contentEquals("PM") ) {// If hour is set at 12 PM, leave it at 12
convert_ready_at_HOUR_to_military = 12;
}
if (get_ready_at_AMPM.matches("AM")) { // Do Nothing if its AM
convert_ready_at_HOUR_to_military = get_ready_at_HOUR + 0;
}
/* ############################################################
* #### GET THE CURRENT DATE/TIME FROM USERS DEVICE ###
* ############################################################
*/
int current_MONTH = Calendar.getInstance().get(Calendar.MONTH); // Get todays month
int current_DAY = Calendar.getInstance().get(Calendar.DAY_OF_MONTH); // Get todays date
int current_YEAR = Calendar.getInstance().get(Calendar.YEAR); // Get todays year
int current_HOUR = Calendar.getInstance().get(Calendar.HOUR_OF_DAY); // Get todays Hour in military format
int current_MINUTE = Calendar.getInstance().get(Calendar.MINUTE); // Get todays minute
int current_year_FIXUP = current_YEAR - 1900; // example, this year is 2013, subtract 1900 you get 113 which is what Date parameter is requesting
int get_ready_at_year_FIXUP = get_ready_at_YEAR - 1900;
int get_ready_at_MONTH_FIXUP = // * We dont need to fixup current_MONTH because java has already done so
get_ready_at_MONTH - 1; // <-- we subtract 1 because according to parameters, January starts at 0 and December is 11
/*
* How to use Date(int, int, int)
*
*
* *Parameters*
* - year the year, 0 is 1900.
* - month the month, 0 - 11.
* - day the day of the month, 1 - 31
*/
Date ready_at_time = new Date(get_ready_at_year_FIXUP, get_ready_at_MONTH_FIXUP, get_ready_at_DAY); // (2010, June, 20th) = (110, 5, 20) June is 5 instead of 6 because we start
Date current_time = new Date(current_year_FIXUP, current_MONTH, current_DAY); // January at 0 in Java. As for days, it starts at 1 like normal.
int days_between = Days.daysBetween(new DateTime(current_time), new DateTime(ready_at_time)).getDays(); // Get the difference in days of current date and ready_at date
int minutes_difference_in_days_between = days_between * 1440; // 1440 minutes = 1 day. multiply with the date difference of int days_between to get the minutes between those days.
/* ############################################################################
* #### FINAL OUTPUT OF CALCULATING TIMES FROM CURRENT AND READY_AT ###
* ############################################################################
*/
int current_TOTAL_MINUTES = current_HOUR * 60 + current_MINUTE; // Multiply hour by 60 to get the minutes in the hour = RIGHT NOW'S time in minute format
int ready_at_TOTAL_MINUTES = convert_ready_at_HOUR_to_military * 60 + get_ready_at_MINUTE + minutes_difference_in_days_between;
PU_time_until_late = ready_at_TOTAL_MINUTES - current_TOTAL_MINUTES;
LOGCAT.DEBUG("READY_AT " + tracking_Number,"'" + days_between + "'" + " days between today and when the package is scheduled for pickup");
LOGCAT.DEBUG("READY_AT " + tracking_Number, "ready_at String's time = " + parse_ready_at_ARRAY +
" Time now in Minutes = " + current_TOTAL_MINUTES +
" ready_at time in Minutes = " + ready_at_TOTAL_MINUTES +
" Minutes left to complete pickup = " + PU_time_until_late + "\n" + "\n" + "\n" + " ");
}
}
catch (Exception e) {
LOGCAT.DEBUG("Jobs", "Error Splitting/Converting ready_at Time");
}
}
Basically I want those lights to resemble on-time, late etc... not looking to be fed with a golden spoon, just some guidance towards the right direction thats all. Thanks!
EDIT here is my stack trace I forgot to include. I am getting a null pointer exception in onPostExecute. I have declared the textView and already defined it in my onCreate. I believe I have already called it properly in my ListAdapter as well.
if ( PU_ time_until_late < 60) { imageViewReadyAt.setBackgroundColor (R.drawable.green_light); }
EDIT Okay, I figured out why I was getting a null exception when calling imageViewReadyAt Textview. That textview belongs to another XML that belongs in the custom list_item. Still could use some help though.
I'm not sure if it's a bug or what, but I've also had issues modifying the UI from onPostExecute(). To work around it I'll either call a method from there to the main activity and have that work with views, or use a handler and post a message to the proper activity that is using the UI thread.
To make sure I'm on the UI thread I usually use a handler message instead like so:
Handler handlerJobs = new jobsHandler();
public class jobsHandler extends Handler {
#Override
public void handleMessage(Message msg) {
switch(msg.arg1) {
case 1:
updateBackgroundColor(msg.arg2);
break;
default:
super.handleMessage(msg);
}
}
}
private void updateBackgroundColor(int dataPassedInMessage) {
if (JOB != null) {
assigned.setText("");
} else {
assigned.setText("You have no jobs assigned");
}
GetWindowParameters();
/** Updating parsed JSON data into ListView */
ListAdapter adapter = new SimpleAdapter(Jobs.this, contactList, R.layout.list_item, new String[] { job, pays, ready_at, due_by, new_job, PU_late, DEL_late},
new int[] { R.id.job1, R.id.pays1, R.id.ready_at1, R.id.due_by1, R.id.newjob1, R.id.imageViewReadyAt, R.id.imageViewDueBy });
TextView imageViewReadyAt = (TextView) findViewById(R.id.imageViewReadyAt);
//Change color/answer/etc for textView_5
if ( PU_time_until_late > 60) {
// if more than 60 minutes
imageViewReadyAt.setBackgroundResource(R.drawable.notification);
}
if ( PU_time_until_late < 60) {
//if less than 60
imageViewReadyAt.setBackgroundResource(R.drawable.green_light);
}
if ( PU_time_until_late < 30) {
// if less than 30
imageViewReadyAt.setBackgroundResource(R.drawable.yellow_light);
}
if ( PU_time_until_late < 1) {
// if less than 1 minutes
imageViewReadyAt.setBackgroundResource(R.drawable.red_light);
}
setListAdapter(adapter);
pDialog.dismissProgressDialog(Jobs.this);
}
}
And then to call it you would use:
#Override
protected void onPostExecute(Void result) {
Message updateBackground = new Message();
updateBackground.arg1 = 1;
updateBackground.arg2 = R.drawable.green_light; //or any int you need to pass
handlerJobs.sendMessage(updateBackground);
}
edit: updated the example so it should work with your code
I think the problem is you are setting background color instead of setting background image. Your image setting code should be as follows e.g. :
imageViewReadyAt.setBackgroundDrawable(R.drawable.green_light);

Want to compare the date with today's date and update the database.

I am trying to compare the userr entered date with today's date and update the database accordingly. This is how i am doing..
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("MM-dd-yyyy");
today = df.format(c.getTime());
//===================================================================
try{
ContentValues val1 = new ContentValues();
val1.put(CPUser.Data.TASK_TYPE, "Todays Task");
getContentResolver().update(CPUser.Data.CONTENT_URI, val1, CPUser.Data.TASK_DUE_DATE + "=" +"'"+today+"'",null);
ContentValues val2 = new ContentValues();
val2.put(CPUser.Data.TASK_TYPE, "Overdue Task");
getContentResolver().update(CPUser.Data.CONTENT_URI, val2, CPUser.Data.TASK_DUE_DATE + "<" +"'"+today+"'",null);
ContentValues val3 = new ContentValues();
val3.put(CPUser.Data.TASK_TYPE, "Active Task");
getContentResolver().update(CPUser.Data.CONTENT_URI, val3, CPUser.Data.TASK_DUE_DATE + ">" +"'"+today+"'",null);
}
Catch(Exception ex)
{ }
If you want to store dates as text in the database, you always have to use "yyyy-MM-dd" format, otherwise you would not be able to do comparisons other than equal ("="). What I do is to save all dates, times and timestamps as INT using Unix Epoch. This allows you to display dates in different formats (using locale for example) to display dates, without first parsing the date. It also allows any type of comparison (equals, greater than etc). The functions are straight forward:
public static long timestampFromUnixEpoch(long unixepoch) {
if (unixepoch == 0)
return 0;
return (unixepoch * 1000) - TimeZone.getDefault().getRawOffset();
}
public static long unixEpochFromTimestamp(long timestampMS) {
if (timestampMS == 0)
return 0;
return ((timestampMS + TimeZone.getDefault().getRawOffset()) / 1000);
}
public static long dateToUnixEpoch(Date date) {
if (date == null)
return 0;
return unixEpochFromTimestamp(date.getTime());
}
public static Date unixEpochToDate(long unixepoch) {
if (unixepoch == 0)
return null;
return new Date(timestampFromUnixEpoch(unixepoch));
}

get current date in dd-mm-yyyy format

how to get current date in DD-MM-YYYY format in BlackBerry
i have already tried the following, but it gives me output of 1318502493
long currentTime = System.currentTimeMillis() / 1000;
System.out.println("Current time in :" + currentTime);
private String pattern = "dd-MM-yyyy";
String dateInString =new SimpleDateFormat(pattern).format(new Date());
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
return formatter.format(new Date());
Check if you can use SimpleDateFormat. If you can, create an object of this class, and use it in order to format the return provided by System.currentTimeMillis(). Some code below:
import java.util.*;
import java.text.*;
public class DateTest {
public static String getCurrentTimeStamp() {
SimpleDateFormat formDate = new SimpleDateFormat("dd-MM-yyyy");
// String strDate = formDate.format(System.currentTimeMillis()); // option 1
String strDate = formDate.format(new Date()); // option 2
return strDate;
}
public static void main (String args[]) {
System.out.println(getCurrentTimeStamp());
}
}