1

I have tried many questions posted here. Still I have not found solution to my problem,

I want to compare dates enter by user, in my android app, I store the dates in a ArrayList.

I dont want to store clone to already saved dates, so I have to check. I am using Java sql date to avoid time part.

static List<DatefromTo> myList;
myList = new ArrayList<Dateclassobject>();
i =myList.size();

for(int j = 1; j <= myList.size(); j ++){
    int results2 = myList.get(i).datefrom.compareTo(myList.get(j).datefrom);
    if(results2 > 0 ){
        Toast.makeText(getApplicationContext(),"First Date is after second",Toast.LENGTH_LONG).show();
    }else if(results2 < 0){
        Toast.makeText(getApplicationContext(), "Wrong", Toast.LENGTH_LONG).show();
    }else if(results2 == 0){
        Toast.makeText(getApplicationContext(),String.valueOf(myList.get(i).datefrom) + "------" + String.valueOf(myList.get(j).datefrom),Toast.LENGTH_LONG).show();
    }else{
        Toast.makeText(getApplicationContext(), "Hi", Toast.LENGTH_LONG).show();
    }
}

datefrom and dateto are stored in everyobject of Dateclassobject

So what I want to achieve is that if user has entered a time period from datefrom to dateto, and that time period is already present in another time period or is present in list itself it wont get enter again. So how can I check this at best?

Also I would like to know why getYear(), or getDate() give wrong answer?


Here is the DateClassObject code :

import java.util.Date;

public class DateClassObject {

    public static Date datefrom;
    public static Date dateto;

    public static Date difference;

    public DateClassObject() {
        super();
    }

    @SuppressWarnings("static-access")
    public DateClassObject(Date datefrom, Date dateto) {
        super();

        this.datefrom = datefrom;
        this.dateto = dateto;
    }
}

Below is the whole code of this class Dateadd , where I am doing everything

import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;

//import java.util.Date;

import java.util.List;


import android.app.Activity;
import android.app.DatePickerDialog;
import android.graphics.Color;
import android.os.Bundle;

import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;

import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;

import android.widget.TextView;
import android.widget.Toast;

public class DateAdd extends Activity {
    private Button buttonsubmit;

    DatePickerDialog dpdfrom, dpdto;

    Date dtFrom, dtTo;

    long milisto, milisfrom, days, diff;

    int i;

    Button delete;
    TableLayout stk;
    TextView tvadd, tvadd2, tvadd3, tvfrompick, tvtopick, t1v;

    String abc;
    DatefromTo datefromto, dtFT;

    int listSize;

    int mYearfrom, mMonthfrom, mDayfrom, mYearto, mMonthto, mDayto;

    static List<DateClassObject> myList;

    Calendar from;  // get the from date from user and store here
    Calendar to; // get the to date from user and store here

    EditText et;
    String datetoday, difference, string1, string2;

    Long bringto, bringfrom, between;
    boolean wrong;
    boolean entryremover;

    // boolean yrfm , mnfm , dyfm , yrto , mnto , dyto;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dateadd);

         from = Calendar.getInstance();

         to= Calendar.getInstance();

        final Calendar c = Calendar.getInstance();
        mYearfrom = c.get(Calendar.YEAR);
        mMonthfrom = c.get(Calendar.MONTH);
        mDayfrom = c.get(Calendar.DAY_OF_MONTH);

        mYearto = c.get(Calendar.YEAR);
        mMonthto = c.get(Calendar.MONTH);
        mDayto = c.get(Calendar.DAY_OF_MONTH);

        buttonsubmit = (Button) findViewById(R.id.buttonsubmit);

        et = (EditText) findViewById(R.id.et);

        // tvspecial = (TextView) findViewById(R.id.tvspecial);

        tvfrompick = (TextView) findViewById(R.id.tvfrompick);
        tvtopick = (TextView) findViewById(R.id.tvtopick);

        myList = new ArrayList<DateClassObject>();

        i = (myList.size()-1);

        init();

