I am using Android Studio and run into a bit of an issue, here due to my inexperience. I have an Activity with a CalendarView and a Button. Upon pressing the Button, the Date selected in the CalendarView will be set into an EditText on the next Activity.
This works, but in a weird way. Usually, I will select a Date from the CalendarView and then when I click the Button the Intent will start but now it is the total opposite; I have to click on the Button and then choose a Date in order for the Intent to be started and to be redirected to another page.
Here is my code:
btnDone1 = (Button) findViewById(R.id.btnDone1);
btnDone1.setOnClickListener(new OnClickListener(){
public void onClick(View v){
calendar1.setOnDateChangeListener(new CalendarView.OnDateChangeListener(){
#Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth){
String date1 = dayOfMonth + "/" + (month + 1) + "/" + year;
Intent doneD = new Intent(RentStartActivity.this, SearchActivity.class);
doneD.putExtra("Date1", date1);
startActivity(doneD);
}
});
}
});
Please kindly show me in what way should I code it.
Help is appreciated, thank you!!
try following
String date1;
calendar1.setOnDateChangeListener(new CalendarView.OnDateChangeListener(){
#Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth){
date1 = dayOfMonth + "/" + (month + 1) + "/" + year;
}
});
btnDone1 = (Button) findViewById(R.id.btnDone1);
btnDone1.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Intent doneD = new Intent(RentStartActivity.this, SearchActivity.class);
doneD.putExtra("Date1", date1);
startActivity(doneD);
}
});
In SearchActivity to get date.
Intent intent = getIntent();
String date = intent.getStringExtra("Date1");
You set the OnDateChangedListener inside the button's OnClickListener, so it will only listen after you click the button. From what I understand, you want to do something like this:
btnDone1 = (Button) findViewById(R.id.btnDone1);
calendar1.setOnDateChangeListener(new CalendarView.OnDateChangeListener(){
#Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth){
btnDone1.setOnClickListener(new OnClickListener(){
public void onClick(View v){
String date1 = dayOfMonth + "/" + (month + 1) + "/" + year;
Intent doneD = new Intent(RentStartActivity.this, SearchActivity.class);
doneD.putExtra("Date1", date1);
startActivity(doneD);
}
});
}
});
This code sends the selected date to SearchActivity after you click the button.
Related
I am working on a simple app in which i have taken two date pickers they subtract two dates and display the result. But i want that if the two dates are same like 06/04/2017 then two radio button should pop up for selecting full day and half day as soon as it calculates that the two dates are same.
how to do that?
public class Leave extends AppCompatActivity {
TextView date;
private DatePickerDialog datePickerDialog;
TextView date2;
//TextView setDay;
private DatePickerDialog datePickerDialog2;
TextView no_of_days;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_leave);
date = (TextView) findViewById(R.id.date);
date2 = (TextView) findViewById(R.id.date2);
//setDay = (TextView) findViewById(R.id.setDay);
no_of_days = (TextView) findViewById(R.id.no_of_days);
// initiate the date picker and a button
date = (TextView) findViewById(R.id.date);
// perform click event on edit text
date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// calender class's instance and get current date , month and year from calender
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR); // current year
int mMonth = c.get(Calendar.MONTH); // current month
int mDay = c.get(Calendar.DAY_OF_MONTH); // current day
// date picker dialog
datePickerDialog = new DatePickerDialog(Leave.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// set day of month , month and year value in the edit text
date.setText(dayOfMonth + "/"
+ (monthOfYear + 1) + "/" + year);
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
});
// initiate the date picker and a button
date2 = (TextView) findViewById(R.id.date2);
// perform click event on edit text
date2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// calender class's instance and get current date , month and year from calender
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR); // current year
int mMonth = c.get(Calendar.MONTH); // current month
int mDay = c.get(Calendar.DAY_OF_MONTH); // current day
// date picker dialog
datePickerDialog2 = new DatePickerDialog(Leave.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// set day of month , month and year value in the edit text
date2.setText(dayOfMonth + "/"
+ (monthOfYear + 1) + "/" + year);
}
}, mYear, mMonth, mDay);
datePickerDialog2.show();
}
});
no_of_days.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SimpleDateFormat format = new SimpleDateFormat("dd/mm/yyyy");
String date01 = date.getText().toString();
String date02 = date2.getText().toString();
try {
Date d = format.parse(date01);
Date d1 = format.parse(date02);
getDifferenceDays(d, d1);
} catch (ParseException e) {
e.printStackTrace();
}
}
});
Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.leave_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
}
public class SpinnerActivity extends Activity implements AdapterView.OnItemSelectedListener {
SpinnerActivity() throws ParseException {
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
Spinner spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
}
}
private void setupRadios() {
RadioButton radio_full = (RadioButton) findViewById(R.id.radio_full);
RadioButton radio_Half = (RadioButton) findViewById(R.id.radio_Half);
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioleave);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
int buttonId = radioGroup.getCheckedRadioButtonId();
switch (buttonId) {
case R.id.radio_full:
Toast.makeText(getApplicationContext(), "You have selected Full Day Leave", Toast.LENGTH_SHORT).show();
break;
case R.id.radio_Half:
Toast.makeText(getApplicationContext(), "You have selected Half Day Leave", Toast.LENGTH_SHORT).show();
break;
}
}
});
}
public void getDifferenceDays(Date d1, Date d2) {
int daysdiff = 0;
long diff = d2.getTime() - d1.getTime();
long diffDays = diff / (24 * 60 * 60 * 1000) + 1;
daysdiff = (int) diffDays;
no_of_days.setText(Integer.toString(daysdiff));
System.out.println("day count=>" + daysdiff);
}
}
Compare the dates whenever any date is selected from any one of the date picker's as follows :
public class Leave extends AppCompatActivity {
TextView date;
private DatePickerDialog datePickerDialog;
TextView date2;
//TextView setDay;
private DatePickerDialog datePickerDialog2;
TextView no_of_days;
String date1 = "", date2 = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_leave);
date = (TextView) findViewById(R.id.date);
date2 = (TextView) findViewById(R.id.date2);
//setDay = (TextView) findViewById(R.id.setDay);
no_of_days = (TextView) findViewById(R.id.no_of_days);
RadioButton radio_full = (RadioButton) findViewById(R.id.radio_full);
RadioButton radio_Half = (RadioButton) findViewById(R.id.radio_Half);
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioleave);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
int buttonId = radioGroup.getCheckedRadioButtonId();
switch (buttonId) {
case R.id.radio_full:
Toast.makeText(getApplicationContext(), "You have selected Full Day Leave", Toast.LENGTH_SHORT).show();
break;
case R.id.radio_Half:
Toast.makeText(getApplicationContext(), "You have selected Half Day Leave", Toast.LENGTH_SHORT).show();
break;
}
}
});
// initially hide the radio buttons
radio_full.setVisibility(View.GONE);
radio_Half.setVisibility(View.GONE);
// initiate the date picker and a button
date = (TextView) findViewById(R.id.date);
// perform click event on edit text
date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// calender class's instance and get current date , month and year from calender
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR); // current year
int mMonth = c.get(Calendar.MONTH); // current month
int mDay = c.get(Calendar.DAY_OF_MONTH); // current day
// date picker dialog
datePickerDialog = new DatePickerDialog(Leave.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// set day of month , month and year value in the edit text
// assign the value to date1
date1 = dayOfMonth + "/"
+ (monthOfYear + 1) + "/" + year;
date.setText(dayOfMonth + "/"
+ (monthOfYear + 1) + "/" + year);
// check if date2 has been set and compare it with date1
if(!TextUtils.isEmpty(date2)) {
// get difference
getDifferenceDays(date, date2);
if(date1.equals(date2)) {
// pop up radio button
radio_full.setVisibility(View.VISIBLE);
radio_Half.setVisibility(View.VISIBLE);
} else {
// hide radio buttons
radio_full.setVisibility(View.GONE);
radio_Half.setVisibility(View.GONE);
}
}
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
});
// initiate the date picker and a button
date2 = (TextView) findViewById(R.id.date2);
// perform click event on edit text
date2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// calender class's instance and get current date , month and year from calender
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR); // current year
int mMonth = c.get(Calendar.MONTH); // current month
int mDay = c.get(Calendar.DAY_OF_MONTH); // current day
// date picker dialog
datePickerDialog2 = new DatePickerDialog(Leave.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// set day of month , month and year value in the edit text
// assign the value to date2
date2 = dayOfMonth + "/"
+ (monthOfYear + 1) + "/" + year;
date2.setText(dayOfMonth + "/"
+ (monthOfYear + 1) + "/" + year);
// check if date2 has been set and compare it with date1
if(!TextUtils.isEmpty(date1)) {
// get difference
getDifferenceDays(date, date2);
if(date1.equals(date2)) {
// pop up radio button
radio_full.setVisibility(View.VISIBLE);
radio_Half.setVisibility(View.VISIBLE);
} else {
// hide radio buttons
radio_full.setVisibility(View.GONE);
radio_Half.setVisibility(View.GONE);
}
}
}
}, mYear, mMonth, mDay);
datePickerDialog2.show();
}
});
no_of_days.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SimpleDateFormat format = new SimpleDateFormat("dd/mm/yyyy");
String date01 = date.getText().toString();
String date02 = date2.getText().toString();
try {
Date d = format.parse(date01);
Date d1 = format.parse(date02);
getDifferenceDays(d, d1);
} catch (ParseException e) {
e.printStackTrace();
}
}
});
Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.leave_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
}
I made a button to open a date and time picker, but a CheckBox must be checked in order to activate my button. Without the checkbox, it works fine, with the chekbox checked or unchecked, it's not opening the date picker. Can you tell me why?
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
pick_date = (Button) findViewById(R.id.pick_date);
tv_result = (TextView) findViewById(R.id.tvdate_result);
CheckBox fixed_date_flag = (CheckBox) findViewById(R.id.fixed_date);
final boolean checked = (fixed_date_flag).isChecked();
if(checked){
pick_date.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(NewActivity.this, NewActivity.this, year, month, day);
datePickerDialog.show();
}
});}
}
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth)
{
yearFinal = year;
monthFinal = month + 1;
dayFinal = dayOfMonth;
Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR);
minute = c.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(NewActivity.this, NewActivity.this, hour, minute, DateFormat.is24HourFormat(this));
timePickerDialog.show();
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute)
{
hourFinal = hourOfDay;
minuteFinal = minute;
tv_result.setText(
"year: " + yearFinal + "\n" +
"month: " + monthFinal + "\n" +
"day: " + dayFinal + "\n" +
"hour: " + hourFinal + "\n" +
"minute: " + minuteFinal);
}
}
your problem is very simple:
When creating the activity, your are checking if the checkbox is checked. If this value is true (but is not true) you add a click listener to the datePicker. So, the picker does not have a click listener! This means that when you "tap" the picker, it has no listener added, even if the checkbox is checked.
You must move the if statement inside the onClick method, like this:
EDITED:
pick_date.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
if((fixed_date_flag).isChecked()){
Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(NewActivity.this, NewActivity.this, year, month, day);
datePickerDialog.show();
}
}
});
Nevertheless, I think is a much better option to create a separated cass that implements OnClickListener interface, so in the constructor you can initialize the datepicker, instanciated as a privated variable of this new class, and on the onClick method you only call to .show() method (if the checkbox is checked, obbiusly)
Hope it helps!
What I have is a calendar widget which opens up when pressed and the user can select their dates from the calendar. I have variables to save the dates entered in inside the DateSetup class and I followed the code on using putExtra() to send the data from one class to another, but the values are not showing up.
The process of the application is when the dates have been selected, the user will then be able to select the times with the time picker widget which works.
After the dates and times have been selected, the values are sent to a MySQL database which the dates/times values should be shown. Only the selected times are showing but not the dates from the calendar selected.
DateSetup class
public class DateSetup extends MainActivity implements View.OnClickListener
{
//UI References
private EditText fromDateEtxt;
private EditText toDateEtxt;
// Dates Strings setup
String startDate;
String endDate;
DatePickerDialog fromDatePickerDialog;
DatePickerDialog toDatePickerDialog;
private SimpleDateFormat dateFormatter;
private DataDBAdapter2 Database;
Button btnHistory;
Button btnTime;
Button btnFuture;
Button btnManual;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.date_setup);
fromDateEtxt = (EditText) findViewById(R.id.etxt_fromdate);
fromDateEtxt.setInputType(InputType.TYPE_NULL);
fromDateEtxt.requestFocus();
toDateEtxt = (EditText) findViewById(R.id.etxt_todate);
toDateEtxt.setInputType(InputType.TYPE_NULL);
toDateEtxt.requestFocus();
btnTime = (Button)findViewById(R.id.btnSetDates);
btnFuture = (Button)findViewById(R.id.btnFutureSetups);
btnManual = (Button)findViewById(R.id.btnManualControl);
fromDateEtxt.setOnClickListener(this);
toDateEtxt.setOnClickListener(this);
// Open the database
Database = new DataDBAdapter2(this);
Database.open();
// Set the date format to English (Australia)
dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
btnHistory = (Button)findViewById(R.id.btnHistoryView);
btnHistory.setOnClickListener(this);
//-------------------------------------------
// Start Date (From 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);
fromDateEtxt.setText(dateFormatter.format(newDate.getTime()));
//startDate = fromDateEtxt.getText().toString();
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
//-------------------------------------------
// End Date (End date)
//-------------------------------------------
toDatePickerDialog = 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);
toDateEtxt.setText(dateFormatter.format(newDate.getTime()));
//endDate = toDateEtxt.getText().toString();
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
// Set dates and continue to set times
btnTime.setOnClickListener(new View.OnClickListener()//OnClickListener()
{
#Override
public void onClick(View view)
{
// Start next activity
Intent i = new Intent(DateSetup.this, TimeSetup.class);
// Send data start data and End Date
//i.putExtra("START", startDate);
//i.putExtra("END", endDate);
i.putExtra("START", fromDateEtxt.getText().toString());
i.putExtra("END", toDateEtxt.getText().toString());
//i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
DateSetup.this.startActivity(i);
}
});
// History view
btnHistory.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v2)
{
Intent myIntent2 = new Intent(DateSetup.this, HistoryView.class);
myIntent2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
DateSetup.this.startActivity(myIntent2);
}
});
// Future Settings View
btnFuture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent myIntent3 = new Intent(DateSetup.this, CurrentView.class);
myIntent3.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
DateSetup.this.startActivity(myIntent3);
}
});
// Manual Control
btnManual.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent myIntent4 = new Intent(DateSetup.this, IrrigationControl.class);
myIntent4.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
DateSetup.this.startActivity(myIntent4);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.date_setup, menu);
//getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onClick(View view)
{
if(view == fromDateEtxt)
{
fromDatePickerDialog.show();
}
else if(view == toDateEtxt)
{
toDatePickerDialog.show();
}
}
}
TimeSetup2 class
public class TimeSetup2 extends TimeSetup
{
Button btnBck;
Button btnSetDatesandTime;
String minutedisplay2;
String hourdisplay2;
private DataDBAdapter2 Database;
private TimePicker timePicker2;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.time_setup2);
btnBck = (Button) findViewById(R.id.btnBack);
btnSetDatesandTime = (Button) findViewById(R.id.btnSet);
timePicker2 = (TimePicker)findViewById(R.id.timePicker2);
Database = new DataDBAdapter2(this);
Database.open();
// Back to previous activity
// http://stackoverflow.com/questions/4038479/android-go-back-to-previous-activity
btnBck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent myIntent = new Intent(TimeSetup2.this, TimeSetup.class);
TimeSetup2.this.startActivity(myIntent);
}
});
// Set time and dates
btnSetDatesandTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
// Generate random number for ID
Random r = new Random();
int i2 = r.nextInt(100-1) + 100;
// Convert from integer to string
String random2 = Integer.toString(i2);
//------------------------------------------------------
// Data from other classes to be sent to the database
//------------------------------------------------------
Intent intent = getIntent();
// Start Date and End date data
String StartD = intent.getStringExtra("START");
String EndD = intent.getStringExtra("END");
// Time Picker 1 Data (Working)
String StartTime1 = intent.getStringExtra("TIMEHOUR1");
String EndTime1 = intent.getStringExtra("TIMEMIN1");
// Time Picker 2 Data
//String StartTime2 = intent.getStringExtra("TIMEHOUR2");
//String EndTime2 = intent.getStringExtra("TIMEMIN2");
hourdisplay2 = timePicker2.getCurrentHour().toString();
minutedisplay2 = timePicker2.getCurrentMinute().toString();
// Send data to the Database
Database.insertData2(random2, StartD, EndD, StartTime1 + ":" + EndTime1, hourdisplay2 + ":" + minutedisplay2);
// Send data to the arduino board
// Show Message that the data has been sent
Toast.makeText(getApplicationContext(), "Irrigation Setups have been sent", Toast.LENGTH_LONG).show();
}
});
}
}
I've been stuck on trying to solve this problem for days. It's probably something really simple I'm missing out but I can't figure it out.
The only data types that are OS-friendly are primitive types (int, long, float, boolean, etc...), so that means that putExtra() allows you to store primitives only. That's why you cant send a Calendar object.
Try to send a String of your period to your next activity.
I am trying to create a popup date picker from a button (the button that pops it up also shows the date). However the popup isn't showing. When the button is pressed nothing happens.
The DatePicker needs to be casted from an xml since I want it to show as spinners not a calendar (and from what I've read after API 21 the only way to do that is in xml)
Here is my code for the onClickLlistner for the button:
final Button startDate = (Button)findViewById(R.id.startDate);
Calendar currentDate = Calendar.getInstance();
mYear = currentDate.get(Calendar.YEAR);
mMonth = currentDate.get(Calendar.MONTH);
int mDay = currentDate.get(Calendar.DAY_OF_MONTH);
startDate.setText(mMonth + "/" + mDay + "/" + mYear);
startDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//get date from button text
Calendar dateInButton = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
try {
dateInButton.setTime(sdf.parse(startDate.getText().toString()));
} catch (ParseException e) {
e.printStackTrace();
}
int pYear = dateInButton.get(Calendar.YEAR);
int pMonth = dateInButton.get(Calendar.MONTH);
int pDay = dateInButton.get(Calendar.DAY_OF_MONTH);
//display popup datepicker
final View dialogView = View.inflate(MyActivity.this, R.layout.date_picker, null);
DatePicker datePicker = (DatePicker) dialogView.findViewById(R.id.date_picker);
datePicker.updateDate(pYear, pMonth, pDay);
datePicker.init(pYear, pMonth, pDay, new DatePicker.OnDateChangedListener() {
#Override
public void onDateChanged(DatePicker view, int year, int month, int day) {
month++;
startDate.setText(month + "/" + day + "/" + year);
}
});
}
});
I had already tried the first two suggestions below, but I tried again and sincerely thanks for the help! The result is the same though. I´ll just edit the post to add more code info.
Hello there! I´m experimenting with a simple ToDo application and managed to change almost everything I wanted besides the date formatted that´s displayed once the user saves the task.
The task itself is added via the AddToDoActivity class which has the following resumed code:
public class AddToDoActivity extends Activity {
// 7 days in milliseconds - 7 * 24 * 60 * 60 * 1000
private static final int SEVEN_DAYS = 604800000;
private static final String TAG = "Lab-UserInterface";
private static String timeString;
private static String dateString;
private static TextView dateView;
private static TextView timeView;
private Date mDate;
private RadioGroup mPriorityRadioGroup;
private RadioGroup mStatusRadioGroup;
private EditText mTitleText;
private RadioButton mDefaultStatusButton;
private RadioButton mDefaultPriorityButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_todo);
mTitleText = (EditText) findViewById(R.id.title);
mDefaultStatusButton = (RadioButton) findViewById(R.id.statusNotDone);
mDefaultPriorityButton = (RadioButton) findViewById(R.id.medPriority);
mPriorityRadioGroup = (RadioGroup) findViewById(R.id.priorityGroup);
mStatusRadioGroup = (RadioGroup) findViewById(R.id.statusGroup);
dateView = (TextView) findViewById(R.id.date);
timeView = (TextView) findViewById(R.id.time);
// Set the default date and time
setDefaultDateTime();
// OnClickListener for the Date button, calls showDatePickerDialog() to show
// the Date dialog
final Button datePickerButton = (Button) findViewById(R.id.date_picker_button);
datePickerButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDatePickerDialog();
}
});
// OnClickListener for the Time button, calls showTimePickerDialog() to show
// the Time Dialog
final Button timePickerButton = (Button) findViewById(R.id.time_picker_button);
timePickerButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showTimePickerDialog();
}
});
// OnClickListener for the Cancel Button,
final Button cancelButton = (Button) findViewById(R.id.cancelButton);
cancelButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
log("Entered cancelButton.OnClickListener.onClick()");
finish();
}
});
//OnClickListener for the Reset Button
final Button resetButton = (Button) findViewById(R.id.resetButton);
resetButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
log("Entered resetButton.OnClickListener.onClick()");
setDefaultDateTime();
mTitleText.setText("");
mDefaultStatusButton.setChecked(true);
mDefaultPriorityButton.setChecked(true);
}
});
// OnClickListener for the Submit Button
// Implement onClick().
final Button submitButton = (Button) findViewById(R.id.submitButton);
submitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
log("Entered submitButton.OnClickListener.onClick()");
// Gather ToDoItem data
Priority priority = getPriority();
Status status = getStatus();
String titleString = mTitleText.getText().toString();
// Date
String fullDate = dateString + " " + timeString;
// Package ToDoItem data into an Intent
Intent data = new Intent();
ToDoItem.packageIntent(data, titleString, priority, status, fullDate);
setResult(Activity.RESULT_OK, data);
finish();
}
});
}
// Do not modify below here
// Use this method to set the default date and time
private void setDefaultDateTime() {
// Default is current time + 7 days
mDate = new Date();
mDate = new Date(mDate.getTime() + SEVEN_DAYS);
Calendar c = Calendar.getInstance();
c.setTime(mDate);
setDateString(c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.MONTH),
c.get(Calendar.YEAR));
dateView.setText(dateString);
setTimeString(c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE),
c.get(Calendar.MILLISECOND));
timeView.setText(timeString);
}
private static void setDateString(int dayOfMonth, int monthOfYear, int year) {
// Increment monthOfYear for Calendar/Date -> Time Format setting
monthOfYear++;
String mon = "" + monthOfYear;
String day = "" + dayOfMonth;
if (monthOfYear < 10)
mon = "0" + monthOfYear;
if (dayOfMonth < 10)
day = "0" + dayOfMonth;
dateString = year + "-" + mon + "-" + day;
}
private static void setTimeString(int hourOfDay, int minute, int mili) {
String hour = "" + hourOfDay;
String min = "" + minute;
if (hourOfDay < 10)
hour = "0" + hourOfDay;
if (minute < 10)
min = "0" + minute;
timeString = hour + ":" + min + ":00";
}
private Priority getPriority() {
switch (mPriorityRadioGroup.getCheckedRadioButtonId()) {
case R.id.lowPriority: {
return Priority.LOW;
}
case R.id.highPriority: {
return Priority.HIGH;
}
default: {
return Priority.MED;
}
}
}
private Status getStatus() {
switch (mStatusRadioGroup.getCheckedRadioButtonId()) {
case R.id.statusDone: {
return Status.DONE;
}
default: {
return Status.NOTDONE;
}
}
}
// DialogFragment used to pick a ToDoItem deadline date
public static class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int day = c.get(Calendar.DAY_OF_MONTH);
int month = c.get(Calendar.MONTH);
int year = c.get(Calendar.YEAR);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
#Override
public void onDateSet(DatePicker view, int dayOfMonth, int monthOfYear,
int year) {
setDateString(dayOfMonth, monthOfYear, year);
dateView.setText(dateString);
}
}
// DialogFragment used to pick a ToDoItem deadline time
public static class TimePickerFragment extends DialogFragment implements
TimePickerDialog.OnTimeSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return
return new TimePickerDialog(getActivity(), this, hour, minute,
true);
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
setTimeString(hourOfDay, minute, 0);
timeView.setText(timeString);
}
}
private void showDatePickerDialog() {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
}
private void showTimePickerDialog() {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "timePicker");
}
private void log(String msg) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i(TAG, msg);
}
}
Here´s the ToDoItem, that actually reads the info from AddToDoActivity:
public class ToDoItem {
public static final String ITEM_SEP = System.getProperty("line.separator");
public enum Priority {
LOW, MED, HIGH
};
public enum Status {
NOTDONE, DONE
};
public final static String TITLE = "title";
public final static String PRIORITY = "priority";
public final static String STATUS = "status";
public final static String DATE = "date";
public final static String FILENAME = "filename";
public final static SimpleDateFormat FORMAT = new SimpleDateFormat(
"dd/MM/yyyy HH:mm:ss", Locale.US);
private String mTitle = new String();
private Priority mPriority = Priority.LOW;
private Status mStatus = Status.NOTDONE;
private Date mDate = new Date();
ToDoItem(String title, Priority priority, Status status, Date date) {
this.mTitle = title;
this.mPriority = priority;
this.mStatus = status;
this.mDate = date;
}
// Create a new ToDoItem from data packaged in an Intent
ToDoItem(Intent intent) {
mTitle = intent.getStringExtra(ToDoItem.TITLE);
mPriority = Priority.valueOf(intent.getStringExtra(ToDoItem.PRIORITY));
mStatus = Status.valueOf(intent.getStringExtra(ToDoItem.STATUS));
try {
mDate = ToDoItem.FORMAT.parse(intent.getStringExtra(ToDoItem.DATE));
} catch (ParseException e) {
mDate = new Date();
}
}
public String getTitle() {
return mTitle;
}
public void setTitle(String title) {
mTitle = title;
}
public Priority getPriority() {
return mPriority;
}
public void setPriority(Priority priority) {
mPriority = priority;
}
public Status getStatus() {
return mStatus;
}
public void setStatus(Status status) {
mStatus = status;
}
public Date getDate() {
return mDate;
}
public void setDate(Date date) {
mDate = date;
}
// Take a set of String data values and
// package them for transport in an Intent
public static void packageIntent(Intent intent, String title,
Priority priority, Status status, String date) {
intent.putExtra(ToDoItem.TITLE, title);
intent.putExtra(ToDoItem.PRIORITY, priority.toString());
intent.putExtra(ToDoItem.STATUS, status.toString());
intent.putExtra(ToDoItem.DATE, date);
}
public String toString() {
return mTitle + ITEM_SEP + mPriority + ITEM_SEP + mStatus + ITEM_SEP
+ FORMAT.format(mDate);
}
public String toLog() {
return "Title:" + mTitle + ITEM_SEP + "Priority:" + mPriority
+ ITEM_SEP + "Status:" + mStatus + ITEM_SEP + "Date:"
+ FORMAT.format(mDate);
}
}
Oh well, after hours tweaking the
public final static SimpleDateFormat FORMAT = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss", Locale.US);
method from ToDoItem, I still cannot successfully convert yyyy-MM-dd to dd/MM/yyyy.
First, I´ve tried the obvious, and changed the expression yyyy-MM-dd to dd/MM/yyyy.
After that, all I got after saving the task was today´s date, even though the date inputted on AddToDoActivity is months or years ahead. If I revert back to yyyy-MM-dd, the date shown on the Task List is the same inputted on AddToDoActivity.
Then I tried to change all mentions of dates on every class to match the exact format that I wanted.
That made everything look good on AddToDoActivity, but again, when I transported the date back to ToDoItem, the app just ignored the previously inputted date and showed today´s date again.
Can anyone help me with this one??
Thanks!!
You are calling setDateString with arguments in the order of year, month, day:
setDateString(c.get(Calendar.YEAR), c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH));
But your method has parameters in the order of day, month, year:
private static void setDateString(int dayOfMonth, int monthOfYear, int year) {
...
}
I also think you made some errors while copying your code into the question, since the setDateString method is duplicated and there is no setTimeString method.
Change:
setDateString(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
to:
setDateString(c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.MONTH), c.get(Calendar.YEAR));
Modify the code as follows in the ToDoListAdapter file getView method
// TODO - Display Time and Date.
// Hint - use ToDoItem.FORMAT.format(toDoItem.getDate()) to get date and time String
final TextView dateView = (TextView) itemLayout.findViewById(R.id.dateView);
dateView.setText(ToDoItem.FORMAT.format(toDoItem.getDate()));
The output will be something similar the the following
Reference:
Completing UI Activity assignment