Setting up a DatePicker - android

I am using the Android pallet DatePicker. As of right now I am able to display the calendar but I'm unable to store any user selected date/time.
JAVA CODE
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import java.util.Calendar;
public class date extends AppCompatActivity {
MainActivity z = new MainActivity();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_date);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "", Snackbar.LENGTH_LONG).setAction("Action", null).show();
}
});
}
}
XML FILE
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="aa.android.group3.com.finalassignmentalert.date"
tools:showIn="#layout/activity_date">
<CalendarView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/calendarView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
Any help that can offered would be greatly appreciated.
Thank you

Instead of using <CalenderView> tag I suggest you to use DatePicker and Calender in Java class.
Example code ->
public class MainActivity extends Activity {
private DatePicker datePicker;
private Calendar calendar;
private TextView dateView;
private int year, month, day;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dateView = (TextView) findViewById(R.id.textView3);
calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
showDate(year, month+1, day);
}
#SuppressWarnings("deprecation")
public void setDate(View view) {
showDialog(999);
Toast.makeText(getApplicationContext(), "ca", Toast.LENGTH_SHORT)
.show();
}
#Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 999) {
return new DatePickerDialog(this, myDateListener, year, month, day);
}
return null;
}
private DatePickerDialog.OnDateSetListener myDateListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
// arg1 = year
// arg2 = month
// arg3 = day
showDate(arg1, arg2+1, arg3);
}
};
private void showDate(int year, int month, int day) {
dateView.setText(new StringBuilder().append(day).append("/")
.append(month).append("/").append(year));
}
}

Related

how to keep min Age Limit in Android

Am building an demo app, in which I would like to allow people who are above 21yrs, how do I do this.
I want to take there DOB and calculate the age, with the current year. I want to use DatePicker, but messed up seeing different snippets. thanks
This is a simple code that will guide your to achieve what your are planning for.
It uses a button click to launch the DatePicker Dialog
Layout file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.inducesmile.mydatepicker.MainActivity">
<EditText
android:id="#+id/display_dob"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="24dp"/>
<Button
android:id="#+id/select_dob"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="16dp"
android:textColor="#000000"
android:textSize="15sp"
android:text="Select your Date of birth"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
Then the Activity class
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Toast;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
private DatePickerFragment datePickerFragment;
private static Calendar dateTime = Calendar.getInstance();
protected static int mYear;
protected static int mMonth;
protected static int mDay;
private static final int allowedDOB = 21;
protected static EditText displayDOB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
displayDOB = (EditText)findViewById(R.id.display_dob);
Button dobButton = (Button) findViewById(R.id.select_dob);
dobButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
datePickerFragment = new DatePickerFragment();
datePickerFragment.show(getSupportFragmentManager(), "Select Your Birthday");
}
});
}
public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Using current date as start Date
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
// Get DatePicker Dialog
return new DatePickerDialog(getActivity(), this, mYear, mMonth, mDay);
}
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
dateTime.set(mYear, monthOfYear, dayOfMonth);
long selectDateInMilliSeconds = dateTime.getTimeInMillis();
Calendar currentDate = Calendar.getInstance();
long currentDateInMilliSeconds = currentDate.getTimeInMillis();
SimpleDateFormat simpleDate = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
String strDt = simpleDate.format(dateTime.getTime());
displayDOB.setText(strDt);
if (selectDateInMilliSeconds > currentDateInMilliSeconds) {
Toast.makeText(getActivity(), "Your birthday date must come before taday's date", Toast.LENGTH_LONG).show();
return;
}
long diffDate = currentDateInMilliSeconds - selectDateInMilliSeconds;
Calendar yourAge = Calendar.getInstance();
yourAge.setTimeInMillis(diffDate);
long returnedYear = yourAge.get(Calendar.YEAR) - 1970;
if (returnedYear < allowedDOB) {
Toast.makeText(getActivity(), "Sorry!!! You are not allowed to use this app", Toast.LENGTH_LONG).show();
return;
} else {
// move to another activity page
}
}
}
}
if you want to limit the age from datepicker itself you can do like this,
<com.deevita.patient.Custom_Layouts.editText
android:id="#+id/dob"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:drawableStart="#drawable/ic_date_icon"
android:drawablePadding="#dimen/drawable_padding"
android:focusable="false"
android:hint="#string/birthday"
android:inputType="date"
android:padding="#dimen/padding_common_new"
android:textSize="#dimen/font_small">
</com.deevita.patient.Custom_Layouts.editText>
add the following code in java
dob.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR,-21); // the age you want to limit
int yy = calendar.get(Calendar.YEAR);
int mm = calendar.get(Calendar.MONTH);
int dd = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePicker = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
String date = String.valueOf(dayOfMonth) + "-" + String.valueOf(monthOfYear + 1)
+ "-" + String.valueOf(year);
dob.setText(date);
}
}, yy, mm, dd);
datePicker.getDatePicker().setMaxDate(calendar.getTimeInMillis());
datePicker.show();
}
});
if user entered age
driverage = edtdriverage.getText().toString();
else if ( Integer.parseInt(driverage)> 55 || Integer.parseInt(driverage)< 18) {
GlobalMethods.Toast(AddDriverActivity.this, getString(R.string.enter_driver_age_min));
cancel = true;
}
you can achieve by validation method also

