Error in Android Edittext Onclick Datepickerdialog in lollipop - java

I am using datepickerdialog. it run properly on kitkat but when i run application on lollipop and when i click on edit text it opens a datepickerdialog box but when i select date it give unfortunately stop error. Below is the code for datepicker on edittext.
private void setDateTimeField() {
fromLabel.setOnClickListener(this);
toLabel.setOnClickListener(this);
final DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); //yyyy/MM/dd HH:mm:ss
final Date date = new Date();
final String u = dateFormat.format(date);
Calendar newCalendar = Calendar.getInstance();
fromDatePickerDialog = new DatePickerDialog(this, new OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
from1 = dateFormatter.format(newDate.getTime());
diff1 = newDate.getTimeInMillis();
long d = date.getTime();
if((newDate.getTime()).equals(date)||(newDate.getTime()).after(date)){
long d1 = (diff1 / (24 * 60 * 60 * 1000) - d / (24 * 60 * 60 * 1000)) + 1;
if(d1>30){
total.setVisibility(View.VISIBLE);
total.setText("Booking not allowed as the Date given is outside Advance Booking Period");
avail.setVisibility(View.GONE);
}
else{
total.setVisibility(View.GONE);
fromLabel.setText(from1);
toLabel.setText(null);
to=null;
avail.setVisibility(View.GONE);
from=fromLabel.getText().toString();
}
}
else{
total.setVisibility(View.VISIBLE);
total.setText("Choose date after or equals to current date");
fromLabel.setText("");
toLabel.setText(null);
from=null;
to=null;
}
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
fromDatePickerDialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.Done), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
dialog.cancel();
if(type.equals("According to time"))
{
int cnt=-1;
if(from1.equals(u)){
cnt = 1;
loadTimeSpinnerDataATT(text,from,cnt);
}
else if(total.getText()=="Choose date after or equals to current date")
{
}
else if(total.getText()=="Booking not allowed as the Date given is outside Advance Booking Period")
{
}
else
{cnt = 0;
loadTimeSpinnerDataATT(text,from,cnt);
}
}
}
}
});
}
public void onClick(View view) {
if(view == fromLabel) {
fromDatePickerDialog.show();
} else if(view == toLabel) {
toDatePickerDialog.show();
}
}
public void onClose(DialogInterface dialogInterface)
{
}
}

Try it, may help you,
Date picker error resloved here
Link For Date picker
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import android.support.v7.app.ActionBarActivity;
import android.text.InputType;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
private int year;
private int month;
private int day;
static final int DATE_PICKER_ID = 1111;
// for date picker
EditText m3_DateDisplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
m3_DateDisplay = (EditText) findViewById(R.id.datepick);
// Get current date by calender
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
// Show selected date
StringBuilder dateValue1 = new StringBuilder().append(day).append("-")
.append(month + 1).append("-").append(year).append(" ");
// for Converting Correct Date format Save into Database
SimpleDateFormat sdf123 = new SimpleDateFormat("dd-MM-yyyy");
String abs1 = dateValue1.toString();
Date testDate1 = null;
try {
testDate1 = sdf123.parse(abs1);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat formatter1 = new SimpleDateFormat("dd-MM-yyyy");
String DateFormat = formatter1.format(testDate1);
m3_DateDisplay.setText(DateFormat);
m3_DateDisplay.setFocusable(false);
m3_DateDisplay.setInputType(InputType.TYPE_NULL);
m3_DateDisplay.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
showDialog(DATE_PICKER_ID);
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_PICKER_ID:
// open datepicker dialog.
// set date picker for current date
// add pickerListener listner to date picker
// return new DatePickerDialog(this, pickerListener, year, month,
// day);
// ///Only Show till Date Not More than That.
DatePickerDialog dialog = new DatePickerDialog(this,
pickerListener, year, month, day);
dialog.getDatePicker().setMaxDate(new Date().getTime());
return dialog;
}
return null;
}
private DatePickerDialog.OnDateSetListener pickerListener = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
#Override
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
// Show selected date
StringBuilder dateValue = new StringBuilder().append(day)
.append("-").append(month + 1).append("-").append(year)
.append(" ");
// for Converting Correct Date format Save into Database
SimpleDateFormat sdf123 = new SimpleDateFormat("dd-MM-yyyy");
String abs1 = dateValue.toString();
Date testDate1 = null;
try {
testDate1 = sdf123.parse(abs1);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat formatter1 = new SimpleDateFormat("dd-MM-yyyy");
String DateFormat = formatter1.format(testDate1);
m3_DateDisplay.setText(DateFormat);
}
};
}
change minimum api-11 in manifest

