To store DateTime value into php and mysql - java

I am working on how to put Date value into my PHP/MySQL using android's date picker.
I want to make a Sharing Parking lot application that owner can register one's parking place with its information like operating time. Then user can use it with choosing the beginning and ending points.
I searched a lot but need more specific information.
How can I save operating time slot into PHP/MySQL?
The following is my android java code.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.avtivity_date_time);
mText1 = (TextView) findViewById(R.id.text1);
mPickDate1 = (Button) findViewById(R.id.pickDate1);
mPickTime1 = (Button) findViewById(R.id.pickTime1);
mText2 = (TextView) findViewById(R.id.text2);
mPickDate2 = (Button) findViewById(R.id.pickDate2);
mPickTime2 = (Button) findViewById(R.id.pickTime2);
mPickDate1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDialog(DATE_DIALOG_ID_1);
}
});
mPickDate2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDialog(DATE_DIALOG_ID_2);
}
});
mPickTime1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDialog(TIME_DIALOG_ID_1);
}
});
mPickTime2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDialog(TIME_DIALOG_ID_2);
}
});
final Calendar c = Calendar.getInstance();
mYear1 = c.get(Calendar.YEAR);
mMonth1 = c.get(Calendar.MONTH);
mDay1 = c.get(Calendar.DAY_OF_MONTH);
mHour1 = c.get(Calendar.HOUR_OF_DAY);
mMinute1 = c.get(Calendar.MINUTE);
mYear2 = c.get(Calendar.YEAR);
mMonth2 = c.get(Calendar.MONTH);
mDay2 = c.get(Calendar.DAY_OF_MONTH);
mHour2 = c.get(Calendar.HOUR_OF_DAY);
mMinute2 = c.get(Calendar.MINUTE);
updateDisplay();
}
private void updateDisplay() {
mText1.setText(String.format("시작 : %d년 %d월 %d일 %d시 %d분", mYear1, mMonth1 + 1, mDay1, mHour1, mMinute1));
mText2.setText(String.format("종료 : %d년 %d월 %d일 %d시 %d분", mYear2, mMonth2 + 1, mDay2, mHour2, mMinute2));
}
private DatePickerDialog.OnDateSetListener mDateSetListener1 =
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mYear1 = year;
mMonth1 = monthOfYear;
mDay1 = dayOfMonth;
updateDisplay();
}
};
private DatePickerDialog.OnDateSetListener mDateSetListener2 =
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mYear2 = year;
mMonth2 = monthOfYear;
mDay2 = dayOfMonth;
updateDisplay();
}
};
private TimePickerDialog.OnTimeSetListener mTimeSetListener1 =
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mHour1 = hourOfDay;
mMinute1 = minute;
updateDisplay();
}
};
private TimePickerDialog.OnTimeSetListener mTimeSetListener2 =
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mHour2 = hourOfDay;
mMinute2 = minute;
updateDisplay();
}
};
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID_1:
return new DatePickerDialog(this, mDateSetListener1, mYear1, mMonth1, mDay1);
case TIME_DIALOG_ID_1:
return new TimePickerDialog(this, mTimeSetListener1, mHour1, mMinute1, false);
case DATE_DIALOG_ID_2:
return new DatePickerDialog(this, mDateSetListener2, mYear2, mMonth2, mDay2);
case TIME_DIALOG_ID_2:
return new TimePickerDialog(this, mTimeSetListener2, mHour2, mMinute2, false);
}
return null;
}
private Long getDateInMS(String stringDateTime) throws ParseException {
SimpleDateFormat simpledateformat1 = new SimpleDateFormat("yyyy MM dd hh mm");
SimpleDateFormat simpledateformat2 = new SimpleDateFormat("yyyy MM dd hh mm");
String formatdate1 = simpledateformat1.format("mYear1, mMonth1, mDay1, mHour1, mMinute1");
String formatdate2 = simpledateformat2.format("mYear12, mMonth2, mDay2, mHour2, mMinute2");
Date startdate = simpledateformat1.parse(formatdate1);
Date enddate = simpledateformat2.parse(formatdate2);
return null;
}

