DatePicker returns null (Android) - android

I'm trying to show DatePicker when user clicks the calendar icon in ActionBar and set the date picked in Textview.But I keep on getting these error.Any help or suggestions would be appreciated.Thank you.
sendUserActionEvent()mView==null
This is my code:
private DatePickerDialog PickDateDialog;
//I called setDataField() in onCreate
private void setDateField() {
Calendar newCalendar = Calendar.getInstance();
PickDateDialog = new PickDateDialog(this, new OnDateSetListener()
{
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
add_show.setText(dateFormatter.format(newDate.getTime()));
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
}
//Under onOptionsItemSelected menu
if (id == R.id.action_pickdate) {
PickDateDialog.show();
return true;
};

I tried your code, and it works!
Just using his DateFormat
import android.app.*;
import android.os.*;
import android.widget.*;
import java.util.*;
import android.view.*;
public class MainActivity extends Activity {
private DatePickerDialog PickDateDialog;
private TextView add_show;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
add_show = new TextView(this);
setContentView(add_show);
setDateField();
}
private void setDateField() {
Calendar newCalendar = Calendar.getInstance();
PickDateDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
add_show.setText(newDate.getTime().toLocaleString());
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add("pickdate").setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem p1) {
PickDateDialog.show();
return true;
}
}).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
return super.onCreateOptionsMenu(menu);
}
}

Related

DatePicker is not working when i used Fragment