Related

set textview value after another two textview get value [duplicate]

This question already has answers here:
Android calculate days between two dates
(17 answers)
How to get number of days between two calendar instance?
(12 answers)
Closed 2 years ago.
i create a booking hotels apps and it hase 3 textview and 2 button to choose the date. if button click it display a date and selected date will displayed to 2 textview. how to display the day between dates in the third textview??
here's my code ( the third textview not displayed as day between dates)
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
tvDateResult = (TextView) findViewById(R.id.tv_dateresult);
res = findViewById(R.id.tv_dateresult1);
ress = findViewById(R.id.tv_dateresult2);
btDatePicker = (Button) findViewById(R.id.bt_datepicker);
date = findViewById(R.id.bt_datepicker1);
get = findViewById(R.id.getprice);
date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDateDialog2();
}
});
btDatePicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDateDialog();
}
});
}
private void showDateDialog2() {
Calendar newCalendar = Calendar.getInstance();
datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
res.setText(dateFormatter.format(newDate.getTime()));
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
datePickerDialog.show();
if(tvDateResult !=null || res !=null) {
try {
String a = tvDateResult.getText().toString();
String b = res.getText().toString();
Date aa = dateFormatter.parse(a);
Date bb = dateFormatter.parse(b);
long diff = bb.getTime() - aa.getTime() / 24 * 60 * 60 * 1000;
ress.setText((int) TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
private void showDateDialog(){
Calendar newCalendar = Calendar.getInstance();
datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
tvDateResult.setText(dateFormatter.format(newDate.getTime()));
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
datePickerDialog.show();
}
Declare 2 global variables:
Calendar date1 = null, date2 = null;
In onDateSet method of both date pickers, save the selected date in global variables.
In onDateSet of first date picker,
Calendar newDate = Calendar.getInstance();
date1 = newDate
updateTextView()
Similarly, In onDateSet of second date picker,
Calendar newDate = Calendar.getInstance();
date1 = newDate
updateTextView()
Call a method from both onDateSet methods.
private void updateTextView() {
if(date1 != null && date2 != null) {
tvDateResult .setText(dateFormatter.format(daysBetween(date1,date2)));
}
}
public static long daysBetween(Calendar startDate, Calendar endDate) {
// Make sure we don't change the parameter passed
Calendar newStart = Calendar.getInstance();
newStart.setTimeInMillis(startDate.getTimeInMillis());
newStart.set(Calendar.HOUR_OF_DAY, 0);
newStart.set(Calendar.MINUTE, 0);
newStart.set(Calendar.SECOND, 0);
newStart.set(Calendar.MILLISECOND, 0);
Calendar newEnd = Calendar.getInstance();
newEnd.setTimeInMillis(endDate.getTimeInMillis());
newEnd.set(Calendar.HOUR_OF_DAY, 0);
newEnd.set(Calendar.MINUTE, 0);
newEnd.set(Calendar.SECOND, 0);
newEnd.set(Calendar.MILLISECOND, 0);
long end = newEnd.getTimeInMillis();
long start = newStart.getTimeInMillis();
return TimeUnit.MILLISECONDS.toDays(Math.abs(end - start));
}
Reference: How to get number of days between two calendar instance?

Android Date Picker Fragment can not be set to Custom date

In here 'onClickListner' on 'Image Button' my custom 'DatePickerFragment' is displaying to select the date. Below is the code for
DatePickerFragment.java
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.widget.DatePicker;
import java.util.Calendar;
/**
* Created by Admin on 9/4/18.
*/
public class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
private onDatePickerListener mListener;
private boolean future;
public DatePickerFragment(){
}
// public DatePickerFragment(boolean future){
// this.future=future;
// }
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
Log.d("DATE_PICKER", " CURRENT_MONTH " + month);
int day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), R.style.AppBaseTheme,this, year, month, day);
if(isFuture() ==false){
datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis());
}
// Create a new instance of DatePickerDialog and return it
return datePickerDialog;
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
callListener(year, month, day);
}
public DialogFragment setCallbackListener(onDatePickerListener listener) {
mListener = listener;
return null;
}
private void callListener(int year, int month, int day) {
if (mListener != null) mListener.onDataSet(year, month, day);
}
public boolean isFuture() {
return future;
}
public void setFuture(boolean future) {
this.future = future;
}
public interface onDatePickerListener {
void onDataSet(int year, int month, int day);
}
}
Then I call this 'Fragment' in my 'MainActivity' to set the date to 'EditText' when click on the 'OK' button from the 'DatePickerFragment'.
MainActivity.java
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import com.sample.DatePickerFragment;
public class AddInterestedKarmaActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_interested_karma);
ButterKnife.bind(this);
context = this;
EditText dateEdittext = (Edittext)findViewById(R.id.date_edit);
setDate(dateEditText);
}
private void setDate(final EditText dateEditText){
datePickerFragment.setCallbackListener(new DatePickerFragment.onDatePickerListener() {
#Override
public void onDataSet(int year, int month, int day) {
int currentMonth = 0;
if (month == 0) {
currentMonth = 1;
} else if (month == 1) {
currentMonth = 2;
} else if (month == 2) {
currentMonth = 3;
} else if (month == 3) {
currentMonth = 4;
} else if (month == 4) {
currentMonth = 5;
} else if (month == 5) {
currentMonth = 6;
} else if (month == 6) {
currentMonth = 7;
} else if (month == 7) {
currentMonth = 8;
} else if (month == 8) {
currentMonth = 9;
} else if (month == 9) {
currentMonth = 10;
} else if (month == 10) {
currentMonth = 11;
} else if (month == 11) {
currentMonth = 12;
} else if (month == 12) {
}
dateEditText.setText(day + "/" + currentMonth + "/" + year);
}
});
}
DialogFragment datePicker = datePickerFragment;
datePicker.show(getSupportFragmentManager(), "datePicker");
}
private void setTime(final EditText timeEditText){
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(context,
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
String curTime = String.format("%02d:%02d", hourOfDay, minute);
timeEditText.setText(curTime);
}
}, mHour, mMinute, false);
timePickerDialog.show();
}
}
I need to set the Date of 'DatePickerFragmenet' for a custom date (not today). such as set the 'DatePickerFragment' onCreate() to the mentioned above final int y, m, d values that from 'dateEditText'. And also I need to set the custom 'time' to the 'TimePickerDialog' such as 'DatePickerFragment'.
There is one function in DatePickerDialog to set custom date(updateDate(year_, month_, day_))
According to your code you need to make changes in your DatePickerFragment
in onCreateDialog of DatePickerFragment where you are getting date, month and year from calendar, instead of getting that from Calendar provide your custom dates.
Updated class is below
public class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
private onDatePickerListener mListener;
private boolean future;
int day_;
int month_;
int year_;
private DatePickerDialog datePickerDialog;
public DatePickerFragment() {
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
// final Calendar c = Calendar.getInstance();
// int year = c.get(Calendar.YEAR);
// int month = c.get(Calendar.MONTH);
// Log.d("DATE_PICKER", " CURRENT_MONTH " + month);
// int day = c.get(Calendar.DAY_OF_MONTH);
datePickerDialog = new DatePickerDialog(getActivity(), R.style.AppTheme, this, year_, month_, day_);
if (isFuture() == false) {
datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis());
}
// datePickerDialog.updateDate(year_, month_, day_);
// Create a new instance of DatePickerDialog and return it
return datePickerDialog;
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
callListener(year, month, day);
}
public DialogFragment setCallbackListener(onDatePickerListener listener) {
mListener = listener;
return null;
}
private void callListener(int year, int month, int day) {
if (mListener != null) mListener.onDataSet(year, month, day);
}
public boolean isFuture() {
return future;
}
public void setFuture(boolean future) {
this.future = future;
}
public interface onDatePickerListener {
void onDataSet(int year, int month, int day);
}
}
In your activity, you need to provide custom date.
Updated Activity is below, you can add your custom date.
public class AddInterestedKarmaActivity extends AppCompatActivity {
DatePickerFragment datePickerDialog;
EditText dateEdittext;
String customDate = "12/12/2007"; //dd/mm/yy
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_interested_karma);
dateEdittext = (EditText) findViewById(R.id.date_edit);
// setDate(dateEditText);
datePickerDialog = new DatePickerFragment();
datePickerDialog.day_ = getDay();
datePickerDialog.month_ = getMonth();
datePickerDialog.year_ = getYear();
datePickerDialog.setCallbackListener(new DatePickerFragment.onDatePickerListener() {
#Override
public void onDataSet(int year, int month, int day) {
month = month + 1;
dateEdittext.setText(day + "/" + month + "/" + year);
}
}
);
datePickerDialog.show(getSupportFragmentManager(), "datePicker");
}
private int getYear() {
return Integer.parseInt(changeDateFormat(customDate, "MM/dd/yyyy", "YYYY"));
}
private int getMonth() {
return Integer.parseInt(changeDateFormat(customDate, "MM/dd/yyyy", "MM")) - 1; //substract one from month because month gets start from 0 in Calendar.
}
private int getDay() {
return Integer.parseInt(changeDateFormat(customDate, "MM/dd/yyyy", "dd"));
}
public String changeDateFormat(String dateString, String sourceDateFormat, String targetDateFormat) {
if (dateString == null || dateString.isEmpty())
return "";
SimpleDateFormat inputDateFromat = new SimpleDateFormat(sourceDateFormat, Locale.US);
Date date = new Date();
try {
date = inputDateFromat.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat outputDateFormat = new SimpleDateFormat(targetDateFormat, Locale.US);
return outputDateFormat.format(date);
}
}

