How to set month and year with LocalDate? - java

I want change the month and year with these two numberpickers but I do not know how to change the date. What I want to do is this: when i click on OK button on BottomSheetDialog I want to set the month and year. Can you help me please? I tried but I couldn't find any solution on the internet. If you help me, I'll be appreciated. Thank you.
public class PlannerFragment extends Fragment implements CalendarAdapter.OnItemListener{
private TextView monthYearTextView;
private TextView monthYearPickerOKTextView;
private ImageView nextMonthImageView, previousMonthImageView;
private RecyclerView calendarRecyclerView;
private LocalDate selectedDate; /// tekrar buna bakılacak
private NumberPicker monthNumberPicker, yearNumberPicker;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getActivity().setTitle("Planner");
View v = inflater.inflate(R.layout.fragment_planner, container, false);
previousMonthImageView = v.findViewById(R.id.previous_month_image_view);
nextMonthImageView = v.findViewById(R.id.next_month_image_view);
calendarRecyclerView = v.findViewById(R.id.calendar_recycler_view);
monthYearTextView = v.findViewById(R.id.month_year_text_view);
selectedDate = LocalDate.now();
setMonthYear();
previousMonthImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedDate = selectedDate.minusMonths(1);
setMonthYear();
}
});
nextMonthImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedDate = selectedDate.plusMonths(1);
setMonthYear();
}
});
monthYearTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
monthYearPicker(v);
}
});
return v;
}
private void setMonthYear() {
monthYearTextView.setText(monthYearFromDate(selectedDate));
ArrayList<String> daysInMonth = daysInMonthArray(selectedDate);
CalendarAdapter calendarAdapter = new CalendarAdapter(getActivity(), daysInMonth,
this);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getActivity(), 7);
calendarRecyclerView.setLayoutManager(layoutManager);
calendarRecyclerView.setAdapter(calendarAdapter);
}
private ArrayList<String> daysInMonthArray(LocalDate date) {
ArrayList<String> daysInMonthList = new ArrayList<>();
YearMonth yearMonth = YearMonth.from(date);
int daysInMonth = yearMonth.lengthOfMonth();
LocalDate firstDayOfMonth = selectedDate.withDayOfMonth(1);
int dayOfWeek = firstDayOfMonth.getDayOfWeek().getValue();
if (dayOfWeek == 7){
dayOfWeek = 1;
} else {
dayOfWeek++;
}
for (int i = 1; i <= 42; i++) {
if (i < dayOfWeek || i >= daysInMonth + dayOfWeek){
daysInMonthList.add("");
} else {
daysInMonthList.add(String.valueOf(i - dayOfWeek + 1));
}
}
return daysInMonthList;
}
private String monthYearFromDate(LocalDate localDate) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM yyyy");
return localDate.format(formatter);
}
#Override
public void onItemClick(int position, String dayText) {
LocalDate firstDayOfMonth = selectedDate.withDayOfMonth(1);
int dayOfWeek = firstDayOfMonth.getDayOfWeek().getValue();
if (dayOfWeek == 7){
dayOfWeek = 1;
} else {
dayOfWeek++;
}
if (!dayText.equals("")){
/*Toast.makeText(getActivity(), dayText + " " + monthYearFromDate(selectedDate),
Toast.LENGTH_SHORT).show();*/
Toast.makeText(getActivity(), String.valueOf(dayOfWeek),
Toast.LENGTH_SHORT).show();
}
}
public void monthYearPicker(View v){
BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(getActivity(),
R.style.BottomSheetDialogTheme);
View bottomSheetView = LayoutInflater.from(getActivity())
.inflate(R.layout.month_and_year_picker_bottom_sheet_layout,
(ConstraintLayout) v.findViewById(R.id.month_year_picker_bottom_sheet_container));
monthNumberPicker = bottomSheetView.findViewById(R.id.month_number_picker);
yearNumberPicker = bottomSheetView.findViewById(R.id.year_number_picker);
final Calendar calendar = Calendar.getInstance();
Month.initMonths();
monthNumberPicker.setMinValue(0);
monthNumberPicker.setMaxValue(Month.getMonthArrayList().size() - 1);
monthNumberPicker.setDisplayedValues(Month.monthNames());
monthNumberPicker.setValue(calendar.get(Calendar.MONTH));
yearNumberPicker.setMinValue(1984);
yearNumberPicker.setMaxValue(2040);
yearNumberPicker.setValue(calendar.get(Calendar.YEAR));
bottomSheetView.findViewById(R.id.month_year_picker_ok_text_view).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bottomSheetDialog.dismiss();
selectedDate.withMonth(monthNumberPicker.getValue());
setMonthYear();
Toast.makeText(getActivity(), Month.getMonthArrayList().get(monthNumberPicker.getValue()).getName(),
Toast.LENGTH_SHORT).show();
}
});
bottomSheetDialog.setContentView(bottomSheetView);
bottomSheetDialog.show();
}
}