Related

I want to pass Date and Time I got using Datepicker Dialog and Timepicker Dialog to next Activity in Android studio

This is the Java code that Datepicker and Timepicker work. Those two are working properly so I want to send that selected date and time to the next activity(Doctor_Time_Picking_data_page.java)
Doctor_Time_Picking_page.java
public class Doctor_Time_Picking_page extends AppCompatActivity {
public static final String TEXT_TO_SEND ="com.example.dogapp.TEXT_TO_SEND";
private DatePickerDialog datePickerDialog;
private Button dateButton;
private Button timeButton;
private Bundle savedInstanceState;
private Button saveButton;
private String DATE;
//On Create method-------------------------------------------------------------------------------------------------------------------------
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctor_time_picking_page);
initDatePicker();
dateButton = findViewById(R.id.datePickerButton);
timeButton = findViewById(R.id.timeButton);
saveButton = findViewById(R.id.date_time_save_button);
Intent intent = new Intent(getApplicationContext(),Doctor_Time_Picking_data_page.class);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(intent);
}
});
}
//-----------------------------------------------------------------------------------------------------------------------------------
private Bundle initDatePicker()
{
DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener()
{
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day)
{
month = month + 1;
String date = makeDateString(day, month, year);
dateButton.setText(date);
}
};
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
int style = AlertDialog.THEME_HOLO_LIGHT;
datePickerDialog = new DatePickerDialog(this, style, dateSetListener, year, month, day);
datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
return null;
}
private String makeDateString(int day, int month, int year)
{
return getMonthFormat(month) + " " + day + " " + year;
}
private String getMonthFormat(int month)
{
if(month == 1)
return "JAN";
if(month == 2)
return "FEB";
if(month == 3)
return "MAR";
if(month == 4)
return "APR";
if(month == 5)
return "MAY";
if(month == 6)
return "JUN";
if(month == 7)
return "JUL";
if(month == 8)
return "AUG";
if(month == 9)
return "SEP";
if(month == 10)
return "OCT";
if(month == 11)
return "NOV";
if(month == 12)
return "DEC";
//default should never happen
return "JAN";
}
public void openDatePicker(View view)
{
datePickerDialog.setTitle("Select Date");
datePickerDialog.show();
}
//Time Button
int hour, minute;
public void popTimePicker(View view)
{
TimePickerDialog.OnTimeSetListener onTimeSetListener = new TimePickerDialog.OnTimeSetListener()
{
#Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute)
{
hour = selectedHour;
minute = selectedMinute;
timeButton.setText(String.format(Locale.getDefault(), "%02d:%02d",hour, minute));
}
};
TimePickerDialog timePickerDialog = new TimePickerDialog(this, /*style,*/ onTimeSetListener, hour, minute, true);
timePickerDialog.setTitle("Select Time");
timePickerDialog.show();
}
}
This is the page where I want to show the date and Time selected form my previous activity(Doctor_Time_Picking_page.java)
Doctor_Time_Picking_data_page.java:
public class Doctor_Time_Picking_data_page extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctor_time_picking_data_page);
Button Button1a = findViewById(R.id.doc_page4_btn1);
Button Button2a = findViewById(R.id.doc_page4_btn2);
Button Button3a = findViewById(R.id.doc_page4_btn3);
Dialog nDialog = new Dialog(this);
Button1a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Doctor_Time_Picking_data_page.this,Doctor_Appoinment_payment.class);
startActivity(intent);
}
});
Button2a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Doctor_Time_Picking_data_page.this,Doctor_Time_Picking_page.class);
startActivity(intent);
}
});
Button3a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
nDialog.setContentView(R.layout.activity_doctor_delete_popup_msg);
nDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Intent intent = new Intent(Doctor_Time_Picking_data_page.this,Doctor_delete_popup_msg.class);
startActivity(intent);
}
});
}
}
In my project there are three buttons those are Select Time, Select Date and save button when I select each button Datepicker and Timepicker dialogues appear when I select Date or time those Data is appearing on the Buttons I want to pass those data to my next activity which is Doctor_Time_Picking_data_page.java and display them to user. What I now want is I want to pass That data selected from those Pickers to next activity
You need to pass an intent extra to the other activity to get your result. Follow the steps:
Create a filed name date in your class:
private String date = "JAN 1 2022"; // I have given a sample date
You need to store the date inside the DateSetListener like this:
DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener()
{
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day)
{
month = month + 1;
date = makeDateString(day, month, year);
dateButton.setText(date);
}
};
You need to pass that date on the click of the save button:
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
intent.putExtra("date", date);
startActivity(intent);
}
});
Then you need to get that date on the other activity like this:
public class Doctor_Time_Picking_data_page extends AppCompatActivity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctor_time_picking_data_page);
String date = getIntent().getStringExtra("date", "");
// 👆 that is the date from the previous activity
...
});
...
}