Android Java show error message when user selects date before today

Below is my code of Datepicker allowing user to select dates and updates the textview with the selected date. How do I update the textview with an error message when user selects the date before today?
public void startCalender() {
txtTrigger = (TextView) findViewById(R.id.calTrigger);
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
myCalendar.set(Calendar.DAY_OF_MONTH, day);
myCalendar.set(Calendar.MONTH, month);
myCalendar.set(Calendar.YEAR, year);
updateLabel();
}
};
txtTrigger.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new DatePickerDialog(DisplayCeeAct.this, date,
myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
}
private void updateLabel() {
String no = "<font color='red'>NO</font>.";
String myFormat = "dd/MM/yy";
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.getDefault());
if (myCalendar.after(myCalendar.getTime())){
txtTrigger.setText(sdf.format(myCalendar.getTime()));
}
else {
txtTrigger.setText(Html.fromHtml(no), TextView.BufferType.SPANNABLE);
}
}
Seems this line is crashing:
txtTrigger.setText(Html.fromHtml(no), TextView.BufferType.SPANNABLE);
A better approach would be:
txtTrigger.setText("NO");
txtTrigger.setTextColor(Color.RED);

Change date displayed in button to DDth MMMM YY but keep values as DD/MM

I am using a DatePicker so that the user can select a date and find out the sunrise and sunset times for that particular date.
The webservice I am using requires the date to be snet in the following format dd/MM but I would like the button to show the date in the format DDth MMMM YYYY e.g 21st March 2013
Any advice on how I should I go about doing this?
Code below as requested:
public class SunriseSunset extends Activity implements OnClickListener {
public Button getLocation;
public Button setLocationJapan;
public TextView LongCoord;
public TextView LatCoord;
public double longitude;
public double latitude;
public LocationManager lm;
public Spinner Locationspinner;
public DateDialogFragment frag;
public Button date;
public Calendar now;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sunrisesunset);
//Date stuff
now = Calendar.getInstance();
date = (Button)findViewById(R.id.date_button);
date.setText(String.valueOf(now.get(Calendar.DAY_OF_MONTH)+1)+"-"+String.valueOf(now.get(Calendar.MONTH))+"-"+String.valueOf(now.get(Calendar.YEAR)));
date.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog();
}
});
}
// More date stuff
public void showDialog() {
FragmentTransaction ft = getFragmentManager().beginTransaction(); //get the fragment
frag = DateDialogFragment.newInstance(this, new DateDialogFragmentListener(){
public void updateChangedDate(int year, int month, int day){
date.setText(String.valueOf(day)+"-"+String.valueOf(month+1)+"-"+String.valueOf(year));
now.set(year, month, day);
}
}, now);
frag.show(ft, "DateDialogFragment");
}
public interface DateDialogFragmentListener{
//this interface is a listener between the Date Dialog fragment and the activity to update the buttons date
public void updateChangedDate(int year, int month, int day);
}
public void addListenerOnSpinnerItemSelection() {
Locationspinner = (Spinner) findViewById(R.id.Locationspinner);
Locationspinner
.setOnItemSelectedListener(new CustomOnItemSelectedListener(
this));
}
private class LongRunningGetIO extends AsyncTask<Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity)
throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n > 0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n > 0)
out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
// Finds todays date and adds that into the URL
SimpleDateFormat df = new SimpleDateFormat("dd/MM");
String formattedDate = df.format(now.getTime());
String finalURL = "http://www.earthtools.org/sun/"
+ LatCoord.getText().toString().trim() + "/"
+ LongCoord.getText().toString().trim() + "/"
+ formattedDate + "/99/0";
HttpGet httpGet = new HttpGet(finalURL);
String text = null;
try {
HttpResponse response = httpClient.execute(httpGet,
localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results != null) {
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
InputSource s = new InputSource(new StringReader(results));
Document doc = dBuilder.parse(s);
doc.getDocumentElement().normalize();
TextView tvSunrise = (TextView) findViewById(R.id.Sunrise);
TextView tvSunset = (TextView) findViewById(R.id.Sunset);
tvSunrise.setText(doc.getElementsByTagName("sunrise").item(0).getTextContent());
tvSunset.setText(doc.getElementsByTagName("sunset").item(0).getTextContent());
} catch (Exception e) {
e.printStackTrace();
}
}
Button b = (Button) findViewById(R.id.CalculateSunriseSunset);
b.setClickable(true);
}
}
class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
DateDialogFragment:
import java.util.Calendar;
import richgrundy.learnphotography.SunriseSunset.DateDialogFragmentListener;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.os.Bundle;
import android.widget.DatePicker;
public class DateDialogFragment extends DialogFragment {
public static String TAG = "DateDialogFragment";
static Context mContext; //I guess hold the context that called it. Needed when making a DatePickerDialog. I guess its needed when conncting the fragment with the context
static int mYear;
static int mMonth;
static int mDay;
static DateDialogFragmentListener mListener;
public static DateDialogFragment newInstance(Context context, DateDialogFragmentListener listener, Calendar now) {
DateDialogFragment dialog = new DateDialogFragment();
mContext = context;
mListener = listener;
mYear = now.get(Calendar.YEAR);
mMonth = now.get(Calendar.MONTH);
mDay = now.get(Calendar.DAY_OF_MONTH);
return dialog;
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new DatePickerDialog(mContext, mDateSetListener, mYear, mMonth, mDay);
}
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
mListener.updateChangedDate(year, monthOfYear, dayOfMonth);
}
};
}
Your help would be greatly appreciated.
Please ask questions for clarification if need =)
----------------UPDATE-------------------------
I'm getting there, updated code now looks like this:
public void showDialog() {
FragmentTransaction ft = getFragmentManager().beginTransaction(); //get the fragment
frag = DateDialogFragment.newInstance(this, new DateDialogFragmentListener(){
public void updateChangedDate(int year, int month, int day){
DateFormat format = new SimpleDateFormat("DD MM yyyy"); // could be created elsewhere
now.set(year, month, day);
date.setText(format.format(now.getTime()));
date.setText(String.valueOf(day)+"-"+String.valueOf(month+1)+"-"+String.valueOf(year));
now.set(year, month, day);
}
}, now);
frag.show(ft, "DateDialogFragment"); }
Just use another SimpleDateFormat to format it.
public void updateChangedDate(int year, int month, int day) {
DateFormat format = new SimpleDateFormat("DD MM YYYY"); // could be created elsewhere
now.set(year, month, day);
date.setText(format.format(now.getTime());
}
Unfortunately there is nothing provided by Java to automatically get the proper suffix for ordinal dates (2nd, 13*th*, 21st, etc.)
public void showDialog() {
FragmentTransaction ft = getFragmentManager().beginTransaction(); //get the fragment
frag = DateDialogFragment.newInstance(this, new DateDialogFragmentListener(){
public void updateChangedDate(int year, int month, int day){
now.set(year, month, day);
date.setText(DateFormat.format("dd MMMM yyyy", now));
}
}, now);
frag.show(ft, "DateDialogFragment"); }
Change
date.setText(String.valueOf(now.get(Calendar.DAY_OF_MONTH)+1)+"-"+String.valueOf(now.get(Calendar.MONTH))+"-"+String.valueOf(now.get(Calendar.YEAR)));
to
date.setText(DateFormat.format("dd MMMM yyyy", Calendar.getInstance()));
public void showDialog()
{
FragmentTransaction ft = getFragmentManager().beginTransaction(); //get the fragment
frag = DateDialogFragment.newInstance(this, new DateDialogFragmentListener()
{
public void updateChangedDate(int year, int month, int day)
{
String dateFormate = "dd'" + getDayOfMonthSuffix(day) +"' MM yyyy";
DateFormat format = new SimpleDateFormat(dateFormate); // could be created elsewhere
now.set(year, month, day);
date.setText(format.format(now.getTime()));
now.set(year, month, day);
}
}, now);
frag.show(ft, "DateDialogFragment");
}
String getDayOfMonthSuffix(final int n) {
checkArgument(n >= 1 && n <= 31), "illegal day of month: " + n);
if (n >= 11 && n <= 13) {
return "th";
}
switch (n % 10) {
case 1: return "st";
case 2: return "nd";
case 3: return "rd";
default: return "th";
}
}
I copy above getDayOfMonthSuffix function from the below link
getDayOfMonthSuffix

