Is there any way to reformat the datePicker so that instead of getting "mm/dd/yyyy" you can get "dd/mm/yyyy" or even "dd/mm/yy"
This is my current code.
import android.app.Activity;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View.OnClickListener;
import android.app.DatePickerDialog.OnDateSetListener;
import java.util.Calendar;
/**
* Created by MOS182 on 7/21/13.
*/
public class AddReminder extends Activity {
TextView Title, Amount, PaymentDate, ReminderDate, ReminderTime;
EditText eTitle, eAmount, ePaymentDate, eReminderDate, eReminderTime;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.reminders_dialog);
initializeVariables();
ePaymentDate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//To show current date in the datepicker
Calendar mcurrentDate = Calendar.getInstance();
int mYear = mcurrentDate.get(Calendar.YEAR);
int mMonth = mcurrentDate.get(Calendar.MONTH);
int mDay = mcurrentDate.get(Calendar.DAY_OF_MONTH);
DatePickerDialog mDatePicker;
mDatePicker = new DatePickerDialog(AddReminder.this, new OnDateSetListener() {
public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) {
// TODO Auto-generated method stub
/* Your code to get date and time */
selectedmonth = selectedmonth + 1;
ePaymentDate.setText("" + selectedday + "/" + selectedmonth + "/" + selectedyear);
}
}, mYear, mMonth, mDay);
mDatePicker.setTitle("Select date");
mDatePicker.show();
}
});
}
private void initializeVariables()
{
Title = (TextView) findViewById(R.id.tvTitle);
Amount = (TextView) findViewById(R.id.tvAmount);
PaymentDate = (TextView) findViewById(R.id.tvPaymentDate);
ReminderDate = (TextView) findViewById(R.id.tvReminderDate);
ReminderTime = (TextView) findViewById(R.id.tvReminderTime);
eTitle = (EditText) findViewById(R.id.etTitle);
eAmount = (EditText) findViewById(R.id.etAmount);
ePaymentDate = (EditText) findViewById(R.id.etPaymentDate);
eReminderDate = (EditText) findViewById(R.id.etReminderDate);
eReminderTime = (EditText) findViewById(R.id.etReminderTime);
}
}
This is what is currently displayed when I run my code and select the ePaymentDate field.
The picker take the date format chosen by the user, which means you don't really have to format it, as probably the user enjoys the most to see the format he's used to.
I just tested a code and on my phone, where I have the date in (dd/mm/yyyy) format, so the picker shows the same format; in emulator, I've put the date in mm/dd/yyyy format, so the picker displays the same.
So there is no method to set the display format.
But if you still really want to display a specific format, then refer to this link, there is an elaborate way to show the date in the desired format, but with changes in the original code.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Android Days between two dates
(19 answers)
How to calculate number of days between two datepicker in android and display in the edit text
(3 answers)
Closed 2 years ago.
I have been trying to find the difference between two dates from date picker. My app is getting crashed for null point object exception.
java.lang.NullPointerException: Attempt to invoke virtual method 'long java.util.Date.getTime()' on a null object reference
package com.cksapp.dateformat;
import androidx.appcompat.app.AppCompatActivity;
import android.app.DatePickerDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import static java.util.Calendar.YEAR;
public class MainActivity extends AppCompatActivity {
TextView t1, t2, t3, t4, difference;
Button b1;
Date datefrom, dateOne;
Date dateto, dateTwo;
Date d1, d2;
private DatePickerDialog.OnDateSetListener mDate1;
private DatePickerDialog.OnDateSetListener mDate2;
private Object Date;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1 = findViewById(R.id.textView);
t2 = findViewById(R.id.textView2);
t3 = findViewById(R.id.textView3);
t4 = findViewById(R.id.textView4);
difference = findViewById(R.id.textView7);
b1 = findViewById(R.id.button);
t1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar c = Calendar.getInstance();
int year = c.get(YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(MainActivity.this,
android.R.style.Theme_Holo_Dialog_MinWidth,
mDate1,
year,month,day);
//Date dateOne = c.getTime();
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
});
mDate1 = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
month = month + 1;
String datefrom = month + "/" + dayOfMonth + "/" + year;
t2.setText(datefrom);
}
};
//next
t3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar c = Calendar.getInstance();
int year = c.get(YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(MainActivity.this,
android.R.style.Theme_Holo_Dialog_MinWidth,
mDate2,
year,month,day);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
});
mDate2 = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
month = month + 1;
String dateto = month + "/" + dayOfMonth + "/" + year;
t4.setText(dateto);
}
};
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//This is where I tried performing subtraction but it didn't work
long diff = dateto.getTime() - datefrom.getTime();
difference.setText((int) diff);
}
});
}
}
By putting String in front of dateto, you've made it a declaration of a local variable rather than a reference to the instance variable (that you're trying to access later). So it will forever be null. Change:
String dateto = month + "/" + dayOfMonth + "/" + year;
to
dateto = new Date(month, dayOfMonth, year); // no "String"
However, the Date constructor is deprecated and using Date is strongly discouraged, so you should really use something like:
import java.time.LocalDate;
import java.time.Instant;
import java.time.ZoneOffset;
//...
Instant dateto;
//...
LocalDate localDate = LocalDate.of(month, dayOfMonth, year);
dateto = localDate.atStartOfDay(ZoneOffset.UTC).toInstant();
Never mind, I figured out the answer using joda library
I have made it with different UI, joda library dependancy is included in build.gradle. It worked perfect.
package com.cksapp.newdateformat;
import androidx.appcompat.app.AppCompatActivity;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;
import net.danlew.android.joda.JodaTimeAndroid;
import org.joda.time.DateMidnight;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.LocalDate;
import org.joda.time.Period;
import org.joda.time.PeriodType;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import static org.joda.time.Days.daysBetween;
public class MainActivity extends AppCompatActivity {
TextView t1, t2, t3, t4, today;
Button b1, b2, b3;
String date1, date2, todaydate;
int daysy, daysm, daysd, daysss;
DatePickerDialog.OnDateSetListener dateSetListener;
DatePickerDialog.OnDateSetListener dateSetListener2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JodaTimeAndroid.init(this);
today = findViewById(R.id.today);
t1 = findViewById(R.id.starttext);
t2 = findViewById(R.id.endtext);
t3 = findViewById(R.id.daystext);
t4 = findViewById(R.id.daysinyears);
b1 = findViewById(R.id.startbutton);
b2 = findViewById(R.id.endbutton);
b3 = findViewById(R.id.calculatebutton);
Calendar c = Calendar.getInstance();
final int year = c.get(Calendar.YEAR);
final int month = c.get(Calendar.MONTH);
final int day = c.get(Calendar.DAY_OF_MONTH);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
todaydate = sdf.format(Calendar.getInstance().getTime());
today.setText("Today is " + todaydate);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerDialog datePickerDialog = new DatePickerDialog(v.getContext(),dateSetListener,year,month,day);
datePickerDialog.getDatePicker().setMaxDate(new Date().getTime());
datePickerDialog.show();
}
});
dateSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
month = month + 1;
date1 = dayOfMonth + "/" + month + "/" + year;
t1.setText(date1);
}
};
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerDialog datePickerDialog2 = new DatePickerDialog(v.getContext(),dateSetListener2,year,month,day);
datePickerDialog2.getDatePicker().setMaxDate(new Date().getTime());
datePickerDialog2.show();
}
});
dateSetListener2 = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
month = month + 1;
date2 = dayOfMonth + "/" + month + "/" + year;
t2.setText(date2);
}
};
b3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(date1 == null || date2 == null){
Toast.makeText(getApplicationContext(), "Please enter the date field(s)",Toast.LENGTH_SHORT).show();
}
else {
SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
try {
Date d1 = sdf1.parse(date1);
Date d2 = sdf1.parse(date2);
long fromdate = d1.getTime();
long todate = d2.getTime();
Period p = new Period(fromdate, todate, PeriodType.yearMonthDay());
int years = p.getYears();
int months = p.getMonths();
int days = p.getDays();
t4.setText(years + " years" + months + " months" + days + " days");
int diff = (int) (d2.getTime() - d1.getTime());
int YO = diff/86400000;
//Log.d("Days", String.valueOf(diff));
t3.setText(String.valueOf(YO));
} catch (ParseException e) {
e.printStackTrace();
}
}}
});
}
}
I have a rather simple issue but this is bugging me out!
I am trying to build an app in which I have 2 DatePickers, periodFrom and periodTo.
Basically what I'm trying to do is let the user pick dates on both cases and then calculate the difference between dates in days. I already know how to get the difference, how to get the date from the DatePicker. The problem is I don't know where I should get the value from the DatePicker, as my onCreate intializes the listener for the DatePickers but it doesn't store the set dates in the global variables, only the current date which it gets from Calendar.getInstance();
Here is my code for the MainActivity, maybe you can enlighten me on this issue I'm having. Thank you!
MainActivity.class
package com.endtech.utilitycalculator;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
private EditText periodFrom, periodTo;
private Calendar mCalendarFrom = Calendar.getInstance();
private Calendar mCalendarTo = Calendar.getInstance();
private long from, to;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
periodFrom = (EditText) findViewById(R.id.periodFrom);
periodTo = (EditText) findViewById(R.id.periodTo);
initListeners();
from = mCalendarFrom.getTimeInMillis(); //This is current time, not the set time
to = mCalendarTo.getTimeInMillis(); //This is current time, not the set time
}
private void initListeners() {
setDateFrom();
setDateTo();
}
private void setDateFrom() {
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mCalendarFrom.set(Calendar.YEAR, year);
mCalendarFrom.set(Calendar.MONTH, monthOfYear);
mCalendarFrom.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabelFrom();
}
};
periodFrom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new DatePickerDialog(MainActivity.this, date, mCalendarFrom.get(Calendar.YEAR),
mCalendarFrom.get(Calendar.MONTH), mCalendarFrom.get(Calendar.DAY_OF_MONTH)).show();
}
});
}
private void updateLabelFrom() {
String mFormat = "dd/MM/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(mFormat, Locale.GERMANY);
periodFrom.setText(sdf.format(mCalendarFrom.getTime()));
}
private void setDateTo() {
final DatePickerDialog.OnDateSetListener date2 = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mCalendarTo.set(Calendar.YEAR, year);
mCalendarTo.set(Calendar.MONTH, monthOfYear);
mCalendarTo.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabelTo();
}
};
periodTo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new DatePickerDialog(MainActivity.this, date2, mCalendarTo.get(Calendar.YEAR),
mCalendarTo.get(Calendar.MONTH), mCalendarTo.get(Calendar.DAY_OF_MONTH)).show();
}
});
}
private void updateLabelTo() {
String mFormat = "dd/MM/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(mFormat, Locale.GERMANY);
periodTo.setText(sdf.format(mCalendarTo.getTime()));
}
}
The problem is you are getting the dates before selecting them.
Simply Create a button (when you click on the button then the process of converting difference into days get done). then on button click get the values of dates and then convert it into days.
Let me know if you find some problem by commenting below.
I have to show calender using DatePickerDialog.
The below code is used:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.TextView;
import android.widget.Toast;
public class DatePickerExample extends Activity {
private TextView Output;
private Button changeDate;
private Boolean mEnableNativeCalGridView = null;
String timeZone;
public static TimeZone tz;
private int year;
private int month;
DatePickerDialog d;
public Calendar c;
SimpleDateFormat sdf;
private int day;
public static IntentFilter s_intentFilter;
static final int DATE_PICKER_ID = 1111;
static{
s_intentFilter = new IntentFilter();
s_intentFilter.addAction(Intent.ACTION_TIME_TICK);
s_intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
s_intentFilter.addAction(Intent.ACTION_TIME_CHANGED);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
registerReceiver(m_timeChangedReceiver, s_intentFilter);
Output = (TextView) findViewById(R.id.Output);
changeDate = (Button) findViewById(R.id.changeDate);
// sdf = new SimpleDateFormat("EEE, MMM d, ''yy");//Wed, Jul 4, '01
// 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() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
// On button click show datepicker dialog
showDialog(DATE_PICKER_ID);
}
});
}
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case DATE_PICKER_ID:
((DatePickerDialog) dialog).updateDate(
c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH));
}
}
#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
sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
tz = TimeZone.getDefault();
System.out.println("TimeZone "+tz.getDisplayName(false, TimeZone.SHORT)+" Timezon id :: " +tz.getID());
timeZone = tz.getDisplayName(false, TimeZone.SHORT);
c= Calendar.getInstance();
c.setTimeZone(tz);
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
d = new DatePickerDialog(DatePickerExample.this, pickerListener, year, month,day);
setMinMaxdate();
return d;
}
return null;
}
////////////////////Fix for issue on OS 5.1 //////////////////////
public long getDateFormatted(String date){
String givenDateString = date;
long timeInMilliseconds = 0;
try {
Date mDate = sdf.parse(givenDateString);
timeInMilliseconds = mDate.getTime();
System.out.println("Date in milli :: " + timeInMilliseconds);
} catch (ParseException e) {
e.printStackTrace();
}
return timeInMilliseconds;
}
//////////////////////////////////////////
private DatePicker.OnDateChangedListener newchange= new OnDateChangedListener(){
#Override
public void onDateChanged(DatePicker view,
int year, int monthOfYear,int dayOfMonth) {
Toast.makeText(getApplicationContext(),
"onDateChanged", Toast.LENGTH_SHORT).show();
}};
DatePicker datePicker;
public void setMinMaxdate() {
//Time zone calculation
//TimeZone.setDefault(tz);
///////////////////////
long calEvtEndDate= getDateFormatted("Sun May 31 23:59:59 "+timeZone+" 2015");//System.currentTimeMillis();
long calEvtStartDate= getDateFormatted("Wed May 13 00:00:00 "+timeZone+" 2015");//System.currentTimeMillis()/2;
// long calEvtEndDate = getDateFormatted("Sun, may 31, '15");
//long calEvtStartDate = getDateFormatted("Wed, may 13, '15");
if(d != null){
datePicker = d.getDatePicker();
if(mEnableNativeCalGridView != null){
datePicker.setCalendarViewShown(mEnableNativeCalGridView.booleanValue());
}
// If Start Date is Greater than End Date then we are showing from valid StartDate
// value and we are not setting the maxdate.
if (calEvtStartDate > calEvtEndDate) {
datePicker.setMinDate(calEvtStartDate);
} else {
if (calEvtStartDate > 0) { // If Only ValidStart date is provided, then setting the minDate.
datePicker.setMinDate(calEvtStartDate);
}
if (calEvtEndDate > 0) { // If Only ValidEnd date is provided, then setting the maxDate.
datePicker.setMaxDate(calEvtEndDate);
}
}
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
System.out.println("-------resumed");
}
public 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) {
//view.updateDate(year, month, day);
System.out.println("---------------datesetchange");
year = selectedYear;
month = selectedMonth;
day = selectedDay;
// Show selected date
Output.setText(new StringBuilder().append(month + 1)
.append("-").append(day).append("-").append(year)
.append(" "));
}
};
public void onDestroy() {
super.onDestroy();
unregisterReceiver(m_timeChangedReceiver);
}
private final BroadcastReceiver m_timeChangedReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(Intent.ACTION_TIME_CHANGED) ||
action.equals(Intent.ACTION_TIMEZONE_CHANGED))
{
System.out.println("timezone changed---"+action.toString());
tz = TimeZone.getDefault();
System.out.println("TimeZone "+tz.getDisplayName(false, TimeZone.SHORT)+" Timezon id :: " +tz.getID());
timeZone = tz.getDisplayName(false, TimeZone.SHORT);
// Intent intent1 = getIntent();
// finish();
// startActivity(intent1);
showDialog(DATE_PICKER_ID);
}
}
};
}
When the app is running, I go to the settings and change the Timezone to such a value so that the current date will change. Now when we select any date in the dialog, it behaves abnormally and goes to other date. I have used setMinDate() and setMaxDate() methods. This happens only in Android OS 5.1.
Any idea or help? Thanks in advance.
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 MyAndroidAppActivity extends Activity {
private TextView tvDisplayDate;
private DatePicker dpResult;
private Button btnChangeDate;
private int year;
private int month;
private int day;
static final int DATE_DIALOG_ID = 999;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setCurrentDateOnView();
addListenerOnButton();
}
// display current date
public void setCurrentDateOnView() {
tvDisplayDate = (TextView) findViewById(R.id.tvDate);
dpResult = (DatePicker) findViewById(R.id.dpResult);
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
// set current date into textview
tvDisplayDate.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(month + 1).append("-").append(day).append("-")
.append(year).append(" "));
// set current date into datepicker
dpResult.init(year, month, day, null);
}
public void addListenerOnButton() {
btnChangeDate = (Button) findViewById(R.id.btnChangeDate);
btnChangeDate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
// set date picker as current date
return new DatePickerDialog(this, datePickerListener,
year, month,day);
}
return null;
}
private DatePickerDialog.OnDateSetListener datePickerListener
= new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
// set selected date into textview
tvDisplayDate.setText(new StringBuilder().append(month + 1)
.append("-").append(day).append("-").append(year)
.append(" "));
// set selected date into datepicker also
dpResult.init(year, month, day, null);
}
};
}
Can someone help me how to use date picker code with fragments please
I am trying to get the user to select a date , work out the difference between the dates from the current date and the date they selected then divide the date difference with the number of pounds (weight) they want to loose so a message appears as in an empty string displaying the target. for example todays date is 14/12/2012 and the user selects 24/12/2012 the date difference is 10 days and they wish to loose 10pounds(weight) in 10 days
how can i programme for it to work out the difference / it by the goal and display a result showing the aim which will be 1pound per day
Any help will be great i am really lost thankss !
you have extend the class Fragment first.
then you override onCreateView() to inflate your contentview.
the you use onActivityCreated you bind your views.
Good day, can't seem to find a solution for this. i have 2 buttons that when pressed, opens a datepickerdialog, but my problem now is , how can i set them to the appropriate button on OnDateSet method. I am using a DialogFragment for the date and then implementing the DateListener in my activity. I have tried using getTag() but no success in getting the tag. here is what i tried:
public void showfromDatePickerDialog(View v) {
DialogFragment dateFragment = new DateDialogFragment();
dateFragment.show(getSupportFragmentManager(), "fromdatePicker");
}
public void showtoDatePickerDialog(View v) {
DialogFragment dateFragment = new DateDialogFragment();
dateFragment.show(getSupportFragmentManager(), "todatePicker");
}
public void onDateSet(DatePicker view, int year, int month, int day) {
StringBuilder builder = new StringBuilder();
builder.append(day).append("-")
.append(month).append("-")
.append(year);
String text= builder.toString();
if(view.getTag().toString().equals("fromdatePicker")) { // error here
Log.d(TAG, "got here" + text);
fromdate.setText(text);
}
if(view.getTag() == "todatePicker") {
todate.setText(text);
}
any ideas how to implement this? i keep seeing solutions about using 2 different DialogFragment class but am guessing there should be another way. or am i wrong? Thank you
ok, i have a work around for these. which can be helpful for anyone with this problem. if its slightly incorrect please let me know and i can change it. but this is what i did to solve this issue.
in on DateSet:
public void onDateSet(DatePicker view, int year, int month, int day) {
StringBuilder builder = new StringBuilder();
builder.append(day).append("-")
.append(month).append("-")
.append(year);
String text= builder.toString();
FragmentManager fragmanager = getSupportFragmentManager();
if(fragmanager.findFragmentByTag("fromdatePicker") != null) {
Log.d(TAG, "got here" + text);
fromdate.setText(text);
}
// if(view.getTag() == "todatePicker") {
if(fragmanager.findFragmentByTag("todatePicker") != null) {
todate.setText(text);
}
that way you can use the same dateListener for multiple calls and set the date appropriately based on the tag that was passed when calling show on the dialog.
Use below code of DatePicker Dialog.
private int mYear;
private int mMonth;
private int mDay;
Calendar cal4DatePicker = Calendar.getInstance();
Button btnDOB=findviewbyId(R.id.btndob);
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
cal4DatePicker.set(Calendar.YEAR, mYear);
cal4DatePicker.set(Calendar.MONTH, mMonth);
cal4DatePicker.set(Calendar.DAY_OF_MONTH, mDay);
btnDOB.setText(new StringBuilder()
.append(mDay).append("-").append(mMonth).append("-").append(mYear).append(" "));
}
};
on btnDOB you need to set click listner to show this DatePicker Dialog.
I have try same thing with Time Picker only. You can try out and set same for date picker also.
package com.example.toolboxtest;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TimePicker;
public class MainActivity extends FragmentActivity implements OnClickListener {
Button testBtn;
EditText testET;
static final int TIME_DIALOG_ID = 0;
int mHour = 0;
int mMinute = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
testBtn = (Button) findViewById(R.id.testBTn);
testET = (EditText) findViewById(R.id.testET);
testBtn.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.testBTn:
showDialog(TIME_DIALOG_ID);
break;
}
}
private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mHour=hourOfDay;
mMinute = minute;
// myPrefs = ImportantDateReminderActivity.this.getSharedPreferences("myPrefs",MODE_WORLD_WRITEABLE);
// prefsEditor = myPrefs.edit();
// prefsEditor.putInt("hour", mHour);
// prefsEditor.putInt("minute", mMinute);
// prefsEditor.putString("a", a);
// prefsEditor.commit();
if(mHour==12){
//reminderSetTime.setText(new StringBuilder().append("12").append(":").append((minute)+" PM"));
testET.setText(mHour+":"+mMinute+" "+"PM");
}
else
updateTimeDisplay();
}
};
private void updateTimeDisplay() {
try {
Format formatter;
SimpleDateFormat df = new SimpleDateFormat("hh:mm");
Date d = df.parse(mHour + ":" + mMinute);
Calendar gc = new GregorianCalendar();
gc.setTime(d);
//gc.add(Calendar.HOUR, 0);
Date d2 = gc.getTime();
formatter = new SimpleDateFormat("hh:mm a");
String time = formatter.format(d2);
System.out.println("The TIME is: "+time);
testET.setText(time);
String hour = new SimpleDateFormat("hh").format(d2);
String minute = new SimpleDateFormat("mm").format(d2);
String a = new SimpleDateFormat("a").format(d2);
System.out.println("The Hour is: "+hour+ " "+minute+ " " +a);
/*myPrefs = this.getSharedPreferences("myPrefs",MODE_WORLD_WRITEABLE);
prefsEditor = myPrefs.edit();
prefsEditor.putInt("hour", Integer.parseInt(hour));
prefsEditor.putInt("minute", Integer.parseInt(minute));
prefsEditor.putString("a", a);
prefsEditor.putString("complateTime", time);
prefsEditor.commit();*/
//addTwoMonthNotification();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG_ID:
return new TimePickerDialog(this,mTimeSetListener, mHour, mMinute, false);
}
return null;
}
}
Hope it will help you.
Please let me know if there is any issue.