i set DatePicker it is working in Activity when i used Fragment it generating the errors like
Error:(63, 61) error: incompatible types: MainActivity cannot be converted to Context
Here i paste the complete code.
MainActivity.Java
package com.example.sachin.datepicker;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.icu.text.SimpleDateFormat;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;
import java.util.Calendar;
import java.util.Locale;
public class MainActivity extends Fragment implements View.OnClickListener {
private EditText fromDateEtxt;
private EditText toDateEtxt;
private EditText toDateEtxt1;
private DatePickerDialog fromDatePickerDialog;
private DatePickerDialog toDatePickerDialog;
private DatePickerDialog toDatePickerDialog1;
private SimpleDateFormat dateFormatter;
View view;
#TargetApi(Build.VERSION_CODES.N)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_add_wod, container, false);
dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
findViewsById();
setDateTimeField();
return view;
}
private void findViewsById() {
fromDateEtxt = (EditText) view.findViewById(R.id.openingdate);
fromDateEtxt.setInputType(InputType.TYPE_NULL);
fromDateEtxt.requestFocus();
toDateEtxt = (EditText) view.findViewById(R.id.Birthdate);
toDateEtxt.setInputType(InputType.TYPE_NULL);
toDateEtxt.requestFocus();
toDateEtxt1 = (EditText) view.findViewById(R.id.Anniversary);
toDateEtxt1.setInputType(InputType.TYPE_NULL);
}
private void setDateTimeField() {
fromDateEtxt.setOnClickListener(this);
toDateEtxt.setOnClickListener(this);
toDateEtxt1.setOnClickListener(this);
Calendar newCalendar = Calendar.getInstance();
fromDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.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()));
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
toDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
#TargetApi(Build.VERSION_CODES.N)
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()));
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
toDatePickerDialog1 = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
#TargetApi(Build.VERSION_CODES.N)
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
toDateEtxt1.setText(dateFormatter.format(newDate.getTime()));
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
}
#Override
public void onClick(View view) {
if(view == fromDateEtxt) {
fromDatePickerDialog.show();
} else if(view == toDateEtxt) {
toDatePickerDialog.show();
} else if(view == toDateEtxt1) {
toDatePickerDialog1.show();
}
}
}
this code is not working:-
fromDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.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()));
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
i tried it but it is generating the same error again and again..
you extend fragment so replace this to getActivity()
fromDatePickerDialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {}
The constructor of DatePickerDialog expects a Context param.
You're passing your Fragment instance to the constructor of DatePickerDialog, but Fragment is not a Context subclass.
Either pass getContext() or getActivity() instead of this.
Change the following line:
fromDatePickerDialog = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
To this:
fromDatePickerDialog = new DatePickerDialog(getContext(),
new DatePickerDialog.OnDateSetListener() {
Or to this:
fromDatePickerDialog = new DatePickerDialog(getActivity(),
new DatePickerDialog.OnDateSetListener() {
According to your code you have multiple DatePickerDialogs, so you need to perform this change on all of them.
P.S. Your Fragment should not be called MainActivity.

Want to use three DatePicker and Display it on TextView

I am tryin to set three DatePicker and want to display selected date in TextView. I tried alot but generating an error like:-
ATAL EXCEPTION: main
Process: com.example.sachin.datepicker, PID: 5708
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setInputType(int)' on a null object reference
at com.example.sachin.datepicker.MainActivity.onCreateView(MainActivity.java:40)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2074)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1286)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:758)
Here I posted complete code of it.. just take a look on it,
MainActivity2.java
package com.example.sachin.datepicker;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Main2Activity extends AppCompatActivity {
Button next;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
next= (Button)findViewById(R.id.next);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView,new MainActivity()).commit();
}
});
}
}
Here, MainActivity.java
package com.example.sachin.datepicker;
import android.annotation.TargetApi;
import android.app.DatePickerDialog;
import android.icu.text.SimpleDateFormat;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;
import java.util.Calendar;
import java.util.Locale;
public class MainActivity extends Fragment implements View.OnClickListener {
public MainActivity() {};
EditText openingdate,Birthdate,Anniversary;
private DatePickerDialog fromDatePickerDialog;
private DatePickerDialog toDatePickerDialog;
private DatePickerDialog toDatePickerDialog1;
private SimpleDateFormat dateFormatter;
View view;
#TargetApi(Build.VERSION_CODES.N)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_add_wod, container, false);
dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
openingdate = (EditText) view.findViewById(R.id.openingdate);
openingdate.setInputType(InputType.TYPE_NULL);
openingdate.requestFocus();
Birthdate = (EditText)view. findViewById(R.id.Birthdate);
Birthdate.setInputType(InputType.TYPE_NULL);
Birthdate.requestFocus();
Anniversary = (EditText)view. findViewById(R.id.Anniversary);
Anniversary.setInputType(InputType.TYPE_NULL);
setDateTimeField();
return view;
}
private void setDateTimeField() {
openingdate.setOnClickListener(this);
Birthdate.setOnClickListener(this);
Anniversary.setOnClickListener(this);
Calendar newCalendar = Calendar.getInstance();
fromDatePickerDialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
#TargetApi(Build.VERSION_CODES.N)
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
openingdate.setText(dateFormatter.format(newDate.getTime()));
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
toDatePickerDialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
#TargetApi(Build.VERSION_CODES.N)
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
Birthdate.setText(dateFormatter.format(newDate.getTime()));
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
toDatePickerDialog1 = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
#TargetApi(Build.VERSION_CODES.N)
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
Anniversary.setText(dateFormatter.format(newDate.getTime()));
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
}
// #Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getActivity().getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onClick(View view) {
if(view == openingdate) {
fromDatePickerDialog.show();
} else if(view == Birthdate) {
toDatePickerDialog.show();
} else if(view == Anniversary) {
toDatePickerDialog1.show();
}
}
}
and lastly manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sachin.datepicker">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<Activity android:name=".MainActivity" />
<activity android:name=".Main2Activity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I tried alot but always getting error...
.setInputType(InputType.TYPE_CLASS_DATETIME);
Change all in .setInputType, try below code also.
#TargetApi(Build.VERSION_CODES.N)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.activity_add_wod, container, false);
dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
openingdate = (EditText) view.findViewById(R.id.openingdate);
openingdate.setInputType(InputType.TYPE_NULL);
openingdate.requestFocus();
Birthdate = (EditText) view.findViewById(R.id.Birthdate);
Birthdate.setInputType(InputType.TYPE_NULL);
Birthdate.requestFocus();
Anniversary = (EditText) view.findViewById(R.id.Anniversary);
Anniversary.setInputType(InputType.TYPE_NULL);
setDateTimeField();
return view;
}
private void setDateTimeField() {
openingdate.setOnClickListener(this);
Birthdate.setOnClickListener(this);
Anniversary.setOnClickListener(this);
Calendar newCalendar = Calendar.getInstance();
fromDatePickerDialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
#TargetApi(Build.VERSION_CODES.N)
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
openingdate.setText(dateFormatter.format(newDate.getTime()));
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
toDatePickerDialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
#TargetApi(Build.VERSION_CODES.N)
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
Birthdate.setText(dateFormatter.format(newDate.getTime()));
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
toDatePickerDialog1 = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
#TargetApi(Build.VERSION_CODES.N)
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
Anniversary.setText(dateFormatter.format(newDate.getTime()));
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
}
#Override
public void onClick(View view) {
if(view == openingdate) {
fromDatePickerDialog.show();
} else if(view == Birthdate) {
toDatePickerDialog.show();
} else if(view == Anniversary) {
toDatePickerDialog1.show();
}
}

How to update the UI in OnDateSet method when implement a DatePicker class?

