How to set maximum and minimum date for datepicker in android - java

I am using a tutorial i found on the net for datepicker.But i want to set the maximum and minimum date for the datepicker.Also i have heard that there is an issue for API level less than 11.
My code:
package com.androidexample.datepicker;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
public class DatePickerExample extends Activity {
private TextView Output;
private Button changeDate;
private int year;
private int month;
private int day;
static final int DATE_PICKER_ID = 1111;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Output = (TextView) findViewById(R.id.Output);
changeDate = (Button) findViewById(R.id.changeDate);
// 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 current date
Output.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(month + 1).append("-").append(day).append("-")
.append(year).append(" "));
// Button listener to show date picker dialog
changeDate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// On button click show datepicker dialog
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);
}
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
Output.setText(new StringBuilder().append(month + 1)
.append("-").append(day).append("-").append(year)
.append(" "));
}
};
}
The xml code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/changeDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click To Change Date" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Current/Selected Date (M-D-YYYY): "
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/Output"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
The problem with the above code is that there is no upper limit on the year part.I also need a lower limit on the year part.Can someone tell me as how to modify the code to set the upper and lower limit on the year part?

In DatePickerDialog.OnDateSetListener() you can compare the month, year , date with your specified min and max dates.

You can obtain DatePicker using DatePickerDialog.
DatePickerDialog dialog = new DatePickerDialog(this, pickerListener, year, month,day);
//calculate min and max dates (you can use, Calender API or Joda Time, just search for it.
dialog.getDatePicker().setMaxDate(maxDate.getTime());
dialog.getDatePicker().setMinDate(minDate.getTime());
return dialog;

You can get the underlying DatePicker from a DatePickerDialog by simply calling getDatePicker() and set its bounds using:
setMinDate(long minDate)
setMaxDate(long maxDate)
This works only for API level 11 and above.

Related

My button is not working, how can i make it work on android studio?

I made a button on my android studio project and I'm pretty sure the code is just fine. the problem is that the button does not respond - I click it, but it doesn't give me the wanted result. If you could help, please do. thank you so much for your time!
this is the code:
XML file code:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Bdateofbirth"
android:text="Date of birth"
android:gravity="center"
android:layout_gravity="center"/>
onClick Code:
#Override
public void onClick(View view) {
if (view == Bdateofbirth) {
dialogDOB();
}
}
dialogDOB:
private void dialogDOB(){
Calendar calendar = Calendar.getInstance();
int d = calendar.get(Calendar.DAY_OF_MONTH);
int m = calendar.get(Calendar.MONTH);
int y = calendar.get(Calendar.YEAR);
DatePickerDialog datePickerDialog = new DatePickerDialog(signup.this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
i1=i1+1;
String date = i + "/" + i1 + "/" + i2;
Toast.makeText(signup.this, date, Toast.LENGTH_SHORT).show();
Bdateofbirth.setText(date);
}
}, d, m, y);
datePickerDialog.show();
}
THANK YOU
In your Activity's XML file, add the attribute android:onclick="onClick" for your button to connect it to your onClick method. You don't need the #override.

How to initialise Android DatePicker by Intent?

I've got a list of elements displayed. When I click on one element, a detail view is opening and displaying name, description etc. Also a date shall be changeable in the detail view.
For now, the date is set to today's date when I click, but the DatePicker does not show up (init method fails). I know I am doing something wrong and that there has to be an intent/an activity to start from my DetailView class, since it's not the MainActivity. But unfortunately, I have no idea how to do it.
This is my code in DetailView.java:
public void onDateChange() {
initDatePicker();
dateButton = findViewById(R.id.itemDateButton);
dateButton.setText(getTodaysDate());
}
private String getTodaysDate() {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
month = month + 1;
int day = cal.get(Calendar.DAY_OF_MONTH);
return makeDateString(day, month, year);
}
private void initDatePicker() {
DatePickerDialog.OnDateSetListener dataSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
month = month + 1;
String date = makeDateString(dayOfMonth, 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, dataSetListener, year, month, day);
}
public void openDatePicker(View view) {
datePickerDialog.show();
}
The xml:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/itemDateText"
android:layout_marginTop="16dp"
android:layout_marginBottom="16dp"
android:text="Date"
app:layout_constraintTop_toBottomOf="#id/itemDescriptionWrapper"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/itemDateButton"
android:text="Change date"
style="?android:spinnerStyle"
app:layout_constraintTop_toBottomOf="#id/itemDateText"
android:onClick="#{() -> controller.onDateChange()}"
/>
I'm also able to send mails and sms from the DetailView by intent. But i just don't know how to start a DatePicker intent.
Any ideas? I would be very grateful. :)
Best regards,
Jess
To show the DatePicker, All you require is to add .show() method of DatePickerDialog inside your initDatePicker() function.
datePickerDialog = new DatePickerDialog(this, style, dataSetListener, year, month, day);
datePickerDialog.show();