        if (entryremover == true) {

            delete.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    myList.remove(dtFT);

                }
            });
        }

        buttonsubmit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                dtFT = new DatefromTo(from,to);





                if(from.before(to)){

                    myList.add(dtFT);

                    AddEntry();
                }

                for(int j = 0; j < myList.size(); j ++){ //Note. you've written, 
                    //for(int j = 1; j <= myList.size(); j ++) , ArrayList index start from 0. you'll miss the first element. I hope it helps you in the future

                    Calendar dateFrom = myList.get(j).dateFrom;
                    Calendar dateTo = myList.get(j).dateTo;

                    if(isSameDay(from, dateFrom) && isSameDay(to, dateTo)){ // checking same period allready exists

                        Toast.makeText(getApplicationContext(),
                                "Already exist",
                                 Toast.LENGTH_LONG).show();
                    }
                    else{
                        // if it does not exists, I assume that you want to add it your arrayList
                        myList.add(new DatefromTo(from, to));
                    }

                    t1v.setText((myList.get(j).dateFrom
                            + "\n" + myList.get(j).dateTo + "\n"));

                }


                tvfrompick.setText("");

                tvtopick.setText("");









            }
        });



        tvfrompick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                dpdfrom.show();

            }
        });

        tvtopick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                dpdto.show();

            }
        });

        dpdfrom = new DatePickerDialog(this,
                new DatePickerDialog.OnDateSetListener() {

                    @Override
                    public void onDateSet(DatePicker view, int year,
                            int monthOfYear, int dayOfMonth) {

                        tvfrompick.setText(dayOfMonth + "-" + monthOfYear + 1
                                + "-" + year);

                        mDayfrom = dayOfMonth;
                        mMonthfrom = (monthOfYear);
                        mYearfrom = year;

                    //  dtFrom = new Date(mYearfrom - 1900, mMonthfrom,mDayfrom);


                        from.set(mYearfrom, mMonthfrom,
                                mDayfrom);
                    }
                }, mYearfrom, mMonthfrom, mDayfrom);

        dpdto = new DatePickerDialog(this,
                new DatePickerDialog.OnDateSetListener() {

                    @SuppressWarnings({ "deprecation", "deprecation" })
                    @Override
                    public void onDateSet(DatePicker view, int year,
                            int monthOfYear, int dayOfMonth) {

                        tvtopick.setText(dayOfMonth + "-" + monthOfYear + 1
                                + "-" + year);

                        mDayto = dayOfMonth;
                        mMonthto = (monthOfYear);
                        mYearto = year;


                    //  dtTo = new Date((mYearto - 1900), mMonthto, mDayto);
                        to.set( mYearto, mMonthto,  mDayto);

                    }
                }, mYearto, mMonthto, mDayto);


    }

    public boolean isSameDay(Calendar cal1, Calendar cal2) {
        if (cal1 == null || cal2 == null) {
            throw new IllegalArgumentException("null");
        }
        return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) &&
                cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
                cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR));
    }


    public void init() {
        stk = (TableLayout) findViewById(R.id.table_main);
        TableRow tbrow0 = new TableRow(this);
        TextView tv0 = new TextView(this);
        tv0.setText("From");
        tv0.setTextColor(Color.WHITE);
        tv0.setPadding(20, 10, 20, 10);
        tbrow0.addView(tv0);

        TextView tv1 = new TextView(this);
        tv1.setText(" To " + myList.size());
        tv1.setTextColor(Color.WHITE);
        tv1.setPadding(20, 10, 20, 10);
        tv1.getPaddingLeft();
        tbrow0.addView(tv1);
        // Button tv2 = new Button(this);
        // tv2.setText("Delete ");
        // tv2.getPaddingLeft();
        // //tv2.setTextColor(Color.WHITE);
        // tbrow0.addView(tv2);

        stk.addView(tbrow0);
    }

    public void AddEntry() {
        entryremover = true;
        TableRow tbrow = new TableRow(this);
        t1v = new TextView(this);
        // t1v.setText("From" + i);
        myList.get(myList.size() - 1);
        t1v.setTextColor(Color.WHITE);
        t1v.setGravity(Gravity.CENTER);
        t1v.setPadding(20, 10, 20, 10);
        tbrow.addView(t1v);

        delete = new Button(this);
        delete.setText("Delete");
        delete.setTextColor(Color.WHITE);
        delete.setGravity(Gravity.CENTER);
        delete.setPadding(20, 10, 20, 10);

        tbrow.addView(delete);

        stk.addView(tbrow);
    }

    public void removeEntry() {

    }
}
Aiman Batul
  • 144
  • 11
  • Do you want to check overlapping of dates?? and also why static variables?? – Prashant Jun 02 '15 at 05:30
  • Yes exactly. Suppose a user enter 2001-2005 , later enter 2002-2004. so second date is already present in first. but i know how to check this overlapping. logic wise. I dont know how to code it. becuase java sql date class methods compareto, or before and after seems not working. Kindly check my obove code. – Aiman Batul Jun 02 '15 at 05:30
  • Remove all the `static` from `DateClassObject`, use getter/setters then try again –  Jun 02 '15 at 05:31
  • i =myList.size(); which gives the size, you're doing myList.get(i).datefrom.compareTo(myList.get(j).datefrom); Now myList.size(); gives the last element in the list and you're comparing to your last element everytime. correct your logic – Drunken Daddy Jun 02 '15 at 05:32
  • I dont care about getter seeter and static things at this point RC. Thank u., Let me solve my issue first. – Aiman Batul Jun 02 '15 at 05:33
  • @ HeisenBerg, can you kindly guide me what should I code instead of this? – Aiman Batul Jun 02 '15 at 05:34
  • I think you should care, https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html "At the same time, you need a field to keep track of how many Bicycle objects have been created so that you know what ID to assign to the next one. **Such a field is not related to any individual object**, but to the class as a whole." –  Jun 02 '15 at 05:42
  • Thank u RC. Can I solve my problem at first please? I am stuck. – Aiman Batul Jun 02 '15 at 05:46
  • Why havent you implemented equals() and hashcode() methods in your DateClassObject class? You will also need to implement comparable< DateClassObject> interface. without these methods you cannot compare DateClassObject's – Hector Jun 02 '15 at 06:05