I have DatePicker class like as:
package datepicker;
import android.app.DatePickerDialog;
import android.content.Context;
import android.text.InputType;
import android.text.format.DateFormat;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.EditText;
import com.marknguyen.babygenderpredictor.TimePredictorActivity;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import sola2lunar.Lunar;
import sola2lunar.LunarSolarConverter;
import sola2lunar.Solar;
public class DatePicker extends EditText implements DatePickerDialog.OnDateSetListener {
public interface OnDateSetListener {
public void onDateSet(DatePicker view, int year, int month, int day);
}
private Lunar lunarBirthday;
private Lunar lunarCurrent;
protected int year;
protected int month;
protected int day;
protected long maxDate = -1;
protected long minDate = -1;
protected OnDateSetListener onDateSetListener = null;
protected java.text.DateFormat dateFormat;
public OnDateSetListener getOnDateSetListener() {
return onDateSetListener;
}
public void setOnDateSetListener(OnDateSetListener onDateSetListener) {
this.onDateSetListener = onDateSetListener;
}
public DatePicker(Context context, AttributeSet attrs) {
super(context, attrs);
dateFormat = DateFormat.getMediumDateFormat(getContext());
setInputType(InputType.TYPE_DATETIME_VARIATION_DATE);
setFocusable(false);
setToday();
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
updateText();
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
updateText();
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
updateText();
}
public void setDate(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
updateText();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN)
showDatePicker();
return super.onTouchEvent(event);
}
public java.text.DateFormat getDateFormat() {
return dateFormat;
}
public void setDateFormat(java.text.DateFormat dateFormat) {
this.dateFormat = dateFormat;
updateText();
}
public void setMaxDate(int year, int month, int day) {
Calendar c = Calendar.getInstance();
c.set(year, month, day, 23, 59, 59);
this.maxDate = c.getTimeInMillis();
}
public void setMinDate(int year, int month, int day) {
Calendar c = Calendar.getInstance();
c.set(year, month, day, 0, 0, 0);
this.minDate = c.getTimeInMillis();
}
public void setToday() {
Calendar c = Calendar.getInstance();
setDate(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
}
protected void showDatePicker() {
DatePickerDialog datePickerDialog;
datePickerDialog = new DatePickerDialog(
getContext(),
this,
getYear(),
getMonth(),
getDay());
if (this.maxDate != -1) {
datePickerDialog.getDatePicker().setMaxDate(maxDate);
}
if (this.minDate != -1) {
datePickerDialog.getDatePicker().setMinDate(minDate);
}
datePickerDialog.show();
}
#Override
public void onDateSet(android.widget.DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
setDate(year, monthOfYear, dayOfMonth);
clearFocus();
Solar solar = new Solar();
solar.solarYear = year;
solar.solarMonth = monthOfYear+1;
solar.solarDay = dayOfMonth;
lunarBirthday = LunarSolarConverter.SolarToLunar(solar);
String currentDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String[] curr = currentDate.split("-");
Solar solar_curr = new Solar();
solar_curr.solarDay = Integer.parseInt(curr[2]);
solar_curr.solarMonth = Integer.parseInt(curr[1]);
solar_curr.solarYear = Integer.parseInt(curr[0]);
lunarCurrent = LunarSolarConverter.SolarToLunar(solar_curr);
TimePredictorActivity.ageMom = lunarCurrent.lunarYear - lunarBirthday.lunarYear;
TimePredictorActivity.tv_lunarAge.setText("Lunar age: " + TimePredictorActivity.ageMom);
// if(onDateSetListener != null)
// onDateSetListener.onDateSet(this, year, month, day);
}
public void updateText() {
Calendar cal = new GregorianCalendar(getYear(), getMonth(), getDay());
setText(dateFormat.format(cal.getTime()));
}
}
In the MainActivity extend DatePicker class. And I have to override the OnDateSet() method, so how to update the UI such as TextView in the onDateSet() method of MainActivity? After debugged it always run cursor to onDateSet() of DatePicker class? Please help me clear the reason why?

How to disable future date with Datepicker