java.lang.ClassCastException: Search cannot be cast to android.app.Activity

Hi does anyone know why i am getting this error in runtime? I am unsure how to resolve it and i am new to this. Please help! I have called the Search class in my MainActivity and my app crashes when i click on the button to open it.
Here is the code used to call the Search class:
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Search.class);
startActivity(intent);
}
});
And here is my Search class:
public class Search extends Fragment implements Filterable {
private FilterViewModel mViewModel;
private TextView fromMauritiusTheNearestTxt;
private TextView largestMagnitudeEarthquakeTxt;
private TextView deepestEarthquakeTxt;
private Button chooseByDateBtn;
private String startdateString, enddateString;
private final LatLng mauritiusLatLng = new LatLng(-20.2005136, 56.5541215);
List<String> alldates;
public List<ItemClass> mRssFeedModels;
private List<ItemClass> datafilteredlist;
public static Search newInstance() {
return new Search();
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
mViewModel = ViewModelProviders.of(this).get(FilterViewModel.class);
View root = inflater.inflate(R.layout.activity_search, container, false);
fromMauritiusTheNearestTxt = root.findViewById(R.id.from_mauritius_the_nearest_txt);
largestMagnitudeEarthquakeTxt = root.findViewById(R.id.largest_magnitude_earthquake_txt);
deepestEarthquakeTxt = root.findViewById(R.id.deepest_earthquake_txt);
chooseByDateBtn = root.findViewById(R.id.choose_by_data_btn);
alldates = new ArrayList<>();
;
mRssFeedModels = mRssFeedModels;
setNearestMagnitudeDeepest();
chooseByDateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder mydialog1 = new AlertDialog.Builder(getContext());
LayoutInflater inflater1 = LayoutInflater.from(getContext());
View myview1 = inflater1.inflate(R.layout.custom_date_range_filter, null);
mydialog1.setView(myview1);
final AlertDialog dialog1 = mydialog1.create();
dialog1.show();
final TextView startdatetxt = myview1.findViewById(R.id.start_date_txt);
final TextView enddatetxt = myview1.findViewById(R.id.end_date_txt);
startdatetxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);
final int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(),
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
SimpleDateFormat format = new SimpleDateFormat("dd MMM yyyy");
c.set(year, monthOfYear, dayOfMonth);
startdateString = format.format(c.getTime());
startdatetxt.setText(startdateString);
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
});
enddatetxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);
final int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(),
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
SimpleDateFormat format = new SimpleDateFormat("dd MMM yyyy");
c.set(year, monthOfYear, dayOfMonth);
enddateString = format.format(c.getTime());
enddatetxt.setText(enddateString);
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
});
Button datefilterbtn = myview1.findViewById(R.id.filterbtn);
datefilterbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(startdateString)) {
startdatetxt.setError("select date");
}
if (TextUtils.isEmpty(enddateString)) {
enddatetxt.setError("select ");
} else {
//setNearestMagnitudeDeepest();
alldates = getDates(startdateString, enddateString);
for (String date : alldates) {
System.out.println(date);
}
getFilter().filter(startdateString);
dialog1.dismiss();
}
}
});
}
});
return root;
}
// mathod used to set
//from Mauritius The Nearest in Textbox
//largest Magnitude Earthquake in Textbox
//deepest Earthquake in Textbox
public void setNearestMagnitudeDeepest() {
String fromMauritiusTheNearest = "";
String largestMagnitudeEarthquake = "";
String largestMagnitudeEarthquakeLocName = "";
String deepestEarthquakeLocName = "";
for (int i = 0; i < mRssFeedModels.size(); i++) {
if (Double.parseDouble(mRssFeedModels.get(i).lat) == findNearestDoubleInList()) {
fromMauritiusTheNearest = mRssFeedModels.get(i).getLocation();
System.out.println(mRssFeedModels.get(i).lat + "------------- " + findNearestDoubleInList() + " " + mRssFeedModels.get(i).getLocation());
}
}
double maxMagnitude = Double.MIN_VALUE;
for (int i = 0; i < mRssFeedModels.size(); i++) {
if (Double.parseDouble(mRssFeedModels.get(i).getMagnitude()) > maxMagnitude) {
maxMagnitude = Double.parseDouble(mRssFeedModels.get(i).getMagnitude());
largestMagnitudeEarthquakeLocName = mRssFeedModels.get(i).getLocation();
}
}
String maxDepthStr = null;
int maxDepth = Integer.MIN_VALUE;
for (int i = 0; i < mRssFeedModels.size(); i++) {
if (Integer.parseInt(mRssFeedModels.get(i).getDepth().replaceAll("[^0-9]", "")) > maxDepth) {
maxDepth = Integer.parseInt(mRssFeedModels.get(i).getDepth().replaceAll("[^0-9]", ""));
maxDepthStr = mRssFeedModels.get(i).getDepth();
deepestEarthquakeLocName = mRssFeedModels.get(i).getLocation();
}
}
largestMagnitudeEarthquake = String.valueOf(maxMagnitude);
fromMauritiusTheNearestTxt.setText(fromMauritiusTheNearest);
largestMagnitudeEarthquakeTxt.setText(largestMagnitudeEarthquake + " in " + largestMagnitudeEarthquakeLocName);
deepestEarthquakeTxt.setText(maxDepthStr + " in " + deepestEarthquakeLocName);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mViewModel = ViewModelProviders.of(this).get(FilterViewModel.class);
// TODO: Use the ViewModel
}
//method use to find nearest location from mauritius
private Double findNearestDoubleInList() {
Double answer = Double.parseDouble(mRssFeedModels.get(0).lat);
Double current = Double.MAX_VALUE;
for (int i = 0; i < mRssFeedModels.size(); i++) {
if (Math.abs(Double.parseDouble(mRssFeedModels.get(i).lat) - mauritiusLatLng.latitude) < current) {
answer = Double.parseDouble(mRssFeedModels.get(i).lat);
current = Math.abs(answer - mauritiusLatLng.latitude);
}
}
return answer;
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
datafilteredlist = mRssFeedModels;
} else {
List<ItemClass> filteredList = new ArrayList<>();
for (int i = 0; i < alldates.size(); i++) {
charString = alldates.get(i);
for (ItemClass row : mRssFeedModels) {
// name match condition. this might differ depending on your requirement
// here we are looking for name or phone number match
if (row.getDescription().toLowerCase().contains(charString.toLowerCase())) {
filteredList.add(row);
System.out.println("matched");
}
}
}
datafilteredlist = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = datafilteredlist;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults results) {
mRssFeedModels = (ArrayList<ItemClass>) results.values;
setNearestMagnitudeDeepest();
if (fromMauritiusTheNearestTxt.getText().toString().isEmpty()) {
final android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(getContext());
builder.setMessage("No record found on this date")
.setCancelable(false)
.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
public void onClick(#SuppressWarnings("unused") final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
mRssFeedModels = mRssFeedModels;
setNearestMagnitudeDeepest();
}
});
final android.app.AlertDialog alert = builder.create();
alert.show();
}
}
};
}
private static List<String> getDates(String dateString1, String dateString2) {
ArrayList<String> dates = new ArrayList<String>();
SimpleDateFormat df1 = new SimpleDateFormat("dd MMM yyyy");
Date date1 = null;
Date date2 = null;
try {
date1 = df1.parse(dateString1);
date2 = df1.parse(dateString2);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
while (!cal1.after(cal2)) {
//Date date=cal1.getTime();
//dates.add(cal1.getTime());
dates.add(df1.format(cal1.getTime()));
cal1.add(Calendar.DATE, 1);
}
return dates;
}
}
Your Search class is a Fragment, you cannot start it with the Intent.
Make Search to be Activity or switch between fragments using FragmentManager.
Intent intent = new Intent(MainActivity.this, Search.class);
The Intent constructor doesn't expect a Fragment class as a second Argument, Here you add Search.class which is a Fragment, but you need to have an Activity instead
Fragments can be loaded in activities using a Transaction, not an intent.