Good implementation, proper updated answer:
LocalDate date1 = LocalDate.of(2021, Month.JANUARY, 1);
LocalDate date2 = date1.withYear(2010);
LocalDate date3 = date2.withMonth(Month.DECEMBER.getValue());
LocalDate date4 = date3.withDayOfMonth(15);
LocalDate date5 = date4.with(ChronoField.DAY_OF_YEAR, 100);
Stolen from https://kodejava.org/how-do-i-manipulate-the-value-of-localdate-object/
Bad outdated implementation, bad answer (just here for protocol)
Simple pure Java implementation:
Use Calendar. Create a new instance; you probably want Gregorian Calendar: Calendar.getInstance();
Set the calendar value to the date: cal.setTime(pDate);
adjust single fields: cal.add(pField, pValue); or cal.set(pField, pValue);
retrieve Date object: cal.getTime();
You could also use the new java.time package, with classes like LocalDateTime etc.
And then there's a myriad of Java Date Time libraries out there.
Choose the way that works best for you.

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.

how to compare date and not display feauter week date in android

public class TestActvity extends AppCompatActivity implements View.OnClickListener {
Button next;
Button previous;
TextView textView;
int interval = 2;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
next = (Button) findViewById(R.id.next);
previous = (Button) findViewById(R.id.previous);
next.setOnClickListener(this);
previous.setOnClickListener(this);
textView = (TextView) findViewById(R.id.textView);
getDate(interval);
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.next)
{
interval = interval + 7;
getDate(interval);
} else if (view.getId() == R.id.previous) {
interval = interval - 7;
getDate(interval);
}
}
public void getDate(int interval) {
try {
Calendar c = GregorianCalendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
c.add(Calendar.DAY_OF_WEEK, interval - 2);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
String startDate = "", endDate = "";
startDate = df.format(c.getTime());
c.add(Calendar.DATE, 6);
endDate = df.format(c.getTime());
textView.setText(startDate + " to " + endDate);
Date date = new Date();
String modifiedDate = new SimpleDateFormat("yyyy-MM-dd").format(date);
if ( endDate.compareTo(modifiedDate) > 0) {
Log.d("data", "" + "");
}
Log.d("data", "" + "");
} catch (Exception e) {
}
}
}
Using this code, i am displaying Monday to Sunday like
2017-7-3 to 2017-7-9 ,2017-7-10 to 2017-7-16 ,2017-7-17 to 2017-7-23
,2017-7-24 to 2017-7-30 ,2017-7-31 to 2017-8-5 ...
Receptively but what I want, if current week is
2017-7-24 to 2017-7-30
then when we click on next week it should display it should display only previous week please suggest me in this scenario I will compare date.
if (c.getTime().after(new Date())){
next.setVisibility(View.GONE);
}else {
next.setVisibility(View.VISIBLE);
}
apply this Condition and enjoy !!

Get 12 hour time from DateTime picker