2 Answers2

1

Use Calendar instead of Date. (easier for me since I've most of what you're looking for, in a project that I'm working on)

List<DateClassObject> myList = new ArrayList<>();

Calendar from =  // get the from date from user and store here
Calendar to = // get the to date from user and store here

//to check 'from' is after 'to'

if(from.after(to)){
    // Do your operation
}

for(int j = 0; j < myList.size(); j ++){ //Note. you've written, for(int j = 1; j <= myList.size(); j ++) , ArrayList index start from 0. you'll miss the first element. I hope it helps you in the future

    Calendar dateFrom = myList.get(j).dateFrom;
    Calendar dateTo = myList.get(j).dateTo;

    if(isSameDay(from, dateFrom) && isSameDay(to, dateTo)){ // checking same period allready exists
        // if it exists Do operation
    }
    else{
        // if it does not exists, I assume, you want to add DateClassObject to your arrayList
        myList.add(new DateClassObject(from, to));
    }
}

public boolean isSameDay(Calendar cal1, Calendar cal2) {
    if (cal1 == null || cal2 == null) {
        throw new IllegalArgumentException("The dates must not be null");
    }
        return (cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH) &&
            cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
            cal1.get(Calendar.DAY_OF_MONTH) == cal2.get(Calendar.DAY_OF_MONTH));
}

public class DateClassObject {

    public Calendar dateFrom;
    public Calendar dateTo;

    public Date difference;

    public DateClassObject(Calendar dateFrom, Calendar dateTo) {
        this.dateFrom = dateFrom;
        this.dateTo = dateTo;
    }
}

I think this is what you're looking for. Regards

EDIT:

store the date selected in date picker to Calendar Instance like this.

int day = datePicker.getDayOfMonth();
int month = datePicker.getMonth();
int year =  datePicker.getYear();

Calendar from = Calendar.getInstance();
from.set(year, month, day);

EDIT:

ok, I've made some change to your button click, add the for loop inside the if Statement. if I assume correctly, you want to add to the arraylist only if fromDate is not before toDate and also if its not a duplicate entry

buttonsubmit.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {

        if(from.before(to)){

            boolean alreadyExists = false;
            for(int j = 0; j < myList.size(); j ++){ 

                Calendar dateFrom = myList.get(j).dateFrom;
                Calendar dateTo = myList.get(j).dateTo;

                if(isSameDay(from, dateFrom) && isSameDay(to, dateTo)){ // checking same period allready exists
                    alreadyExists = true;
                    break;
                }
            }
            if (alreadyExists){
                Toast.makeText(getApplicationContext(),
                            "Already exist",
                            Toast.LENGTH_LONG).show();
            }
            else{
                myList.add(new DateClassObject(from, to));
            }
        }
        tvfrompick.setText("");
        tvtopick.setText("");
    }
});