date picker dialog show on edit text double click

I have a search activity with two edit text fields. I like on edit text click date picker dialog to be show. However when I click on edit text, first the keyboard is shown, then after second click the date picker dialog is shown. Could somebody help me?
Here is activity code
package com.example.firstdemoapp.activities;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import com.example.firstdemoapp.R;
import com.example.firstdemoapp.model.StatusDK;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
public class SearchingTaxActivity extends Activity implements OnClickListener,
DatePickerDialog.OnDateSetListener, OnItemSelectedListener {
private Calendar calendarFrom;
private Calendar calendarTo;
private String myFormat;
private SimpleDateFormat sdf;
private EditText dateFrom;
private EditText dateTo;
private EditText activeEditText;
private Calendar activeCalendar;
private Spinner spinnerStatusDK;
private ArrayAdapter spinnerArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_tax);
calendarFrom = Calendar.getInstance();
calendarTo = Calendar.getInstance();
myFormat="dd/MM/yyyy";
sdf = new SimpleDateFormat(myFormat, Locale.US);
dateFrom = (EditText) findViewById(R.id.dateFrom);
dateTo = (EditText) findViewById(R.id.dateTo);
spinnerStatusDK=(Spinner)findViewById(R.id.spinnerStatusDK);
spinnerArrayAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, new StatusDK[] {
new StatusDK( 0, "0" ),
new StatusDK( 1, "1" ),
new StatusDK( 2, "2" ),
});
spinnerStatusDK.setAdapter(spinnerArrayAdapter);
spinnerStatusDK.setOnItemSelectedListener(this);
dateFrom.setOnClickListener(this);
dateTo.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == dateFrom) {
activeCalendar = calendarFrom;
activeEditText = dateFrom;
} else if (v == dateTo) {
activeCalendar = calendarTo;
activeEditText = dateTo;
}
new DatePickerDialog(SearchingTaxActivity.this, this,
activeCalendar.get(Calendar.YEAR),
activeCalendar.get(Calendar.MONTH),
activeCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
activeCalendar.set(Calendar.YEAR, year);
activeCalendar.set(Calendar.MONTH, monthOfYear);
activeCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
if (activeEditText != null) {
activeEditText.setText(sdf.format(activeCalendar.getTime()));
}
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
and the layout for the activity is:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}" >
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/dateFromTextView"
/>
<EditText
android:id="#+id/dateFrom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/edit_datefrom"
/>
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/dateToTextView"
/>
<EditText
android:id="#+id/dateTo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/edit_dateto"
/>
<Spinner
android:id="#+id/spinnerStatusDK"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
I added android:focusableInTouchMode="false" for edit text in the xml file and this helped me. Because first focus event is fired, and then click event is fired.
you can try to hide a keyboard using InputMethodManager class
private void hideKeyboard(EditText et) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
}
This is best solution which is very useful for open any DatePicker & TimePicker Dialog from EditText,
editdate.setFocusable(false);
editdate.setKeyListener(null);

Setting date using DialogFragment and Android Annotations