Date Picker In Edit Text - What's wrong in this code?

I tried running it, but the Edit Text View gave no respond on clicking. The Date Picker was not even opened. What is wrong in here?
Please do help me with an elaborated answer along with the full code since I'm a newbie. Thanks
XML
<EditText
android:id="#+id/add_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginLeft="32dp"
android:layout_marginTop="16dp"
android:ems="10"
android:hint="Enter Date"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/add" />
MainActivity
public class addScreen extends AppCompatActivity {
EditText dateFormat;
int year, month, day;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_screen);
{
dateFormat = findViewById(R.id.add_date);
final Calendar calendar = Calendar.getInstance();
dateFormat.setOnClickListener(v -> {
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(addScreen.this, (view, year, month, dayOfMonth) -> dateFormat.setText(SimpleDateFormat.getDateInstance().format(calendar.getTime())), year, month, day);
datePickerDialog.show();
});
}
}
}
As Ben P said in the comment above, EditText is focusable by default.
So if you want to stop it from being shown the keyboard and just listen to the click listener you may need to stop the focus this below line do this so add it EditText declaration in your xml
android:focusable="false"
and that's it your EditText now can listen to your click listener.
P.S. I would recommend for you to use the material TextInputLayout and TextInputEditText which has a great look and follows the modern UX when it comes to create and input field and shown it to your users.

Retrieving TextView.getText() to set a CountDownTimer with a Start Button

I am in the dawn of my Android programming adventure and have just become able to communicate between on-screen views. So the next step for me is to successfully pull text from a TextView (set by a Dialog) and use a Start Button to run a Timer based on the user selected Dialog (default to the current minute value of the clock).
Here is what you see on screen.
A TextView that displays the selection from the Dialog.
A Selector Button that launches the Dialog TimePicker Dialog and resets the Start Button.
A Start Button that (should) read the TextView, disable itself, and begin a CountDownTimer based on a Long extracted from the TextView string.
A debug TextView that displays to me what is actually seen by the system.
The entire activity consists of a single Java File with two Classes declared and of course an XML. Every time I click my start button, despite the Debug TextView showing that I properly extracted the Long value for the seconds the timer instantly completes. I can see from my debug TextView that when I select say.. 08:26, the pSecondsLeft=26 as it should.. but the timer still doesn't count down from 26. I can't see my mistake.
Here is the XML first.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical">
<TextView android:id="#+id/timeDisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Time will appear here after being selected"
android:textSize="30sp"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button android:id="#+id/pickTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Change the time"/>
<Button android:id="#+id/startTimer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Start the time"
/>
</LinearLayout>
<TextView android:id="#+id/timeRemaining"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="center_horizontal"
android:textSize="30sp"
android:text="Time Remaining"
/>
</LinearLayout>
And here is my Main Activity.
package com.stembo.android.botskooltimepickertutorial;
import java.util.Calendar;
import java.util.StringTokenizer;
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class TimePickerActivity extends Activity {
/** Private members of the class */
private TextView displayTime;
private Button pickTime;
private Button startTimer;
private TextView timeRemaining;
private int pMinutesLeft;
private int pSecondsLeft;
/** This integer will uniquely define the
* dialog to be used for displaying time picker.*/
static final int TIME_DIALOG_ID = 0;
/** Callback received when the user "picks" a time in the dialog */
private TimePickerDialog.OnTimeSetListener mTimeSetListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int minLeft, int secLeft) {
pMinutesLeft = minLeft;
pSecondsLeft = secLeft;
updateDisplay();
displayToast();
}
};
/** Updates the time in the TextView */
private void updateDisplay() {
displayTime.setText(
new StringBuilder()
.append(pad(pMinutesLeft)).append(":")
.append(pad(pSecondsLeft)));
}
/** Displays a notification when the time is updated */
private void displayToast() {
Toast.makeText(this, new StringBuilder().append("Time choosen is ")
.append(displayTime.getText()), Toast.LENGTH_SHORT).show();
}
/** Add padding to numbers less than ten */
private static String pad(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/** Capture our View elements */
displayTime = (TextView) findViewById(R.id.timeDisplay);
pickTime = (Button) findViewById(R.id.pickTime);
startTimer = (Button) findViewById(R.id.startTimer);
timeRemaining = (TextView) findViewById(R.id.timeRemaining);
/** Listener for click event of the pick button */
pickTime.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startTimer.setEnabled(true);
showDialog(TIME_DIALOG_ID);
}
});
/**Listener for click event of the start button */
startTimer.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
startTimer.setEnabled(false);
StringTokenizer st = new StringTokenizer(displayTime.getText().toString(), ":");
while (st.hasMoreElements()){
st.nextElement();
long pSecondsTimer = Long.parseLong(st.nextToken());
}
timeRemaining.setText(displayTime.getText()+" Token="+ pSecondsLeft);
long oneSecondInterval = 1000;
MyCount counter = new MyCount(pSecondsLeft, oneSecondInterval);
counter.start();
}
});
/** Get the current time */
final Calendar cal = Calendar.getInstance();
pMinutesLeft = cal.get(Calendar.HOUR_OF_DAY);
pSecondsLeft = cal.get(Calendar.MINUTE);
/** Display the current time in the TextView */
updateDisplay();
}
/** Create a new dialog for time picker */
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG_ID:
return new TimePickerDialog(this,
mTimeSetListener, pMinutesLeft, pSecondsLeft, true);
}
return null;
}
public class MyCount extends CountDownTimer {
public MyCount(long pSecondsLeft, long countDownInterval){
super(pSecondsLeft, countDownInterval);
}
#Override
public void onTick(long pSecondsTimer){
displayTime.setText("Time remaining: " + pSecondsLeft);
}
#Override
public void onFinish(){
displayTime.setText("Countdown Complete!");
}
}
}
Here is the Start Button code which I am having trouble with, its in the Main Activity but may be easier to see excluded.
/**Listener for click event of the start button */
startTimer.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
startTimer.setEnabled(false);
StringTokenizer st = new StringTokenizer(displayTime.getText().toString(), ":");
while (st.hasMoreElements()){
st.nextElement();
long pSecondsTimer = Long.parseLong(st.nextToken());
}
timeRemaining.setText(displayTime.getText()+" Token="+ pSecondsLeft);
long oneSecondInterval = 1000;
MyCount counter = new MyCount(pSecondsLeft, oneSecondInterval);
counter.start();
}
});
It appears there is a misunderstanding about the values you get back from TimePickerDialog.OnTimeSetListener. It gives you hours and minutes, but you're expecting minutes and seconds. Same for the values coming out of the Calendar you're using on onCreate.
That said, if you are still trying to use a TimePickerDialog to get minutes and seconds with a full understanding that you're reinterpreting the values, you will need to multiply the number of "seconds" you receive from the picker by 1000 to get a unit in milliseconds that you can feed to the CountDownTimer.
MyCount counter = new MyCount(pSecondsLeft * 1000, oneSecondInterval);
I think it's because you're not subtracting from the pSecondsLeft variable on each tick
public class MyCount extends CountDownTimer {
public MyCount(long pSecondsLeft, long countDownInterval){
super(pSecondsLeft, countDownInterval);
}
#Override
public void onTick(long pSecondsTimer){
displayTime.setText("Time remaining: " + pSecondsLeft);
pSecondsLeft --;
}
#Override
public void onFinish(){
displayTime.setText("Countdown Complete!");
}
}

