I have a TimePickerDialog that I would like to show the user when she pushes on a button, so that she can choose a time to set the display to (some time other than the current time). Currently when the button is pushed the current time is displayed in a TextView and a Toast. Also the screen Darkens and a small box in the center of screen appears. The TimePickerDialog does not display to the user.
Here's the code;
import java.util.Calendar;
import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class AddAlarmActivity extends FragmentActivity implements TimePickerDialog.OnTimeSetListener, TimePickerDialog.OnDismissListener {
Button setTime;
public int hour_local;
public int minute_local;
public Dialog onCreateDialog;
public TimePicker timePicker;
public TextView displayAlarm;
static final int TIME_DIALOG_ID = 999;
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_alarm);
//add a TextView thing to this part
setTime = (Button) findViewById(R.id.button_set_time);
displayAlarm = (TextView) findViewById(R.id.tvDisplayTime);
setTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onCreateDialog(savedInstanceState);
showTimePickerDialog(timePicker);
displayAlarm.setText(hour_local + ":" + minute_local);
}
});
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
hour_local = c.get(Calendar.HOUR_OF_DAY);
minute_local = c.get(Calendar.MINUTE);
Context context = getApplicationContext();
CharSequence text = hour_local + ":" + minute_local;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getApplicationContext(), this, hour_local, minute_local,
DateFormat.is24HourFormat(getApplicationContext()));
}
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new DialogFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
public void onDismiss(DialogInterface dialog){
System.out.println("oui c'est très bon !");
}
public void onTimeSet(TimePicker view, int hour_l, int minute_l) {
hour_local = hour_l;
minute_local = minute_l;
System.out.println("voila");
}
}
I would advice that you follow the developer sites way of doing it:
Create a static class that handles the dialog fragment
public static class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// Do something with the time chosen by the user
}
}
Call this method in your button on click listener:
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
Source here.
public class AddAlarmActivity extends FragmentActivity {
Button setTime;
public static int hour_local;
public static int minute_local;
public Dialog onCreateDialog;
public TimePicker timePicker;
public static TextView displayAlarm;
public static int hour_alarm;
public static int minute_alarm;
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_alarm);
setTime = (Button) findViewById(R.id.button_set_time);
displayAlarm = (TextView) findViewById(R.id.tvDisplayTime);
final Calendar c = Calendar.getInstance();
hour_local = c.get(Calendar.HOUR_OF_DAY);
minute_local = c.get(Calendar.MINUTE);
displayAlarm.setText(hour_local + ":" + minute_local);
setTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showTimePickerDialog(timePicker);
}
});
}
public void onTimeSet(TimePicker view, int hour_l, int minute_l) {
// intentionally blank
}
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
/*New static class*/
public static class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
hour_local = c.get(Calendar.HOUR_OF_DAY);
minute_local = c.get(Calendar.MINUTE);
Context context = getActivity();
CharSequence text = hour_local + ":" + minute_local;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour_local, minute_local,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hour_l, int minute_l) {
hour_alarm = hour_l;
minute_alarm = minute_l;
displayAlarm.setText(hour_alarm + ":" + minute_alarm);
}
}
}
TimePickerDialog dialog = new TimePickerDialog(this,OnTimeSet,DateTime.Now.Hour,DateTime.Now.Minute,true);
dialog.Show();
void OnTimeSet (object sender, TimePickerDialog.TimeSetEventArgs e)
{
}
Related
Currently, my main activity displays an arbitrary time, and holds a button that when pressed, brings up a Time Picker Dialog Fragment. After the user sets a new time in the Fragment, closing the fragment, I want my main activity to update it's TextView with the new time the user chose.
My issue right now is that I can't figure out how to update the time displayed in the activity after the user sets the time. I have tried playing with onResume, but it keeps causing the app to crash. What is the best way to refresh an activity after exiting a fragment?
The flow I am trying to achieve is that the user sets the time in the fragment, causing the shared preferences to be updated, and then the main acitivty refreshes, updating the text view with the chosen time. Am I thinking of this incorrectly?
Here is my TimePickerFragment class:
package com.example.habitabilitystudy;
import java.util.Calendar;
import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.widget.TimePicker;
public class TimePickerFragment extends DialogFragment implements
TimePickerDialog.OnTimeSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
"prediction", Context.MODE_PRIVATE);
final Calendar c = Calendar.getInstance();
int defaultHour = c.get(Calendar.HOUR_OF_DAY);
int defaultMinute = c.get(Calendar.MINUTE);
int hour = sharedPref.getInt("prediction_hour", defaultHour);
int minute = sharedPref.getInt("prediction_min", defaultMinute);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
"prediction", Context.MODE_PRIVATE);
SharedPreferences.Editor editorh = sharedPref.edit();
editorh.putInt("prediction_hour", hourOfDay);
editorh.commit();
SharedPreferences.Editor editorm = sharedPref.edit();
editorm.putInt("prediction_min", minute);
editorm.commit();
mCallbacks.TimeUpdated();
}
/**
* Interface
*/
private FragmentCallbacks mCallbacks;
public interface FragmentCallbacks {
void TimeUpdated();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (FragmentCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException(
"Activity must implement Fragment Two.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
}
My Main Activity:
package com.example.habitabilitystudy;
import java.util.Calendar;
import android.app.Activity;
import android.app.DialogFragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements
TimePickerFragment.FragmentCallbacks {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Use the current time as the default values for the picker
SharedPreferences sharedPref = this.getSharedPreferences("prediction",
Context.MODE_PRIVATE);
final Calendar c = Calendar.getInstance();
int defaultHour = c.get(Calendar.HOUR_OF_DAY);
int defaultMinute = c.get(Calendar.MINUTE);
int hour = sharedPref.getInt("prediction_hour", defaultHour);
int minute = sharedPref.getInt("prediction_min", defaultMinute);
String timeString = Integer.toString(hour) + ":"
+ Integer.toString(minute);
TextView predictionText = (TextView) findViewById(R.id.prediction_time);
predictionText.setText(timeString);
}
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "timePicker");
}
#Override
public void TimeUpdated() {
Toast.makeText(this, "Updated", Toast.LENGTH_SHORT).show();
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.predictButton:
startActivity(new Intent(this, MainActivity.class));
break;
case R.id.login:
startActivity(new Intent(this, LoginActivity.class));
break;
}
}
}
My Main Activity xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/prediction_time"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingRight="3dip"
android:background="#5c755e"
android:gravity="end"
android:textColor="#3d4935"
android:textSize="25sp"
android:textStyle="italic"
android:text="(c) appsrox.com" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/adjust_time"
android:onClick="showTimePickerDialog" />
</RelativeLayout>
You want to create an Interface in the Dialog Fragment. When the time is picked it will notify the Activity. Let me know if this gives you any issues.
Fragment
public class TimePickerFragment extends DialogFragment implements
TimePickerDialog.OnTimeSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
"prediction", Context.MODE_PRIVATE);
final Calendar c = Calendar.getInstance();
int defaultHour = c.get(Calendar.HOUR_OF_DAY);
int defaultMinute = c.get(Calendar.MINUTE);
int hour = sharedPref.getInt("prediction_hour", defaultHour);
int minute = sharedPref.getInt("prediction_min", defaultMinute);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
"prediction", Context.MODE_PRIVATE);
SharedPreferences.Editor editorh = sharedPref.edit();
editorh.putInt("prediction_hour", hourOfDay);
editorh.commit();
SharedPreferences.Editor editorm = sharedPref.edit();
editorm.putInt("prediction_min", minute);
editorm.commit();
mCallbacks.TimeUpdated(hourOfDay, minute);
}
/**
* Interface
*/
private FragmentCallbacks mCallbacks;
public interface FragmentCallbacks {
void TimeUpdated(int hour, int minute);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (FragmentCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement Fragment Two.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
}
MainActivity
public class MainActivity extends Activity implements TimePickerFragment.FragmentCallbacks {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Use the current time as the default values for the picker
SharedPreferences sharedPref = this.getSharedPreferences("prediction",
Context.MODE_PRIVATE);
final Calendar c = Calendar.getInstance();
int defaultHour = c.get(Calendar.HOUR_OF_DAY);
int defaultMinute = c.get(Calendar.MINUTE);
int hour = sharedPref.getInt("prediction_hour", defaultHour);
int minute = sharedPref.getInt("prediction_min", defaultMinute);
String timeString = Integer.toString(hour) + ":"
+ Integer.toString(minute);
TextView predictionText = (TextView) findViewById(R.id.prediction_time);
predictionText.setText(timeString);
}
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "timePicker");
}
#Override
public void TimeUpdated(int hour, int minute) {
Toast.makeText(this, "Hour: " + hour + " Minute: " + minute, Toast.LENGTH_SHORT).show();
String timeString = Integer.toString(hour) + ":" + Integer.toString(minute);
TextView predictionText = (TextView) findViewById(R.id.prediction_time);
predictionText.setText(timeString);
}
}
As a part of The Big Nerd Ranch's Android Guide example Criminal Intent,
I am updating a button with date/time entered in the
Date/TimePicker. Button and Date/TimePicker reside in different
fragments. I am transferring data between them using an Intent. It
works fine on Pre-Lollipop devices but doesn't seem to update button
text on Android 5.0 or Lollipop devices. What am I missing?
Full code can be seen at Github.
CrimeFragment.java
package com.sudhirkhanger.android.criminalintent;
import java.util.Date;
import java.util.UUID;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
public class CrimeFragment extends Fragment {
private Crime mCrime;
private EditText mTitleField;
private Button mDateButton;
private Button mTimeButton;
private CheckBox mSolvedCheckBox;
private static final String TAG = "CriminalFragment";
public static final String EXTRA_CRIME_ID = "com.sudhirkhanger.android.criminalintent.crime_id";
private static final String DIALOG_DATE = "date";
private static final String DIALOG_TIME = "time";
private static final int REQUEST_DATE = 0;
private static final int REQUEST_TIME = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UUID crimeId = (UUID) getArguments().getSerializable(EXTRA_CRIME_ID);
mCrime = CrimeLab.get(getActivity()).getCrime(crimeId);
}
private void updateDateAndTime() {
Date d = mCrime.getDate();
CharSequence c = DateFormat.format("EEEE, MMM dd, yyyy", d);
CharSequence t = DateFormat.format("h:mm a", d);
mDateButton.setText(c);
mTimeButton.setText(t);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_crime, parent, false);
mTitleField = (EditText) v.findViewById(R.id.crime_title);
mTitleField.setText(mCrime.getTitle());
mTitleField.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence c, int start, int before,
int count) {
mCrime.setTitle(c.toString());
}
public void beforeTextChanged(CharSequence c, int start, int count,
int after) {
// This space intentionally left blank
}
public void afterTextChanged(Editable c) {
// This one too
}
});
mDateButton = (Button) v.findViewById(R.id.crime_date);
mDateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentManager fm = getActivity().getSupportFragmentManager();
DatePickerFragment dialog = DatePickerFragment
.newInstance(mCrime.getDate());
dialog.setTargetFragment(CrimeFragment.this, REQUEST_DATE);
dialog.show(fm, DIALOG_DATE);
}
});
mTimeButton = (Button) v.findViewById(R.id.crime_time);
mTimeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentManager fm = getActivity().getSupportFragmentManager();
TimePickerFragment dialog = TimePickerFragment
.newInstance(mCrime.getDate());
dialog.setTargetFragment(CrimeFragment.this, REQUEST_TIME);
dialog.show(fm, DIALOG_TIME);
}
});
updateDateAndTime();
mSolvedCheckBox = (CheckBox) v.findViewById(R.id.crime_solved);
mSolvedCheckBox.setChecked(mCrime.isSolved());
mSolvedCheckBox
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// Set the crime's solved property
mCrime.setSolved(isChecked);
}
});
return v;
}
public static CrimeFragment newInstance(UUID crimeId) {
Bundle args = new Bundle();
args.putSerializable(EXTRA_CRIME_ID, crimeId);
CrimeFragment fragment = new CrimeFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK)
return;
if (requestCode == REQUEST_DATE) {
Date date = (Date) data
.getSerializableExtra(DatePickerFragment.EXTRA_DATE);
mCrime.setDate(date);
updateDateAndTime();
} else if (requestCode == REQUEST_TIME) {
Date date = (Date) data
.getSerializableExtra(TimePickerFragment.EXTRA_TIME);
mCrime.setDate(date);
updateDateAndTime();
}
}
}
DatePickerFragment.java
package com.sudhirkhanger.android.criminalintent;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.View;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
public class DatePickerFragment extends DialogFragment {
public static final String EXTRA_DATE = "com.sudhirkhanger.android.criminalintent.date";
private Date mDate;
public static DatePickerFragment newInstance(Date date) {
Bundle args = new Bundle();
args.putSerializable(EXTRA_DATE, date);
DatePickerFragment fragment = new DatePickerFragment();
fragment.setArguments(args);
return fragment;
}
private void sendResult(int resultCode) {
if (getTargetFragment() == null)
return;
Intent i = new Intent();
i.putExtra(EXTRA_DATE, mDate);
getTargetFragment().onActivityResult(getTargetRequestCode(),
resultCode, i);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
mDate = (Date) getArguments().getSerializable(EXTRA_DATE);
// Create a Calendar to get the year, month, and day
final Calendar calendar = Calendar.getInstance();
// calendar.setTime(mDate);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
View v = getActivity().getLayoutInflater().inflate(
R.layout.dialog_date, null);
DatePicker datePicker = (DatePicker) v
.findViewById(R.id.dialog_date_datePicker);
datePicker.init(year, month, day, new OnDateChangedListener() {
public void onDateChanged(DatePicker view, int year, int month,
int day) {
// Translate year, month, day into a Date object using a
// calendar
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
mDate = new GregorianCalendar(year, month, day, hour, minute)
.getTime();
// Update argument to preserve selected value on rotation
getArguments().putSerializable(EXTRA_DATE, mDate);
}
});
return new AlertDialog.Builder(getActivity())
.setView(v)
.setTitle(R.string.date_picker_title)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
sendResult(Activity.RESULT_OK);
}
}).create();
}
}
The problem isn't with the communication between the Fragments, it's that for some reason the default CalendarView DatePicker in Lollipop never calls the OnDateChanged() method, so mDate in DatePickerFragment.java never gets changed; DatePickerFragment sends back to CrimeFragment the same value it received from CrimeFragment, so it only looks like the communication between the two Fragments isn't working.
The Lollipop DatePicker does call OnDateChanged() when it's in SpinnerView mode, so CrimeFragment's date will then get properly updated. Unfortunately, Lollipop ignores the android:calendarViewShown="false" directive in the DatePicker's tag in the dialog_date.xml file. The only way to force the DatePicker to display as spinners is to include a android:datePickerMode="spinner" directive in the DatePicker's xml tag. You will get a warning that this directive is supported in API 21 only, but it will be ignored by devices running pre-5.0 Android.You have to keep the calendarViewShown="false" directive for pre-5.0 devices.
DatePickerDialog appears to have been fixed in Android 5.0, so you could also use that resource in DatePickerFragment to make things work.
I am new to android development and I hope you can help me solve my problem. Any help will be appreciated. I created a dialogfragment for picking dates. I am able to select the desired dates but I am having trouble in displaying the selected dates.
Here is my DialogFragment
public class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
private Calendar mCalendar;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
mCalendar = Calendar.getInstance();
int year = mCalendar.get(Calendar.YEAR);
int monthOfYear = mCalendar.get(Calendar.MONTH);
int dayOfMonth = mCalendar.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, monthOfYear, dayOfMonth);
}
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mCalendar.set(Calendar.YEAR, year);
mCalendar.set(Calendar.MONTH, monthOfYear);
mCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
}
and I call it from my remindersFragment which extends fragment
private void registerButtonListenersAndSetDefaultText() {
mDateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//getActivity().showDialog(DATE_PICKER_DIALOG);
android.support.v4.app.DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
updateDateButtonText();
}
});
updateDateButtonText();
}
and my updateButton :
private void updateDateButtonText() {
// Set the date button text based upon the value from the database
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
String dateForButton = dateFormat.format(mCalendar.getTime());
mDateButton.setText(dateForButton);
}
I hope you can help me. I've been trying to figure this out for days but I had no luck. Thanks in advance.
Here is the full code on my DialogFragment. I hope this will help:
package com.csu.eclassrecord;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
public class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener{
//
// Date Format
//
private static final String DATE_FORMAT = "yyyy-MM-dd";
private static final String TIME_FORMAT = "kk:mm";
public static final String DATE_TIME_FORMAT = "yyyy-MM-dd kk:mm:ss";
private EditText mTitleText;
private EditText mBodyText;
private Button mDateButton;
private Button mTimeButton;
private Button mConfirmButton;
private Long mRowId;
private RemindersDbAdapter mDbHelper;
private Calendar mCalendar;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
mCalendar = Calendar.getInstance();
int year = mCalendar.get(Calendar.YEAR);
int monthOfYear = mCalendar.get(Calendar.MONTH);
int dayOfMonth = mCalendar.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, monthOfYear, dayOfMonth);
}
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mCalendar.set(Calendar.YEAR, year);
mCalendar.set(Calendar.MONTH, monthOfYear);
mCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateDateButtonText();
}
private void updateDateButtonText() {
// Set the date button text based upon the value from the database
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
String dateForButton = dateFormat.format(mCalendar.getTime());
mDateButton.setText(dateForButton);
}
}
and on my remindersFragment:
package com.csu.eclassrecord;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import com.csu.eclassrecord.R;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;
public class RemindersFragment extends Fragment {
//
// Dialog Constants
//
private static final int DATE_PICKER_DIALOG = 0;
private static final int TIME_PICKER_DIALOG = 1;
//
// Date Format
//
private static final String DATE_FORMAT = "yyyy-MM-dd";
private static final String TIME_FORMAT = "kk:mm";
public static final String DATE_TIME_FORMAT = "yyyy-MM-dd kk:mm:ss";
private EditText mTitleText;
private EditText mBodyText;
private Button mDateButton;
private Button mTimeButton;
private Button mConfirmButton;
private Long mRowId;
private RemindersDbAdapter mDbHelper;
private Calendar mCalendar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDbHelper = new RemindersDbAdapter(getActivity());
View rootView = inflater.inflate(R.layout.fragment_reminders, container, false);
mCalendar = Calendar.getInstance();
mTitleText = (EditText) rootView.findViewById(R.id.title);
mBodyText = (EditText) rootView.findViewById(R.id.body);
mDateButton = (Button) rootView.findViewById(R.id.reminder_date);
mTimeButton = (Button) rootView.findViewById(R.id.reminder_time);
mConfirmButton = (Button) rootView.findViewById(R.id.confirm);
mRowId = savedInstanceState != null ? savedInstanceState.getLong(RemindersDbAdapter.KEY_ROWID)
: null;
registerButtonListenersAndSetDefaultText();
return rootView;
}
private void setRowIdFromIntent() {
if (mRowId == null) {
Bundle extras = getActivity().getIntent().getExtras();
mRowId = extras != null ? extras.getLong(RemindersDbAdapter.KEY_ROWID)
: null;
}
}
#Override
public void onPause() {
super.onPause();
mDbHelper.close();
}
#Override
public void onResume() {
super.onResume();
mDbHelper.open();
setRowIdFromIntent();
populateFields();
}
/**
protected Dialog onCreateDialog(int id) {
switch(id) {
case DATE_PICKER_DIALOG:
return showDatePicker();
case TIME_PICKER_DIALOG:
return showTimePicker();
}
return super.onCreate(id);
private DatePickerDialog showDatePicker() {
DatePickerDialog datePicker = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mCalendar.set(Calendar.YEAR, year);
mCalendar.set(Calendar.MONTH, monthOfYear);
mCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateDateButtonText();
}
}, mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH));
return datePicker;
}
**/
private TimePickerDialog showTimePicker() {
TimePickerDialog timePicker = new TimePickerDialog(getActivity(), new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
mCalendar.set(Calendar.MINUTE, minute);
updateTimeButtonText();
}
}, mCalendar.get(Calendar.HOUR_OF_DAY), mCalendar.get(Calendar.MINUTE), true);
return timePicker;
}
private void registerButtonListenersAndSetDefaultText() {
mDateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//getActivity().showDialog(DATE_PICKER_DIALOG);
android.support.v4.app.DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
}
});
mTimeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().showDialog(TIME_PICKER_DIALOG);
}
});
mConfirmButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent;
saveState();
getActivity().setResult(Activity.RESULT_OK);
Toast.makeText(getActivity(), getString(R.string.task_saved_message), Toast.LENGTH_SHORT).show();
intent = new Intent(getActivity().getApplication(), Manage_Settings.class);
startActivity(intent);
}
});
updateDateButtonText();
updateTimeButtonText();
}
private void populateFields() {
// Only populate the text boxes and change the calendar date
// if the row is not null from the database.
if (mRowId != null) {
Cursor reminder = mDbHelper.fetchReminder(mRowId);
getActivity().startManagingCursor(reminder);
mTitleText.setText(reminder.getString(
reminder.getColumnIndexOrThrow(RemindersDbAdapter.KEY_TITLE)));
mBodyText.setText(reminder.getString(
reminder.getColumnIndexOrThrow(RemindersDbAdapter.KEY_BODY)));
// Get the date from the database and format it for our use.
SimpleDateFormat dateTimeFormat = new SimpleDateFormat(DATE_TIME_FORMAT);
Date date = null;
try {
String dateString = reminder.getString(reminder.getColumnIndexOrThrow(RemindersDbAdapter.KEY_DATE_TIME));
date = dateTimeFormat.parse(dateString);
mCalendar.setTime(date);
} catch (ParseException e) {
Log.e("ReminderEditActivity", e.getMessage(), e);
}
} else {
// This is a new task - add defaults from preferences if set.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String defaultTitleKey = getString(R.string.pref_task_title_key);
String defaultTimeKey = getString(R.string.pref_default_time_from_now_key);
String defaultTitle = prefs.getString(defaultTitleKey, null);
String defaultTime = prefs.getString(defaultTimeKey, null);
if(defaultTitle != null)
mTitleText.setText(defaultTitle);
if(defaultTime != null)
mCalendar.add(Calendar.MINUTE, Integer.parseInt(defaultTime));
}
updateDateButtonText();
updateTimeButtonText();
}
private void updateTimeButtonText() {
// Set the time button text based upon the value from the database
SimpleDateFormat timeFormat = new SimpleDateFormat(TIME_FORMAT);
String timeForButton = timeFormat.format(mCalendar.getTime());
mTimeButton.setText(timeForButton);
}
private void updateDateButtonText() {
// Set the date button text based upon the value from the database
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
String dateForButton = dateFormat.format(mCalendar.getTime());
mDateButton.setText(dateForButton);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putLong(RemindersDbAdapter.KEY_ROWID, mRowId);
}
private void saveState() {
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
SimpleDateFormat dateTimeFormat = new SimpleDateFormat(DATE_TIME_FORMAT);
String reminderDateTime = dateTimeFormat.format(mCalendar.getTime());
if (mRowId == null) {
long id = mDbHelper.createReminder(title, body, reminderDateTime);
if (id > 0) {
mRowId = id;
}
} else {
mDbHelper.updateReminder(mRowId, title, body, reminderDateTime);
}
new ReminderManager(getActivity()).setReminder(mRowId, mCalendar);
}
}
I have 2 TextViews from which I can call a time picker. But Im not able to figure out from which TextBox I callt the time Picker.
Following is the code snippset from the Activity:
case R.id.tv_to_night:
// show the time picker dialog
TimePickerFragment newFragmentNight = new TimePickerFragment();
newFragmentNight.show(getSupportFragmentManager(), "timePicker to");
break;
case R.id.tv_from_night:
// show the time picker dialog
TimePickerFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker from");
break;
Here I want to know from which TextBox I get the Time:
public void onTimePicked(Calendar time) {
if(depending from were it was called)
tv_from_night.setText(DateFormat.format("h:mm a", time));
else
tv_to_night.setText(DateFormat.format("h:mm a", time));
}
TimePickerFragment
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.widget.TimePicker;
import java.util.Calendar;
public class TimePickerFragment extends DialogFragment implements
TimePickerDialog.OnTimeSetListener {
private TimePickedListener mListener;
public Dialog onCreateDialog(Bundle savedInstanceState) {
// use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
#Override
public void onAttach(Activity activity) {
// when the fragment is initially shown (i.e. attached to the activity),
// cast the activity to the callback interface type
super.onAttach(activity);
try {
mListener = (TimePickedListener) activity;
} catch(ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement " + TimePickedListener.class.getName());
}
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// when the time is selected, send it to the activity via its callback
// interface method
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
mListener.onTimePicked(c);
}
public static interface TimePickedListener {
public void onTimePicked(Calendar time);
}
}
Solution
Activity:
case R.id.tv_to_night:
TimePickerFragment newFragmentNight = TimePickerFragment.newInstance(TO_TIME_PICKER_ID);
newFragmentNight.show(getSupportFragmentManager(), "timePicker");
break;
case R.id.tv_from_night:
TimePickerFragment newFragment = TimePickerFragment.newInstance(FROM_TIME_PICKER_ID);
newFragment.show(getSupportFragmentManager(), "timePicker");
break;
Here you get the time with the id:
public void onTimePicked(Calendar time, int id) {
Log.i("TimePicker", "Time picker called from id " + id);
switch(id) {
case FROM_TIME_PICKER_ID:
// do thomething
break;
case TO_TIME_PICKER_ID:
// do thomething
break;
}
}
TimePickerFragment:
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.widget.TimePicker;
import java.util.Calendar;
public class TimePickerFragment extends DialogFragment implements
TimePickerDialog.OnTimeSetListener {
private int mId;
private TimePickedListener mListener;
static TimePickerFragment newInstance(int id) {
Bundle args = new Bundle();
args.putInt("picker_id", id);
TimePickerFragment fragment = new TimePickerFragment();
fragment.setArguments(args);
return fragment;
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
// use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
mId = getArguments().getInt("picker_id");
// create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
#Override
public void onAttach(Activity activity) {
// when the fragment is initially shown (i.e. attached to the activity),
// cast the activity to the callback interface type
super.onAttach(activity);
try {
mListener = (TimePickedListener) activity;
} catch(ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement " + TimePickedListener.class.getName());
}
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// when the time is selected, send it to the activity via its callback
// interface method
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
if(mListener != null)
mListener.onTimePicked(c, mId);
}
public static interface TimePickerDialogListener {
public void onTimeSet(int id, TimePicker view, int hourOfDay, int minute);
}
public static interface TimePickedListener {
public void onTimePicked(Calendar time, int id);
}
}
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.