As for the remove button you've written in your code myList.remove(dtFT);. The remove method takes the position in the array list as a parameter(integer value.) myList.remove(2) removes the 2nd element from list. so figure out some way to get the position of the element you want to delete.

Drunken Daddy
  • 7,326
  • 14
  • 70
  • 104
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/79393/discussion-between-heisenberg-and-aiman-batul). – Drunken Daddy Jun 02 '15 at 08:03
  • Okay let me try this way. btw thank u so much for helping me out. and i exactly want this that no duplicate entry plus datefrom is always before dateto. – Aiman Batul Jun 02 '15 at 09:34
  • one thing more you have not said anything about myList that is Arraylist. is this fine? – Aiman Batul Jun 02 '15 at 09:36
  • read this topic http://stackoverflow.com/questions/14903145/what-is-the-difference-between-list-and-arraylist – Drunken Daddy Jun 02 '15 at 09:49
  • Checked about this array list . This whole program is taking dates, but if user enter a date before the given period it is saying already exist, although that does not exist. say 2008-2015, and if user later enter 2000-2002 it says already exist. – Aiman Batul Jun 02 '15 at 10:02
  • I think you did not change the isSameDay() method. I made some edit to my post a while ago – Drunken Daddy Jun 02 '15 at 10:08
0

You are going about this the hard way.

First of all, the java.sql.Date class does have a time-of-day, but pretends not to. As a subclass of java.util.Date, it inherits a time-of-day but sets that time-of-day to zero values (you can think of that as midnight). To quote the doc:

To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero…

Furthermore, that time-of-day is in UTC time zone. So if you are comparing date-time values for a locality, say Montréal, then you have a problem.

These are just a couple of many reasons to avoid the java.util.Date/.Calendar, java.sql.Date, and SimpleDateFormat classes. They are one of the weakest areas of the libraries bundled with Java.

Half-Open

One key idea in working with spans of time is how to compare. Generally, the best way is "Half-Open" where the beginning is inclusive while the ending is exclusive.

So a week would be defined as starting on a Monday and running up to, but not including, the next Monday.

diagram of week in Half-Open, going Monday to Monday

The first two months of this year would be January 1, 2015 to March 1, 2015.

In the diagram above, not the symbols for the comparison, >= versus < (without equals).

For simply collecting earliest and latest dates from the user, you may want to ignore Half-Open and instead use Closed (both beginning and ending are inclusive). If using date-time values, then you should understand Half-Open and look at Joda-Time’s Interval class. Either way, be sure to note your intention in your code’s comments.

Joda-Time

This is the kind of work you should leave to a decent date-time library rather than roll-your-own.

For Android that means the Joda-Time library. In Joda-Time you could go either of two ways: with or without time-of-day.

Date-Only

If you truly do not care about time-of-day and time zone, then see this Question, Determine Whether Two Date Ranges Overlap, for general idea without regard for any particular language or library.

In Joda-Time you can use the LocalDate class to represent date-only values.

If the user is entering a pair of date values to define a range, you really don't care about the range. Just compare each of the pair. If either lies outside your current range, then extend your current range to that date. Otherwise, ignore the input date.

LocalDate earliest = new LocalDate( 2015 , 6 , 1 );
LocalDate latest = new LocalDate( 2015 , 7 , 1 );

LocalDate inputLocalDate = new LocalDate( 2015 , 5 , 15 );
if ( inputLocalDate.isBefore( earliest ) ) {
    earliest = inputLocalDate ;  // Extend left-side of date range to earlier date.
} else if ( inputLocalDate.isAfter( latest ) ) {
    latest = inputLocalDate ;  // Extend right-side of date range to later date.
} else {
    // Else the input date is within the date range, inclusive ( Closed range '[]', rather than Half-Open '[)` ).
}

As you call this for each input, your date-range grows to include the earliest and the latest of any values. You question is not quite clear, but I gather this was your goal.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • I want to check date range if the new date enter is alreday clone of a previous date. Suppose a user enter 2001-2005 , later enter 2002-2004. so second date is already present in first. but i know how to check this overlapping. logic wise. I dont know how to code it. becuase java sql date class methods compareto, or before and after seems not working. Kindly check my obove code. – Aiman Batul Jun 03 '15 at 09:48