I have created a date picker.
This is my fragment:
import java.util.Calendar;
import my.project.mysimplecal.MainActivity.DateDialogFragmentListener;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.os.Bundle;
import android.widget.DatePicker;
public class DateDialogFragment extends DialogFragment {
public static String TAG = "DateDialogFragment";
static Context mContext;
static int mYear;
static int mMonth;
static int mDay;
static DateDialogFragmentListener mListener;
public static DateDialogFragment newInstance(Context context,
DateDialogFragmentListener listener, Calendar now) {
DateDialogFragment dialog = new DateDialogFragment();
mContext = context;
mListener = listener;
mYear = now.get(Calendar.YEAR);
mMonth = now.get(Calendar.MONTH);
mDay = now.get(Calendar.DAY_OF_MONTH);
Bundle args = new Bundle();
args.putString("title", "Set Date");
dialog.setArguments(args);
return dialog;
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new DatePickerDialog(mContext, mDateSetListener, mYear, mMonth,
mDay);
}
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
mListener.updateChangedDate(year, monthOfYear, dayOfMonth);
}
};
}
And this is my Main activity
import java.util.Calendar;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.app.FragmentTransaction;
import android.graphics.drawable.Drawable;
public class MainActivity extends Activity {
DateDialogFragment frag;
Button btnPickDate;
CompoundButton btnCycleStart;
CompoundButton btnCycleStop;
CompoundButton btnPillStart;
CompoundButton btnPillStop;
Calendar now;
TextView textView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
now = Calendar.getInstance();
btnPickDate = (Button) findViewById(R.id.pickDate);
btnCycleStart = (CompoundButton) findViewById(R.id.cycleStart);
btnCycleStop = (CompoundButton) findViewById(R.id.cycleStop);
btnPillStart = (CompoundButton) findViewById(R.id.pillStart);
btnPillStop = (CompoundButton) findViewById(R.id.pillStop);
textView = (TextView) findViewById(R.id.showDate);
textView.setText(String.valueOf(now.get(Calendar.DAY_OF_MONTH)) + "-"
+ String.valueOf(now.get(Calendar.MONTH) + 1) + "-"
+ String.valueOf(now.get(Calendar.YEAR)));
//Set the calendar button on listening
btnPickDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog();
}
});
//Set all the Compound button on listening and
//set one alternative to another. If start is
//clicked then stop cannot be clicked
btnCycleStart
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
btnCycleStop.setChecked(false);
}
}
});
btnCycleStop
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
btnCycleStart.setChecked(false);
}
}
});
btnPillStart
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
btnPillStop.setChecked(false);
}
}
});
btnPillStop
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
btnPillStart.setChecked(false);
}
}
});
}
//Set the text from the fragment class choice
public void showDialog() {
FragmentTransaction ft = getFragmentManager().beginTransaction();
frag = DateDialogFragment.newInstance(this,
new DateDialogFragmentListener() {
public void updateChangedDate(int year, int month, int day) {
textView.setText(String.valueOf(day) + "-"
+ String.valueOf(month + 1) + "-"
+ String.valueOf(year));
now.set(year, month, day);
}
}, now);
frag.show(ft, "DateDialogFragment");
}
// Listener between the Date Dialog fragment and the
// activity to update the buttons date
public interface DateDialogFragmentListener {
public void updateChangedDate(int year, int month, int day);
}
}
How could I set a different format for the date to be shown, depending on which State the user is living ? For example in Italy people are used to see day/month/year but in USA they are used to see month/day/year. I hope someone is able and willing to answer because I've searched for hours without success.
Instead of doing your own formatting from Calendar fields, use DateFormat.getDateInstance() to get a DateFormat object appropriate to the current Locale. Use format() to format a Date to a string then. You can use a Calendar to convert between the year/month/day fields and a Date.
Related
I want to get the selected Date from the DatePickerDialog back to my Fragment.
Whe i test it, i only get in the Build Log this Error:
E/ViewRootImpl: sendUserActionEvent() mView == null
Testing my code on an Samsung Galaxy S6 Edge (7.0)
The Dialog appears, i can choose a date, click on ok but dont get the result to my TextView... Did i forget a little detail??
My Fragment where i call the DatePickerDialog:
package at.marcelklein.drautaxi;
import android.app.DatePickerDialog;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import java.text.DateFormat;
import java.util.Calendar;
/**
* Created by Marcel on 10.09.2017.
*/
public class FourthFragment extends Fragment implements DatePickerDialog.OnDateSetListener {
View myView;
TextView textView;
Button btnDayStart, btnDayEnd;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.fourth_layout, container, false);
btnDayStart = (Button) myView.findViewById(R.id.button_daystart);
btnDayEnd = (Button) myView.findViewById(R.id.button_dayend);
textView = (TextView) myView.findViewById(R.id.textView12);
btnDayStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment datePicker = new DatePickerFragment();
FragmentTransaction ft = ((FragmentActivity)getActivity()).getSupportFragmentManager().beginTransaction();
datePicker.show(ft, "datepicker");
}
});
btnDayEnd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//showDialog();
}
});
return myView;
}
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
String currentDateString = DateFormat.getDateInstance(DateFormat.FULL).format(c.getTime());
textView.setText(currentDateString);
}
}
DatePickerDialog Fragment:
package at.marcelklein.drautaxi;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import java.util.Calendar;
public class DatePickerFragment extends DialogFragment {
DatePickerDialog.OnDateSetListener onDateSet;
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), onDateSet, year, month, day);
}
}
Thanks in advance!
You forgot to assign your fragment as a listener. Add it as listener like this
btnDayStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment datePicker = new DatePickerFragment();
datePicker.onDateSet = FourthFragment.this
FragmentTransaction ft = ((FragmentActivity)getActivity()).getSupportFragmentManager().beginTransaction();
datePicker.show(ft, "datepicker");
}
});
I changed my code to this: DatePickerDialog
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, year, month, day);
}
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
TextView tv = (TextView) getActivity().findViewById(R.id.textView12);
DecimalFormat df = new DecimalFormat("00");
tv.setText("Gewähltes Datum:");
tv.setText(tv.getText() + "\nJahr: " + year);
tv.setText(tv.getText() + "\nMonat: " + df.format(month));
tv.setText(tv.getText() + "\nTag: " + df.format(day));
}
----------- And my Fragment where i call the DatePickerDialog:
public class FourthFragment extends Fragment {
View myView;
public TextView textView;
Button btnDayStart, btnDayEnd;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.fourth_layout, container, false);
btnDayStart = (Button) myView.findViewById(R.id.button_daystart);
btnDayEnd = (Button) myView.findViewById(R.id.button_dayend);
textView = (TextView) myView.findViewById(R.id.textView12);
btnDayStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getFragmentManager(), "date Picker");
}
});
return myView;
}
Now i change the TextView directly from the DatePickerDialog.
I think thats not the best Solution...
The think i want is a Range Date Picker like "TimeSquare DatePicker".
But i cant choose days from the past in "TimeSquare DatePicker".
Any suggestions?
As above I am trying to work out how to pass back the date selected by the user. I have worked out how to get the date selected by using the onDateSet method but I do not know how to feed this back to the parent fragment, and then set the EditText text to the date selected.
package com.example.androidvehicle;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
public class fragmentServicing extends Fragment {
callBack mCallBack;
Button mot;
Button servicing;
Button tax;
EditText txtService;
final int Date_Dialog_ID=0;
int cDay,cMonth,cYear; // this is the instances of the current date
Calendar cDate;
int sDay,sMonth,sYear; // this is the instances of the entered date
int id_dialog = 1;
int yr, day, month = 0;
// interfacing back to activity
public interface callBack
{
public void onItemSelected(String id);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_servicing, container, false);
txtService = (EditText) view.findViewById(R.id.txtServiceDate);
mot = (Button) view.findViewById(R.id.buttonMOT);
servicing = (Button) view.findViewById(R.id.buttonService);
servicing.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// this will then pass back to the activity the string hello
mCallBack.onItemSelected("hello");
getActivity().showDialog(1);
}
});
mot.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getActivity().showDialog(1);
}
});
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallBack = (callBack) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
// this is an override for when the dialog is created
protected Dialog onCreateDialog(int id)
{
switch(id)
{
// this will return a date picker dialog if 1 is passed
// could use another number for another dialog
case 1:
// passes it the current date
return new DatePickerDialog(getActivity(), mDateSetListener, yr, month, day);
}
return null;
}
// this returns the date back that has been selected by the user
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
yr = year;
month = monthOfYear;
day = dayOfMonth;
Log.d("date selected", "year "+ yr+ " month " +month+" day "+day);
}
};
}
You can set DateListner on Edittext onClicklistner..
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
public class DateListener implements OnClickListener, OnDateSetListener {
private Activity activity;
private int year;
private int monthOfYear;
private int dayOfMonth;
private View touchedView;
public DateListener(Activity activity) {
this.activity = activity;
final Calendar c = Calendar.getInstance();
this.year = c.get(Calendar.YEAR);
this.monthOfYear = c.get(Calendar.MONTH);
this.dayOfMonth = c.get(Calendar.DAY_OF_MONTH);
}
public int getYear() {
return year;
}
public int getMonth() {
return monthOfYear;
}
public int getDay() {
return dayOfMonth;
}
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
this.year = year;
this.monthOfYear = monthOfYear + 1;
this.dayOfMonth = dayOfMonth;
updateDisplay();
updateEditText();
}
#Override
public void onClick(View v) {
touchedView = v;
new DatePickerDialog(activity,
this, this.getYear(), this.getMonth(), this.getDay()).show();
}
private void updateDisplay() {
((TextView) touchedView).setText(
new StringBuilder()
.append(pad(dayOfMonth)).append(".")
.append(pad(monthOfYear)).append(".")
.append(pad(year)));
}
private void updateEditText() {
((EditText) touchedView).setText(
new StringBuilder()
.append(pad(dayOfMonth)).append(".")
.append(pad(monthOfYear)).append(".")
.append(pad(year)));
}
private static String pad(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
}
In Your Fragment
DateListener dateListener = new DateListener(getActivity());
edittext.setOnClickListener(dateListener);
I am attempting to create a ToDo list for a class that I am in, and how I have the app is that I have an EditText on top to enter an item in the TDL. and then I am using an extended tablelayout to display the items. I also have a button that calls to a second activity that then has 2 other buttons to get the time and date to (hopefully) display on the TDL item after I hit the Done button on the button (where I would like to go back to the main activity) So far I am testing this on an AVD.
So what I think my issue is that I dont think my second activity is passing back the info that I want. According to the debugger, the onActivityResults method from the first one gets called earlier than the second activity gets called.
Here is the first Activity:
package com.parrishb.todo;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.Button;
public class ToDoActivity extends Activity {
SharedPreferences pref;
public final static int ACTIVITY =1;
public static Globals g;
public ToDoView tdv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_to_do);
final EditText myEditText = (EditText)findViewById(R.id.myEditText);
Button mPickDate = (Button) findViewById(R.id.pickDate);
tdv = (ToDoView)findViewById(R.id.tdv);
myEditText.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if(event.getAction()== KeyEvent.ACTION_DOWN){
if((keyCode == KeyEvent.KEYCODE_DPAD_CENTER) || (keyCode == KeyEvent.KEYCODE_ENTER)){
tdv.addRow(ToDoActivity.this, myEditText.getText().toString());
myEditText.setText("");
return true;
}
}
return false;
}
});
// CLick listener for the date/time button
mPickDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(new Intent(ToDoActivity.this, DatePickerActivity.class), ACTIVITY);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(resultCode== RESULT_OK && requestCode== ACTIVITY){
String append= (new StringBuilder().append(data.getStringExtra("Time"))
.append(" ").append(data.getStringExtra("Date")).toString());
tdv.editRow(ToDoActivity.this, append);
}
}
}
Here is my second activity:
package com.parrishb.todo;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
public class DatePickerActivity extends Activity {
private TextView mDateDisplay;
private Button mPickDate;
private int mYear;
private int mMonth;
private int mDay;
private TextView mTimeDisplay;
private Button mPickTime;
private Button done;
private int mhour;
private int mminute;
static final int TIME_DIALOG_ID = 1;
static final int DATE_DIALOG_ID = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.buttonclick);
mDateDisplay =(TextView)findViewById(R.id.date);
mPickDate =(Button)findViewById(R.id.datepicker);
mTimeDisplay = (TextView) findViewById(R.id.time);
mPickTime = (Button) findViewById(R.id.timepicker);
done = (Button)findViewById(R.id.done);
//Pick time's click event listener
mPickTime.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
showDialog(TIME_DIALOG_ID);
}
});
//PickDate's click event listener
mPickDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//DatePickerActivity.this.finishActivityFromChild(DatePickerActivity.this, ToDoActivity.ACTIVITY);
//finishActivity(ToDoActivity.ACTIVITY);
//return;
//DatePickerActivity.this.finish(ToDoActivity.ACTIVITY);
//finish();
DatePickerActivity.this.finish();
}
});
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
mhour = c.get(Calendar.HOUR_OF_DAY);
mminute = c.get(Calendar.MINUTE);
}
#Override
public void finish(){
Intent resultIntent = new Intent();
Bundle b = new Bundle();
b.putString("Date", mDateDisplay.getText().toString());
b.putString("Time", mTimeDisplay.getText().toString());
resultIntent.putExtras(b);
setResult(Activity.RESULT_OK, resultIntent);
super.finish();
}
//-------------------------------------------update date----------------------------------------//
private void updateDate() {
mDateDisplay.setText(
new StringBuilder()
// Month is 0 based so add 1
.append(mMonth + 1).append("/")
.append(mDay).append("/")
.append(mYear).append(" "));
}
//-------------------------------------------update time----------------------------------------//
public void updatetime()
{
mTimeDisplay.setText(
new StringBuilder()
.append(pad(mhour)).append(":")
.append(pad(mminute)));
}
private static String pad(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
//Datepicker dialog generation
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
updateDate();
}
};
// Timepicker dialog generation
private TimePickerDialog.OnTimeSetListener mTimeSetListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mhour = hourOfDay;
mminute = minute;
updatetime();
}
};
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this,
mDateSetListener,
mYear, mMonth, mDay);
case TIME_DIALOG_ID:
return new TimePickerDialog(this,
mTimeSetListener, mhour, mminute, true);
}
return null;
}
}
I had scratched the second activity and brought the date and time picker into the main activity.
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.
Brand new to android and facing a weird problem.Check out the code below
FirstActivity.java:
package experiment.on.it;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class FirstActivity extends Activity implements Button.OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button timeDatePicker = (Button) findViewById(R.id.timeDatePickerBtn);
Button customSpinner = (Button) findViewById(R.id.spinnerBtn);
timeDatePicker.setOnClickListener(this);
customSpinner.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.timeDatePickerBtn:
startActivity(new Intent(this, TimeDatePicker.class));
case R.id.spinnerBtn:
startActivity(new Intent(this, CustomSpinner.class));
}
}
}
As I/you expected that by clicking on the two buttons i.e.
timeDatePicker
customSpinner
a new Activity will starts (TimeDatePicker and CustomSpinner respectively).
Our expectation is correct. But the problem i'm facing that when i click on the timeDatePicker the second activity (CustomSpinner) starts. But if i press the emulator's back button (i.e. the device back button) the first activity(TimeDatePicker) appears. I cant find any keyword to describe this kind of problem. So writing this boring question. Any help will be greatly appreciated from a beginner.(...And i think the answer will be pretty easy and small, which i couldnt get. :-P) The Activities code are given below.
TimeDatePicker.java:
package experiment.on.it;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
public class TimeDatePicker extends Activity {
private TextView mDateDisplay;
private Button mPickDate;
private int mYear;
private int mMonth;
private int mDay;
private TextView mTimeDisplay;
private Button mPickTime;
private int mhour;
private int mminute;
static final int TIME_DIALOG_ID = 3;
static final int DATE_DIALOG_ID = 2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.timedatepicker);
mDateDisplay = (TextView) findViewById(R.id.date);
mPickDate = (Button) findViewById(R.id.datepicker);
mTimeDisplay = (TextView) findViewById(R.id.time);
mPickTime = (Button) findViewById(R.id.timepicker);
// Pick time's click event listener
mPickTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDialog(TIME_DIALOG_ID);
}
});
// PickDate's click event listener
mPickDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
mhour = c.get(Calendar.HOUR_OF_DAY);
mminute = c.get(Calendar.MINUTE);
}
// -------------------------------------------update
// date----------------------------------------//
private void updateDate() {
mDateDisplay.setText(new StringBuilder()
// Month is 0 based so add 1
.append(mDay).append("/").append(mMonth + 1).append("/")
.append(mYear).append(" "));
showDialog(TIME_DIALOG_ID);
}
// -------------------------------------------update
// time----------------------------------------//
public void updatetime() {
mTimeDisplay.setText(new StringBuilder().append(pad(mhour)).append(":")
.append(pad(mminute)));
}
private static String pad(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
// Datepicker dialog generation
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
updateDate();
}
};
// Timepicker dialog generation
private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mhour = hourOfDay;
mminute = minute;
updatetime();
}
};
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
mDay);
case TIME_DIALOG_ID:
return new TimePickerDialog(this, mTimeSetListener, mhour, mminute,
true);
}
return null;
}
}
CustomSpinner.java:
package experiment.on.it;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class CustomSpinner extends Activity {
String[] items = { "this", "is", "a", "really", "really2", "really3",
"really4", "really5", "silly", "list" };
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.spinnerlayout);
Spinner spin =(Spinner)findViewById(R.id.sPinner);
ArrayAdapter adapter = new ArrayAdapter(this,R.layout.radio,R.id.txt,items);
spin.setAdapter(adapter);
}
}
The problem can be solved putting break in every case of the switch
public void onClick(View v) {
switch (v.getId()) {
case R.id.timeDatePickerBtn:
startActivity(new Intent(this, TimeDatePicker.class));
break;
case R.id.spinnerBtn:
startActivity(new Intent(this, CustomSpinner.class));
break;
}
}
try this.
You are missing break; statement in your switch case block.
So, thought the first activity starts and is in your backstack, it is immediately pushed down by the second one due to the missing break and the back button behaves as it should and return you to the the first one.
I think, you missed 'break' in switch~case.
You're missing break in your switch case, along with default. Since your switch case is taking the value of the spinner class, when you end the spinner class by pressing back button, the time-date picker class pops up.