I have problem with writing date I selected in DatePicker with Dialog Fragment.
I`m trying to do this using Android Annotations. Problem is, I have to implement behavior for setting this date to TextView on OnDateSet function in DatePickerFragment class.
How can I choose in which TextView, which #Click should write?
Code below:
#EActivity(R.layout.activity_main_search)public class SearchActivity extends FragmentActivity{
private int mFYear, mFMonth, mFDay, mTYear, mTMonth, mTDay;
(R.id.main_search_city)
EditText cityET;
#ViewById(R.id.main_search_price)
EditText priceET;
#ViewById(R.id.main_search_from)
TextView dateFromTV;
#ViewById(R.id.main_search_to)
TextView dateToTV;
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 year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
}
}
#AfterViews
public void setCurrentdateonView(){
final Calendar c = Calendar.getInstance();
mFYear = c.get(Calendar.YEAR);
mFMonth = c.get(Calendar.MONTH)+1;
mFDay = c.get(Calendar.DAY_OF_MONTH);
dateFromTV.setText(new StringBuffer().append(mFDay).append("-").append(mFMonth).append("-").append(mFYear).append(""));
dateToTV.setText(new StringBuffer().append(mFDay).append("-").append(mFMonth).append("-").append(mFYear).append(""));
}
#App
HApplication mApp;
#Click(R.id.main_search_from_btn)
public void showFromDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
#Click(R.id.main_search_to_btn)
public void showToDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
#Click(R.id.main_search_btn)
public void openSearch(){
//SearchActivity_.intent(this).city(cityET.getText().toString()).start();
ListActivity_.intent(this).city(cityET.getText().toString()).price(priceET.getText().toString()).start();
}}
Functions that should realise that date writing are:
#Click(R.id.main_search_from_btn)
public void showFromDatePickerDialog(View v)
it should write date to dateFromTV
and
#Click(R.id.main_search_to_btn)
public void showToDatePickerDialog(View v)
it should write date to dateToTV
I SOLVED THE PROBLEM.
What I needed was flags, which were set on each button #Click and then in onDateSet case switch with flag number check. Maybe it will help someone, because it took me whole day to figure it out...
The Click annotation is just for triggering the dialog.
You should implement a callback method through listener interfaces described here:
http://developer.android.com/guide/topics/ui/dialogs.html#PassingEvents
EDIT: I implemented a version for myself, here is the code:
MainActivity.java:
package com.example.datepickerexample;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.TextView;
import com.example.datepickerexample.DatePickerFragment.DatePickerDialogListener;
public class MainActivity extends FragmentActivity implements
DatePickerDialogListener {
TextView lbl_from, lbl_to, cpn_from, cpn_to;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cpn_from = (TextView) findViewById(R.id.cpn_from);
cpn_to = (TextView) findViewById(R.id.cpn_to);
lbl_from = (TextView) findViewById(R.id.lbl_from);
lbl_to = (TextView) findViewById(R.id.lbl_to);
}
public void showFromDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
Bundle bundle = new Bundle();
bundle.putBoolean("isFromDate", true);
newFragment.setArguments(bundle);
newFragment.show(getSupportFragmentManager(), "datePicker");
}
public void showToDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
Bundle bundle = new Bundle();
bundle.putBoolean("isFromDate", false);
newFragment.setArguments(bundle);
newFragment.show(getSupportFragmentManager(), "datePicker");
}
#Override
public void onDatePicked(DialogFragment dialog, Calendar c,
boolean isFromDate) {
String strdate = null;
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
if (c != null) {
strdate = sdf.format(c.getTime());
}
if (isFromDate) {
lbl_from.setText(strdate);
} else {
lbl_to.setText(strdate);
}
}
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="#+id/cpn_from"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_margin="6dp"
android:text="#string/from_date" />
<TextView
android:id="#+id/lbl_from"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#id/cpn_from"
android:layout_toRightOf="#id/cpn_from" />
<Button
android:id="#+id/btn_from"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/cpn_from"
android:onClick="showFromDatePickerDialog"
android:text="#string/pick_from_date" />
<TextView
android:id="#+id/cpn_to"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/btn_from"
android:layout_margin="6dp"
android:text="#string/to_date" />
<TextView
android:id="#+id/lbl_to"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/btn_from"
android:layout_alignBaseline="#id/cpn_to"
android:layout_toRightOf="#id/cpn_to" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/cpn_to"
android:onClick="showToDatePickerDialog"
android:text="#string/pick_to_date" />
</RelativeLayout>
DatePickerFragment.java:
package com.example.datepickerexample;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.DatePicker;
public class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
public interface DatePickerDialogListener {
public void onDatePicked(DialogFragment dialog, Calendar c,
boolean isFromDate);
}
// Use this instance of the interface to deliver action events
DatePickerDialogListener mListener;
boolean isFromDate;
public static DatePickerFragment newInstance(boolean isFromDate) {
DatePickerFragment instance = new DatePickerFragment();
instance = new DatePickerFragment();
Bundle args = new Bundle();
args.putBoolean("isFromDate", isFromDate);
instance.setArguments(args);
return instance;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isFromDate = getArguments().getBoolean("isFromDate");
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
Calendar c = Calendar.getInstance();
c.set(year, month, day);
mListener.onDatePicked(this, c, isFromDate);
}
// Override the Fragment.onAttach() method to instantiate the
// NoticeDialogListener
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeDialogListener so we can send events to the
// host
mListener = (DatePickerDialogListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement NoticeDialogListener");
}
}
}

Android DatePicker Button not working

Ok so i have this app i'm working on... It has a left menu slide-out using ABS and the sliding menu lib. Here's my fragment that is launched once the menu item is selected. This fragment is suppose to have a text field to display the date you select and a button to select a date. Any idea's on what i'm doing wrong that SelectDateFragment is erroring?
Here's the XML layout:
<EditText
android:id="#+id/dateselected"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="56dp"
android:ems="10"
android:inputType="date" >
<requestFocus />
</EditText>
<Button
android:id="#+id/pickdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/dateselected"
android:layout_toRightOf="#+id/dateselected"
android:contentDescription="#string/selectdate"
android:cropToPadding="true"
android:onClick="selectDate"
android:src="#drawable/ic_datepicker" />
</RelativeLayout>
Here's the java class:
import java.util.Calendar;
import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.app.Fragment;
import android.support.v4.app.DialogFragment;
import android.widget.EditText;
public class DatePicker extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstaceState){
return inflater.inflate(R.layout.fragment_charting, container, false);
}
EditText mEdit;
#Override
public void onStart() {
super.onStart();
}
public void selectDate(View view) {
DialogFragment newFragment = new SelectDateFragment();
newFragment.show(getFragmentManager(), "DatePicker");
}
public void populateSetDate(int year, int month, int day) {
mEdit = (EditText)getView().findViewById(R.id.dateselected);
mEdit.setText(month+"/"+day+"/"+year);
}
public class SelectDateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar calendar = Calendar.getInstance();
int yy = calendar.get(Calendar.YEAR);
int mm = calendar.get(Calendar.MONTH);
int dd = calendar.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, yy, mm, dd);
}
#Override
public void onDateSet(android.widget.DatePicker view, int year, int monthOfYear, int dayOfMonth) {
// TODO Auto-generated method stub
populateSetDate(year, monthOfYear, dayOfMonth);
}
}
}
EDIT:
I'm trying to follow http://javapapers.com/android/android-datepicker/
The error i'm getting is the fragment inner class should be static. I don't understand enough about this topic, and from reading more i still do not, to understand why his works and mine does not.
try this one
shipdate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(999);
}
});
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case 999:
// 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) {
final Calendar cf = Calendar.getInstance();
year = cf.get(Calendar.YEAR);
month = cf.get(Calendar.MONTH);
day = cf.get(Calendar.DAY_OF_MONTH);
// set selected date into textview
shipdate.setText(new StringBuilder().append(month + 1)
.append("-").append(day).append("-").append(year)
.append(" "));
}
};

How to pass data from date picker and spinner to another activity

I'm a beginning android developer.
I need to pass data from two date pickers and a spinner to another activity.
Can some one help me with this code:
package qi.com;
import java.text.DateFormat;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
//multi date input
public class CoaActivity extends Activity implements AdapterView.OnItemSelectedListener {
TextView selection;
TextView mDateStart;
TextView mDateEnd;
Button mPickStart;
Button mPickEnd;
Calendar startDate;
Calendar EndDate;
int mYear;
int mMonth;
int mDay;
//list menu
String[] items = {"Pendapatan","Biaya"};
static final int DATE_DIALOG_ID = 0;
private TextView activeDateDisplay;
private Calendar activeDate;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//display to text view from list View
selection = (TextView) findViewById(R.id.selection);
Spinner spin= (Spinner) findViewById(R.id.spinner);
spin.setOnItemSelectedListener(this);
ArrayAdapter<String> aa= new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, items);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(aa);
//capture view elements
mDateStart = (TextView) findViewById(R.id.DateStar);
mPickStart = (Button) findViewById(R.id.btn_PickDateStart);
//current date
startDate = Calendar.getInstance();
//listener click button
mPickStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDateDialog(mDateStart, startDate);
}
});
//END Date
mDateEnd = (TextView) findViewById(R.id.DateEnd);
mPickEnd = (Button) findViewById(R.id.btn_PickDateEnd);
EndDate = Calendar.getInstance();
//listener click button
mPickEnd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDateDialog(mDateEnd, EndDate);
}
});
//display current date
updateDisplay(mDateStart, startDate);
updateDisplay(mDateEnd, EndDate);
//Detail("tes");
}
private void updateDisplay(TextView dateDisplay, Calendar date) {
dateDisplay.setText(
new StringBuilder()
// Month is 0 based so add 1
//.append(date.get(Calendar.DAY_OF_MONTH)).append("-")
.append(date.get(Calendar.DATE)).append("-")
.append(date.get(Calendar.MONTH) + 1).append("-")
.append(date.get(Calendar.YEAR)).append(" "));
//.append(DateFormat.getDateInstance(Calendar.MONTH)));
}
public void showDateDialog(TextView dateDisplay, Calendar date) {
activeDateDisplay = dateDisplay;
activeDate = date;
showDialog(DATE_DIALOG_ID);
}
private OnDateSetListener dateSetListener = new OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
activeDate.set(Calendar.YEAR, year);
activeDate.set(Calendar.MONTH, monthOfYear);
//activeDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
activeDate.set(Calendar.DATE, dayOfMonth);
updateDisplay(activeDateDisplay, activeDate);
unregisterDateDisplay();
}
};
private void unregisterDateDisplay() {
activeDateDisplay = null;
activeDate = null;
}
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, dateSetListener, activeDate.get(Calendar.YEAR), activeDate.get(Calendar.MONTH), activeDate.get(Calendar.DATE));
}
return null;
}
protected void onPrepareDialog(int id, Dialog dialog) {
super.onPrepareDialog(id, dialog);
switch (id) {
case DATE_DIALOG_ID:
((DatePickerDialog) dialog).updateDate(activeDate.get(Calendar.YEAR), activeDate.get(Calendar.MONTH), activeDate.get(Calendar.DATE));
break;
}
}
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
selection.setText(items[position]);
Intent grid=new Intent(this, Grid.class);
this.startActivity(grid);
//send to another activity
//Detail(items[position]);
}
public void onNothingSelected(AdapterView<?> parent) {
selection.setText("");
}
//another activity
public void Detail(String id)
//public void Detail()
{
//Intent detail=new Intent(con, Detail.class);
Intent grid=new Intent(this, Grid.class);
grid.putExtra("IDP", id);
this.startActivity(grid);
//Toast.makeText(this, "list : " , Toast.LENGTH_SHORT).show();
}
}
This is the xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Mulai dari :" />
<TextView
android:id="#+id/DateStar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="" />
<Button
android:id="#+id/btn_PickDateStart"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Tanggal Awal" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Sampai dengan :" />
<TextView
android:id="#+id/DateEnd"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="" />
<Button
android:id="#+id/btn_PickDateEnd"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Tanggal Akhir" />
<TextView
android:id="#+id/selection"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<Spinner
android:id="#+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop="false" />
</LinearLayout>
Use the long value that Date gives you, and put it in the extras, along with everything else you are sending to the activity.

Categories

Resources