I am using Material DateTime picker for choosing date and time. Its working fine, but in onTimeSetListener method it returns hourOfTheDay in 24 hours format.
I want to show it it 12 hour format for that I used the if condition where hours are greater than 12 then it should show PM, but the hour number dose not change.
How can I change this?
public class TransportFragment extends Fragment implements DatePickerDialog.OnDateSetListener,TimePickerDialog.OnTimeSetListener {
private OnFragmentInteractionListener mListener;
private EditText mEditTxt_From,mEditTxt_To,mEditTxt_DateTime;
int PLACE_PICKER_REQUEST = 1;
private static final String TAG = "PlacePickerSample";
private static final int REQUEST_PLACE_PICKER_FROM = 1;
private static final int REQUEST_PLACE_PICKER_TO = 2;
private String mDate;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_transport, container, false);
mEditTxt_From = (EditText) view.findViewById(R.id.editTextFrom);
mEditTxt_To = (EditText) view.findViewById(R.id.editTextTo);
mEditTxt_DateTime = (EditText) view.findViewById(R.id.editTextDateTime);
mEditTxt_DateTime = (EditText) view.findViewById(R.id.editTextDateTime);
mEditTxt_DateTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar now = Calendar.getInstance();
DatePickerDialog dpd = DatePickerDialog.newInstance(
TransportFragment.this,
now.get(Calendar.YEAR),
now.get(Calendar.MONTH),
now.get(Calendar.DAY_OF_MONTH)
);
dpd.setVersion(DatePickerDialog.Version.VERSION_2);
dpd.setAccentColor(ContextCompat.getColor(getActivity(),R.color.colorAccent));
dpd.show(getFragmentManager(), "Datepickerdialog");
}
});
#Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
mDate = dayOfMonth+"/"+(++monthOfYear)+"/"+year;
Calendar now = Calendar.getInstance();
TimePickerDialog tpd = TimePickerDialog.newInstance(
TransportFragment.this,
now.get(Calendar.HOUR_OF_DAY),
now.get(Calendar.MINUTE),
false
);
tpd.setVersion(TimePickerDialog.Version.VERSION_2);
tpd.setAccentColor(ContextCompat.getColor(getActivity(),R.color.colorAccent));
tpd.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialogInterface) {
Log.d("TimePicker", "Dialog was cancelled");
}
});
tpd.show(getFragmentManager(), "Timepickerdialog");
}
#Override
public void onTimeSet(TimePickerDialog view, int hourOfDay, int minute, int second) {
String hourString = hourOfDay < 10 ? "0"+hourOfDay : ""+hourOfDay;
String minuteString = minute < 10 ? "0"+minute : ""+minute;
String secondString = second < 10 ? "0"+second : ""+second;
String time;
if(hourOfDay > 12)
{
time = hourOfDay + ":" + minuteString + " PM";
}
else {
time = hourOfDay + ":" + minuteString + " AM";
}
mEditTxt_DateTime.setText(mDate + " " + time );
}
}
Please help. Thank you.
I think your if statement is invalid:
if (hourOfDay > 12) {
time = (hourOfDay - 12) + ":" + minuteString + " PM";
} else {
...
}
You do not need to reinvent the wheel. In particular, if your app is working with dates and times, you should consider getting the ThreeTenABP library and using the modern Java date and time classes. One of these, LocalTime, solves your task in two lines:
DateTimeFormatter twelveHourTimeFormatter
= DateTimeFormatter.ofPattern("hh:mm:ss a", Locale.ENGLISH);
String time = LocalTime.of(hourOfDay, minute, second)
.format(twelveHourTimeFormatter);
Once you move to Java 8 the classes are built-in and you can discard the library.
In case you don’t want the dependency on one more external library, you can obtain the same with the outdated classes GregorianCalendar, Date and SimpleDateFormat, only it will be less elegant and far from future-proof.
Links
ThreeTenABP
Question: How to use ThreeTenABP in Android Project

How to restrict user to set date based on other date from date picker in android