How to compare current time with time range?

I have two String variables - time1 and time2. Both contain value in the format HH:MM. How can I check:
If the current time is within
time1 and time2?
time1 will happen in the nearest
hour?
Upd.
I've implemented the following to convert time1 to Date format. But it uses depreciated methods:
Date clTime1 = new Date();
SimpleDateFormat timeParser = new SimpleDateFormat("HH:mm", Locale.US);
try {
clTime1 = timeParser.parse(time1);
} catch (ParseException e) {
}
Calendar now = Calendar.getInstance();
clTime1.setYear(now.get(Calendar.YEAR) - 1900);
clTime1.setMonth(now.get(Calendar.MONTH));
clTime1.setDate(now.get(Calendar.DAY_OF_MONTH));
System.out.println(clTime1.toString());
Convert the two strings to Date
objects (which are also time objects)
Create a new Date object.
This will
contain the current time.
Use the
Date.before() and Date.after() methods to determine if
you are in the time interval.
EDIT: You should be able to use this directly (and no deprecated methods)
public static final String inputFormat = "HH:mm";
private Date date;
private Date dateCompareOne;
private Date dateCompareTwo;
private String compareStringOne = "9:45";
private String compareStringTwo = "1:45";
SimpleDateFormat inputParser = new SimpleDateFormat(inputFormat, Locale.US);
private void compareDates(){
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR);
int minute = now.get(Calendar.MINUTE);
date = parseDate(hour + ":" + minute);
dateCompareOne = parseDate(compareStringOne);
dateCompareTwo = parseDate(compareStringTwo);
if ( dateCompareOne.before( date ) && dateCompareTwo.after(date)) {
//yada yada
}
}
private Date parseDate(String date) {
try {
return inputParser.parse(date);
} catch (java.text.ParseException e) {
return new Date(0);
}
}
This is what I used as simple function and it worked for me:
public static boolean isTimeWith_in_Interval(String valueToCheck, String startTime, String endTime) {
boolean isBetween = false;
try {
Date time1 = new SimpleDateFormat("HH:mm:ss").parse(startTime);
Date time2 = new SimpleDateFormat("HH:mm:ss").parse(endTime);
Date d = new SimpleDateFormat("HH:mm:ss").parse(valueToCheck);
if (time1.before(d) && time2.after(d)) {
isBetween = true;
}
} catch (ParseException e) {
e.printStackTrace();
}
return isBetween;
}
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
Date EndTime = dateFormat.parse("10:00");
Date CurrentTime = dateFormat.parse(dateFormat.format(new Date()));
if (CurrentTime.after(EndTime))
{
System.out.println("timeeee end ");
}
Don't forget to surrounded with a try catch block
if you want time between after 9PM to before 9Am you can use following condition..
if(cal.get(Calendar.HOUR_OF_DAY)> 20 || cal.get(Calendar.HOUR_OF_DAY)< 9)
{
// do your stuffs
}
Look into the Calendar class. It has the methods to support what you are asking. Date is deprecated and not recommended to use.
Here is the link to the API. Calendar
About the usage. First you need to call Calendar.getInstance() to create a calendar object.
Next you need to Set the two fields using cal.set(Calendar.HOUR, your hours) and Calendar.MINUTES the same way. Next you can call the compare function, before or after functions to get the desired info. Also you can get an instance with the current time in the current locale.
For example if you want to compare time between 11pm to 6am for calculating extra night fare for any vechicle. then following code will help you.
// Code
package com.example.timedate;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import android.os.Bundle;
import android.app.Activity;
import android.text.format.DateFormat;
import android.text.format.Time;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView tv;
Button bt;
int hour,min;
String AM_PM;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.textView1);
bt = (Button)findViewById(R.id.button1);
final String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());*/
bt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
min = c.get(Calendar.MINUTE);
int ds = c.get(Calendar.AM_PM);
if(ds==0)
AM_PM="am";
else
AM_PM="pm";
Toast.makeText(MainActivity.this, ""+hour+":"+min+AM_PM, Toast.LENGTH_SHORT).show();
if((hour==11&&AM_PM.matches("pm")) || (hour<7&&AM_PM.matches("am")) || (hour==12&&AM_PM.matches("am")))
{
Toast.makeText(MainActivity.this, "Time is between the range", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(MainActivity.this, "Time is not between the range", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}`
As of now, I am thinking about the following approach:
int clTime = Integer.parseInt(time1.substring(0, 1))*60 + Integer.parseInt(time1.substring(3, 4));
Time now = new Time();
now.setToNow();
int nowTime = now.hour*60 + now.minute;
So, I'll need to compare just integer values clTime and nowTime.
Try this if you have specific time Zone.
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("hh a");
Date timeseven = dateFormat.parse("7 AM");
Date timeTen = dateFormat.parse("10 AM");
Date timeOne = dateFormat.parse("1 PM");
Date timefour = dateFormat.parse("4 PM");
Date timefive = dateFormat.parse("10 PM");
//Get current time
// Date CurrentTime = dateFormat.parse(dateFormat.format(new Date()));
//Sample time
Date CurrentTime = dateFormat.parse("9 PM");
if (CurrentTime.after(timeseven) && CurrentTime.before(timeTen)) {
Toast.makeText(this, "FIRST", Toast.LENGTH_SHORT).show();
} else if (CurrentTime.after(timeTen) && CurrentTime.before(timeOne)) {
Toast.makeText(this, "Secound", Toast.LENGTH_SHORT).show();
} else if (CurrentTime.after(timeOne) && CurrentTime.before(timefour)) {
Toast.makeText(this, "THird", Toast.LENGTH_SHORT).show();
} else if (CurrentTime.after(timefour) && CurrentTime.before(timefive)) {
Toast.makeText(this, "Fourth", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Not found in your time zone", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
class TimeRange {
LocalTime from;
LocalTime to;
public TimeRange(LocalTime from, LocalTime to) {
this.from = from;
this.to = to;
}
public boolean isInRange(Date givenDate) {
LocalTime givenLocalTime = getLocalDateTime(givenDate).toLocalTime();
return givenLocalTime.isAfter(from) && givenLocalTime.isBefore(to);
}
public static LocalDateTime getLocalDateTime(Date date){
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
}
}

Categories