DatePicker dialog not working propely and not looking nice

I am trying to use a DatePicker:
My code is:
DatePicker datePicker = (DatePicker) v.findViewById(R.id.dialog_date_datePicker);
datePicker.init(year, month, day, new OnDateChangedListener() {
#Override
public void onDateChanged(DatePicker view, int year, int month,
int day) {
mDate = new GregorianCalendar(year, month, day).getTime();
getArguments().putSerializable(EXTRA_DATE, mDate);
}
});
But when I select a date the onDateChanged method is never called. After googling I found that if I changed my date picker layout to include: android:datePickerMode="spinner" /> and remove android:calendarViewShown="false" the onDateChanged is called and the code works but the date picker dialog is really bad looking.
My layout is:
<DatePicker xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/dialog_date_datePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:datePickerMode="spinner" />
<!-- android:calendarViewShown="false" -->
So why is the calenderViewShown attribute causing a problem and how can I improve the look of the date picker UI dialog?
If you want to use datepicker dialog than there's no need to use DatePicker just do it this way:
Calendar c = Calendar.getInstance();
DatePickerDialog datePickerDialog = new DatePickerDialog(SignUpActivity.this, android.R.style.Theme_Holo_Light_Dialog_MinWidth, new OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
// TODO Auto-generated method stub
try {
Date d = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).parse(year+"-"+(monthOfYear+1)+"-"+dayOfMonth);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
datePickerDialog.getDatePicker().setCalendarViewShown(false);
datePickerDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
datePickerDialog.show();
You can also use this library : Beautiful DatePicker UI
If on AS, add this in dependencies : compile 'com.github.flavienlaurent.datetimepicker:library:0.0.2'
Also,as pointed at this question : Datepicker
You can use this to solve the issue.
<DatePicker xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/dialog_date_datePicker"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:calendarViewShown="false"
android:datePickerMode="spinner" >
</DatePicker>

Categories

Resources