I am trying to disable date picker for future date but getting not idea...
Here is the what I have tried:
bday.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Calendar mcurrentDate=Calendar.getInstance();
year=mcurrentDate.get(Calendar.YEAR);
month=mcurrentDate.get(Calendar.MONTH);
day=mcurrentDate.get(Calendar.DAY_OF_MONTH);
DatePickerDialog mDatePicker =new DatePickerDialog(CreateAccountActivity.this, new OnDateSetListener()
{
#Override
public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday)
{
year = selectedyear;
month = selectedmonth;
day = selectedday;
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
String currenttime = new String(dateFormat.format(cal.getTime()));
String selectedtime = new String (new StringBuilder().append(year).append("-").append(month+1).append("-").append(day));
String futuretime = new String (dateFormat.format(System.currentTimeMillis()));
if(selectedtime==currenttime)
{
Toast.makeText(getApplicationContext(), "you were not born in the future", Toast.LENGTH_SHORT).show();
bday.setText("");
}
else
{
bday.setText(new StringBuilder().append(year).append("-").append(month+1).append("-").append(day));
}}
},year, month, day);
mDatePicker.setTitle("Please select date");
mDatePicker.show();
}
});
Stackoverflow suggested to use:
mDatePicker.getDatePicker().setMaxDate(System.currentTimeMillis());
but in above condition how should I use this.?
I am trying to disable future date. But not getting any idea :(
After Declaring Listener on DatePicker use the mDatePicker.getDatePicker().setMaxDate(System.currentTimeMillis());
package com.keshav.datePicker_With_Hide_Future_Past_Date;
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.util.Calendar;
public class MainActivity extends AppCompatActivity {
EditText ed_date;
int year;
int month;
int day;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed_date=(EditText) findViewById(R.id.et_date);
ed_date.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Calendar mcurrentDate=Calendar.getInstance();
year=mcurrentDate.get(Calendar.YEAR);
month=mcurrentDate.get(Calendar.MONTH);
day=mcurrentDate.get(Calendar.DAY_OF_MONTH);
final DatePickerDialog mDatePicker =new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener()
{
#Override
public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday)
{
ed_date.setText(new StringBuilder().append(year).append("-").append(month+1).append("-").append(day));
int month_k=selectedmonth+1;
}
},year, month, day);
mDatePicker.setTitle("Please select date");
// TODO Hide Future Date Here
mDatePicker.getDatePicker().setMaxDate(System.currentTimeMillis());
// TODO Hide Past Date Here
// mDatePicker.getDatePicker().setMinDate(System.currentTimeMillis());
mDatePicker.show();
}
});
}
}

How to use DatePicker widget in android?

enter code hereI have used the DatePicker widget in android.Upon clicking that I want the datePickerdialog to show up and date should be set and the same I want to set to a textview.
Thanks in advance.
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dpd = new DatePickerDialog(this,new DatePickerDialog.OnDateSetListener() {
#Override
// TODO Auto-generated method stub
public void onDateSet(DatePicker view, int year,int monthOfYear, int dayOfMonth) {
startDateTextView.setVisibility(View.VISIBLE);
startDateTextView.setText(dayOfMonth + "-"+ (monthOfYear + 1) + "-" + year);
}
}, year, month, day);
dpd.show();
the above code i used,bt this works before i click on datepicker. please let me know how to use OnClickListener of datepicker to this
Try below code.
package com.example.datetimepicker;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
import java.text.DateFormat;
import java.util.Calendar;
public class MainActivity extends Activity {
Button date,time;
TextView preview;
int year,monthofyear,dayofmonth,hourofday,minute;
Calendar cal = Calendar.getInstance();
DateFormat dt = DateFormat.getInstance();
TimePickerDialog.OnTimeSetListener tpd;
DatePickerDialog.OnDateSetListener dpd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
date = (Button)findViewById(R.id.date);
date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new DatePickerDialog(MainActivity.this,dpd,
cal.get(Calendar.YEAR),cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH)).show();
}
});
time = (Button)findViewById(R.id.time);
time.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new TimePickerDialog(MainActivity.this,tpd,
cal.get(Calendar.HOUR_OF_DAY),cal.get(Calendar.MINUTE),
false).show();
}
});
preview = (TextView)findViewById(R.id.textView1);
dpd = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, monthOfYear);
cal.set(Calendar.DAY_OF_MONTH, dayOfMonth);
preview.setText(new StringBuilder().append(year+"/")
.append(monthOfYear+"/").append(dayOfMonth));
}
};
tpd = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker arg0, int hourofday, int minute) {
// TODO Auto-generated method stub
cal.set(Calendar.HOUR_OF_DAY, hourofday);
cal.set(Calendar.MINUTE, minute);
preview.setText(new StringBuilder().append(hourofday+"/")
.append(minute));
}
};
}
}
you can use like this:
//variables
DatePicker dpResult;
static final int DATE_DIALOG_ID = 999;
//methods
public void setCurrentDateOnView() {
dpResult = (DatePicker) findViewById(R.id.dpResult);
dpResult.setVisibility(View.GONE );
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 datepicker
dpResult.init(year-7, month, day, null);
}
#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
mbirthdayView.setText( (day)+(".")+(month + 1)+(".")+(year));
// set selected date into datepicker also
dpResult.init(year, month, day, null);
}
};
and finally you can call datepicker like this:
showDialog(DATE_DIALOG_ID);

Categories

Resources