Textview is updated only after picking date twice

I'm using two text views in a dialog, one is for from date and another is for to date. Now when i click on from date text view the date picker dialog opens and when i select the date it is not updated in the text view, if i open the date picker again and select the date for the second time the date is updated in the text view. can any one figure out why it is not updated the first time.
public static void datePickerDialog(final Context context) {
dialog = new Dialog(context);
dialog.setContentView(R.layout.date_picker_dialog);
fromDateText = dialog.findViewById(R.id.from_date);
toDateText = dialog.findViewById(R.id.to_date);
fromDateText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
datePicker(context);
}
});
toDateText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
datePicker(context);
}
});
dialog.show();
fromDateText.setText(fromDate);
toDateText.setText(toDate);
}
public static void datePicker(Context context){
fromDatePicker = new DatePickerDialog(context, android.R.style.Theme_Holo_Light_Dialog_MinWidth
,fromDateListner, fromDay, fromMonth, fromYear);
simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
fromDatePicker.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
fromDatePicker.show();
fromDateListner = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
month+=1;
fromDate = dayOfMonth+"/"+month+"/"+year;
setDate();
}
};
}
private static void setDate() {
try {
dateFrom = simpleDateFormat.parse(fromDate);
dateTo = simpleDateFormat.parse(toDate);
} catch (ParseException e) {
e.printStackTrace();
}
fromDateText.setText(dateFrom.toString());
toDateText.setText(dateTo.toString());
}
fromDateListner is initialized after the dialog creation, so the first time the DatePickerDialog is created without listener.
Move the fromDateListner = new DatePickerDialog.OnDateSetListener() ... part before fromDatePicker = new DatePickerDialog(context ...
Can you try like this?
private static void setDate() {
try {
dateFrom = simpleDateFormat.parse(fromDate);
dateTo = simpleDateFormat.parse(toDate);
fromDateText.setText(dateFrom.toString());
toDateText.setText(dateTo.toString());
} catch (ParseException e) {
e.printStackTrace();
}
}
// Edit:
Check my code:
private void showDatePicker() {
final Calendar myCalendar = Calendar.getInstance();
DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int monthOfYear, int dayOfMonth) {
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
setDate(myCalendar.getTime());
}
};
if (getActivity() != null) {
new DatePickerDialog(getActivity(), date, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
}
private void setDate(Date time) {
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy", Locale.US);
editText.setText(sdf.format(time));
}
Try this code ..
take boolean variable for selected textview ...
change method like this way..
public class DialogActiivty extends AppCompatActivity {
private TextView fromDateText,toDateText;
private String fromDate,toDate;
private Dialog dialog;
private DatePickerDialog fromDatePicker;
private SimpleDateFormat simpleDateFormat;
private Calendar calendar;
private int year, month, day;
private boolean fromSelected=false,toSelected=true;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
datePickerDialog(DialogActiivty.this);
}
public void datePickerDialog(final Context context) {
calendar=Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
dialog = new Dialog(context);
dialog.setContentView(R.layout.date_picker_dialog);
fromDateText = dialog.findViewById(R.id.from_date);
toDateText = dialog.findViewById(R.id.to_date);
fromDateText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
toSelected=false;
fromSelected=true;
datePicker(context);
}
});
toDateText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fromSelected=false;
toSelected=true;
datePicker(context);
}
});
dialog.show();
// fromDateText.setText(fromDate);
// toDateText.setText(toDate);
}
public void datePicker(Context context){
fromDatePicker = new DatePickerDialog(context, android.R.style.Theme_Holo_Light_Dialog_MinWidth
,fromDateListner, year, month, day);
simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
fromDatePicker.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
fromDatePicker.show();
}
DatePickerDialog.OnDateSetListener fromDateListner = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
month+=1;
fromDate = dayOfMonth+"/"+month+"/"+year;
setDate(fromDate);
}
};
private void setDate(String fromDate) {
if (fromSelected) {
fromDateText.setText(fromDate);
}
if (toSelected) {
toDateText.setText(fromDate);
}
}
}