I have 2 date-picker in one activity. What i want to do is when user try to select date from second date-picker then that date should greater than first date-picker's date otherwise it should show alert dialog.
So below is my code.
public class Assignment_Create extends Activity implements OnClickListener {
DataManipulator dataManipulator;
static final int DIALOG_ID = 1;
ImageView imageViewDateAssign, imageViewDueDate, imageViewSubmit;
TextView textViewDtAssign, textViewDueDt;
EditText editTextTitle, editTextDesc;
static final int DATE_DIALOG_ID = 0;
int cDay, cMonth, cYear;
private TextView activeDateDisplay;
private Calendar activeDate;
// Update database
String updateId;
public boolean isEdit;
#Override
public void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.assignment_create);
imageViewDateAssign = (ImageView) findViewById(R.id.dateassign);
imageViewDueDate = (ImageView) findViewById(R.id.duedate);
imageViewSubmit = (ImageView) findViewById(R.id.submit);
textViewDtAssign = (TextView) findViewById(R.id.textViewDateAssign);
textViewDueDt = (TextView) findViewById(R.id.textViewDueDate);
editTextTitle = (EditText) findViewById(R.id.title);
editTextDesc = (EditText) findViewById(R.id.description);
isEdit = getIntent().getExtras().getBoolean("isEdit");
updateId = getIntent().getExtras().getString("idNo");
if (isEdit) {
editTextTitle.setText(getIntent().getExtras().getString(
"AsmntTitle"));
editTextDesc
.setText(getIntent().getExtras().getString("AsmntDesc"));
}
Code.AssignDate = Calendar.getInstance();
Code.DueDate = Calendar.getInstance();
imageViewDateAssign.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
showDateDialog(textViewDtAssign, Code.AssignDate);
}
});
imageViewDueDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
showDateDialog(textViewDueDt, Code.DueDate);
}
});
imageViewSubmit.setOnClickListener(this);
updateDisplay(textViewDtAssign, Code.AssignDate);
updateDisplay(textViewDueDt, Code.DueDate);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.submit:
Code.title = editTextTitle.getText().toString().trim();
Code.description = editTextDesc.getText().toString().trim();
Code.diff = Code.DueDate.getTimeInMillis()
- Code.AssignDate.getTimeInMillis();
Code.days = Code.diff / (24 * 60 * 60 * 1000);
Code.strDays = String.valueOf(Code.days);
Date assignDate = new Date(Code.AssignDate.getTimeInMillis());
Date dueDate = new Date(Code.DueDate.getTimeInMillis());
if (dueDate.before(assignDate) || dueDate.equals(assignDate)) {
AlertDialog.Builder myDialogBattery = new AlertDialog.Builder(
Assignment_Create.this);
myDialogBattery.setTitle("How to use Less Battery");
myDialogBattery.setMessage("hahahahahaha");
myDialogBattery.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
}
});
myDialogBattery.show();
}
if (isEdit) {
this.dataManipulator = new DataManipulator(this);
this.dataManipulator.update(updateId);
this.dataManipulator.close();
} else {
this.dataManipulator = new DataManipulator(this);
this.dataManipulator.insert(Code.title, Code.description,
Code.strDays);
this.dataManipulator.close();
}
Toast.makeText(getApplicationContext(),
"Details are saved successfully", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(),
"Assignment Created Succesfully", Toast.LENGTH_LONG).show();
Assignment_Create.this.finish();
break;
}
}
private void updateDisplay(TextView dateDisplay, Calendar date) {
dateDisplay.setText(new StringBuilder()
// Month is 0 based so add 1
.append(date.get(Calendar.MONTH) + 1).append("-")
.append(date.get(Calendar.DAY_OF_MONTH)).append("-")
.append(date.get(Calendar.YEAR)).append(" "));
}
#SuppressWarnings("deprecation")
public void showDateDialog(TextView dateDisplay, Calendar date) {
activeDateDisplay = dateDisplay;
activeDate = date;
showDialog(DATE_DIALOG_ID);
}
private OnDateSetListener dateSetListener = new OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
activeDate.set(Calendar.YEAR, year);
activeDate.set(Calendar.MONTH, monthOfYear);
activeDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateDisplay(activeDateDisplay, activeDate);
unregisterDateDisplay();
}
};
private void unregisterDateDisplay() {
activeDateDisplay = null;
activeDate = null;
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, dateSetListener,
activeDate.get(Calendar.YEAR),
activeDate.get(Calendar.MONTH),
activeDate.get(Calendar.DAY_OF_MONTH));
}
return null;
}
#SuppressWarnings("deprecation")
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
super.onPrepareDialog(id, dialog);
switch (id) {
case DATE_DIALOG_ID:
((DatePickerDialog) dialog).updateDate(
activeDate.get(Calendar.YEAR),
activeDate.get(Calendar.MONTH),
activeDate.get(Calendar.DAY_OF_MONTH));
break;
}
}
}
I have tried with the following link but not getting solution as i want
how to not allow user select past date in datepicker?
Setting upper and lower date limits to date picker dialog
How to set min-max age limit with datepicker android
Date Picker with max and minimum date in onDateChanged() in Android 1.5?
so i am setting date, now when user click on submit button and if the date-picker2's date is lesser than date-picker1's date then alert dialog should come..
So what i am doing wrong, can anyone help me please. Thanks in advance.
Just compare getTimeInMillis of Calendar
Calendar mCalendarFirst = Calendar.getInstance();
mSelectedCalendar.set(Calendar.YEAR, your_year_from_frist_datepicker);
mSelectedCalendar.set(Calendar.MONTH, your_month_from_frist_datepicker);
mSelectedCalendar.set(Calendar.DAY_OF_MONTH, your_day_from_frist_datepicker);
Calendar mCalendarSecond = Calendar.getInstance();
mSelectedCalendar.set(Calendar.YEAR, your_year_from_second_datepicker);
mSelectedCalendar.set(Calendar.MONTH, your_month_from_seconf_datepicker);
mSelectedCalendar.set(Calendar.DAY_OF_MONTH, your_day_from_second_datepicker);
if(mCalendarSecond.getTimeInMillis() <= mCalendarFirst.getTimeInMillis())
{
//Your second date is less than first date
//Show your dialog here.
}
Update:
For your situation use below:
if(Code.DueDate.getTimeInMillis() <= Code.AssignDate.getTimeInMillis())
{
//Your second date is less than first date
//Show your dialog here.
}
Try Below code:
public void onClick(View v) {
switch (v.getId()) {
case R.id.submit:
Code.title = editTextTitle.getText().toString().trim();
Code.description = editTextDesc.getText().toString().trim();
Code.diff = Code.DueDate.getTimeInMillis()
- Code.AssignDate.getTimeInMillis();
Code.days = Code.diff / (24 * 60 * 60 * 1000);
Code.strDays = String.valueOf(Code.days);
Date assignDate = new Date(Code.AssignDate.getTimeInMillis());
Date dueDate = new Date(Code.DueDate.getTimeInMillis());
if (Code.DueDate.getTimeInMillis() <= Code.AssignDate.getTimeInMillis()){
AlertDialog.Builder myDialogBattery = new AlertDialog.Builder(
Assignment_Create.this);
myDialogBattery.setTitle("How to use Less Battery");
myDialogBattery.setMessage("hahahahahaha");
myDialogBattery.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
}
});
myDialogBattery.show();
}else
{
if (isEdit) {
this.dataManipulator = new DataManipulator(this);
this.dataManipulator.update(updateId);
this.dataManipulator.close();
} else {
this.dataManipulator = new DataManipulator(this);
this.dataManipulator.insert(Code.title, Code.description,
Code.strDays);
this.dataManipulator.close();
}
Toast.makeText(getApplicationContext(),
"Details are saved successfully", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(),
"Assignment Created Succesfully", Toast.LENGTH_LONG).show();
Assignment_Create.this.finish();
}
break;
}
}
try following code. Here firstDate and secondDate are Date object
if (firstDate.after(secondDate)) { OR //secondDate.before(firstDate)
//display alert here
} else {
}

Categories