Datepicker dialog box does not open on click

When I run and click the button, it does not open the datapicker dialogbox. I am not able to find out what is incorrect. Please, any one can check and guide me where is the incorrect code in the program.
{
//Declaration for class
ButtonViews views;
dpListener dpListenerView;
// Declartion for member vairables
int day, month, x_year;
int hour;
int minute;
Calendar calendar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
views = new ButtonViews();
dpListenerView = new dpListener();
//ButtonListener
views.button_date.setOnClickListener(this);
views.button_time.setOnClickListener(this);
//
// pick up the default date using Calender class
calendar = GregorianCalendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.getDefault());
day = calendar.get(Calendar.DAY_OF_MONTH);
month = calendar.get(Calendar.MONTH);
x_year = calendar.get(Calendar.YEAR);
Log.i("DAY in Num....."," "+ month);
hour = calendar.get(Calendar.HOUR_OF_DAY);
minute = calendar.get(Calendar.MINUTE);
setupDate(day, month, x_year);
setupTime(hour, minute);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_date:
showDatePickerDialog();
break;
case R.id.button_time:
showTimePickerDialog();
break;
}
}
private void setupTime(int hours, int minutes) {
views.button_time.setText(hours + ":" + minutes);
}
private void setupDate(int day, int month, int year) {
String strMonth = ((month+1) <=9) ? ("0" + (month+1)) : String.valueOf(month+1);
views.button_date.setText(String.valueOf(day) + "/" + strMonth + "/" + String.valueOf(year));
}
private void showDatePickerDialog() {
DatePickerDialog datepickerdialog = new DatePickerDialog
(
this,
dpListenerView,
/* new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
} },*/
//this,
x_year,
month,
day
);
}
/* private OnDateSetListener dpListener = new OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
*//* day = dayOfMonth;
month = monthOfYear;
x_year = year;*//*
setupDate(dayOfMonth,monthOfYear,year);
}
};*/
public void showTimePickerDialog() {
TimePickerDialog timePickerDialog = new TimePickerDialog(
DateTimePickerActivity.this,
this,
hour,
minute,
true
);
calendar.set(Calendar.HOUR, hour);
calendar.set(Calendar.MINUTE, minute);
timePickerDialog.show();
}
// #Override
// public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
// setupDate(dayOfMonth,monthOfYear,year);
// }
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
setupTime(hourOfDay, minute);
}
class ButtonViews {
Button button_time;
Button button_date;
public ButtonViews() {
button_date = (Button) findViewById(R.id.button_date);
button_time = (Button) findViewById(R.id.button_time);
}
}
class dpListener implements OnDateSetListener
{
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
/* day = dayOfMonth;
month = monthOfYear;
x_year = year;*/
setupDate(dayOfMonth,monthOfYear,year);
}
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_date:
showDialog(999);// Method for Show Dialog. You can use any Int
break;
case R.id.button_time:
showDialog(99);
break;
}
}
and Define this method for Identified dialog from int.
#Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 999) {
return new DatePickerDialog(this, myDateListener, yr, month, day);
} else if (id == 99) {
return new TimePickerDialog(this, myTimeListener, h, m, true);
}
return null;
}
And there Listeners
// For Date Picker
private DatePickerDialog.OnDateSetListener myDateListener = new OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
day = dayOfMonth;
month = monthOfYear + 1;
yr = year;
Toast.makeText(
MainActivity.this,
new StringBuilder().append(day).append("-").append(month)
.append("-").append(yr), Toast.LENGTH_LONG).show();
}
};
// For TimePicker
private TimePickerDialog.OnTimeSetListener myTimeListener = new OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// TODO Auto-generated method stub
h = hourOfDay;
m = minute;
Toast.makeText(MainActivity.this,
new StringBuilder().append(h).append(":").append(m),
Toast.LENGTH_LONG).show();
}
};

Dates in all activity

Hi am using Date picker in more than three class with same validation. Instead I must write in one class and call that function in other classes when I required, is it possible Below code for Date picker.
public class MainActivity extends Activity {
private TextView tvDisplayDate;
private Button btnChangeDate;
private int myear;
private int mmonth;
private int mday;
static final int DATE_DIALOG_ID = 999;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setCurrentDateOnView();
addListenerOnButton();
}
// display current date
public void setCurrentDateOnView() {
tvDisplayDate = (TextView) findViewById(R.id.tvDate);
final Calendar c = Calendar.getInstance();
myear = c.get(Calendar.YEAR);
mmonth = c.get(Calendar.MONTH);
mday = c.get(Calendar.DAY_OF_MONTH);
// set current date into textview
tvDisplayDate.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(mmonth + 1).append("-").append(mday).append("-")
.append(myear).append(" "));
}
public void addListenerOnButton() {
btnChangeDate = (Button) findViewById(R.id.btnChangeDate);
btnChangeDate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
// set date picker as current date
DatePickerDialog _date = new DatePickerDialog(this, datePickerListener, myear,mmonth,
mday)
{
#Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
if (year < myear)
view.updateDate(myear, mmonth, mday);
if (monthOfYear < mmonth && year == myear)
view.updateDate(myear, mmonth, mday);
if (dayOfMonth < mday && year == myear && monthOfYear == mmonth)
view.updateDate(myear, mmonth, mday);
}
};
return _date;
}
return null;
}
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
myear = selectedYear;
mmonth = selectedMonth;
mday = selectedDay;
// set selected date into textview
tvDisplayDate.setText(new StringBuilder().append(mmonth + 1)
.append("-").append(mday).append("-").append(myear)
.append(" "));
Date dateObject1 = new Date(myear - 1900, mmonth, mday);
Date dateObj2 = new Date(System.currentTimeMillis());
if(dateObject1.before(dateObj2) || dateObject1.equals(dateObj2)){
//the program runs normally
}
else{
new AlertDialog.Builder(MainActivity.this)
.setTitle("Wrong Data Input!")
.setMessage("The end Date must be Before the start Date, please insert new Date values")
.setNeutralButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
}).show();
}
}
};
}
You could have a DateUtils class with a static method, which takes in the dates, along with the context. This method can do the date validations and build the AlertDialog accordingly. You can call this static method this way.
DateUtils.dateValidator(Date, Context);
This can be called in the onDateSet() of your OnDateSetListener for each DatePicker.

Categories