I have 4 timePicker in my app. The timePicker dialog will pop out when the user double click on the editText. But sometimes when I accidentally click more than two times, the app crashed and said that the fragment already added. How can I fix this? Insted of clicking the editText twice, I want the timePicker dialog shown by just one click on the editText.
public void onClick(View v) {
int id = v.getId();
if (id == R.id.editTextTI1) {
tp.setFlag(TimePick.FLAG_START_DATE);
FragmentTransaction ft = getFragmentManager().beginTransaction();
tp.show(ft, "TimePicker");
}
if (id == R.id.editTextTO1) {
tp.setFlag(TimePick.FLAG_END_DATE);
FragmentTransaction ft = getFragmentManager().beginTransaction();
tp.show(ft, "TimePicker");
}
if (id == R.id.editTextTI2) {
tp.setFlag(TimePick.FLAG_START_DATE1);
FragmentTransaction ft = getFragmentManager().beginTransaction();
tp.show(ft, "TimePicker");
}
if (id == R.id.editTextTO2) {
tp.setFlag(TimePick.FLAG_END_DATE1);
FragmentTransaction ft = getFragmentManager().beginTransaction();
tp.show(ft, "TimePicker");
}
if (id == R.id.editTextTI3) {
tp.setFlag(TimePick.FLAG_START_DATE2);
FragmentTransaction ft = getFragmentManager().beginTransaction();
tp.show(ft, "TimePicker");
}
if (id == R.id.editTextTO3) {
tp.setFlag(TimePick.FLAG_END_DATE2);
FragmentTransaction ft = getFragmentManager().beginTransaction();
tp.show(ft, "TimePicker");
}
if (id == R.id.editTextTI4) {
tp.setFlag(TimePick.FLAG_START_DATE3);
FragmentTransaction ft = getFragmentManager().beginTransaction();
tp.show(ft, "TimePicker");
}
if (id == R.id.editTextTO4) {
tp.setFlag(TimePick.FLAG_END_DATE3);
FragmentTransaction ft = getFragmentManager().beginTransaction();
tp.show(ft, "TimePicker");
}
}
public static class TimePick extends android.app.DialogFragment implements TimePickerDialog.OnTimeSetListener {
public static final int FLAG_START_DATE = 00;
public static final int FLAG_END_DATE = 01;
public static final int FLAG_START_DATE1 = 10;
public static final int FLAG_END_DATE1 = 11;
public static final int FLAG_START_DATE2 = 20;
public static final int FLAG_END_DATE2 = 21;
public static final int FLAG_START_DATE3 = 30;
public static final int FLAG_END_DATE3 = 31;
private int flag = 00;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
return new TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
}
public void setFlag(int i) {
flag = i;
}
#Override
public void onTimeSet(TimePicker view, int hourofDay, int minute) {
if (flag == FLAG_START_DATE) {
start.setText(Integer.toString(hourofDay) + ":" + Integer.toString(minute));
b = start.getText().toString();
}
if (flag == FLAG_END_DATE) {
end.setText(Integer.toString(hourofDay) + ":" + Integer.toString(minute));
c = end.getText().toString();
}
if (flag == FLAG_START_DATE1) {
start1.setText(Integer.toString(hourofDay) + ":" + Integer.toString(minute));
d = start1.getText().toString();
}
if (flag == FLAG_END_DATE1) {
end1.setText(Integer.toString(hourofDay) + ":" + Integer.toString(minute));
e1 = end1.getText().toString();
}
if (flag == FLAG_START_DATE2) {
start2.setText(Integer.toString(hourofDay) + ":" + Integer.toString(minute));
f = start2.getText().toString();
}
if (flag == FLAG_END_DATE2) {
end2.setText(Integer.toString(hourofDay) + ":" + Integer.toString(minute));
g = end2.getText().toString();
}
if (flag == FLAG_START_DATE3) {
start3.setText(Integer.toString(hourofDay) + ":" + Integer.toString(minute));
h = start3.getText().toString();
}
if (flag == FLAG_END_DATE3) {
end3.setText(Integer.toString(hourofDay) + ":" + Integer.toString(minute));
i = end3.getText().toString();
}
LogCat Error
10-15 12:53:17.113 7943-7943/com.example.project.project E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.project.project, PID: 7943
java.lang.IllegalStateException: Fragment already added: TimePick{7c7eb96 #0 TimePicker}
at android.app.FragmentManagerImpl.addFragment(FragmentManager.java:1219)
at android.app.BackStackRecord.run(BackStackRecord.java:715)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1535)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:482)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
Your code is so hardcoded and not easy to extend, which could lead to many bugs in future.
You should encapsulate general logic as max as you can, so in current case:
public void onClick(View v) {
EditText editText = (EditText) v;
if (tp==null || !tp.isAdded()){
FragmentTransaction ft = getFragmentManager().beginTransaction();
tp = new TimePick(editText);
tp.show(ft, "TimePicker");
}
}
#Override
public void onStop() {
super.onStop();
if (tp.isAdded()) tp.dismiss();
}
public static class TimePick extends android.app.DialogFragment implements TimePickerDialog.OnTimeSetListener {
private EditText editText;
public TimePick(EditText editText) {
this.editText = editText;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
return new TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
}
#Override
public void onTimeSet(TimePicker view, int hourofDay, int minute) {
editText.setText(Integer.toString(hourofDay) + ":" + Integer.toString(minute));
}
}
this code won't try to create new time picker if any is on screen. You could pass target edittext to timePicker fragment. When you need values from these edittexts(your a,b,c,d... variables) you could read it when needed, not in onTimeSetMethod.
onStop method was provided to handle activity recreation cases. Here i just hide active timepicker.
You are adding the same DialogFragment instance twice, to fix this, check whether TimePicker is added with getFragmentManager.findFragmentByTag("TimePicker").
Related
I want to call a custom Dialog in fragment, where user will add some data and I want to get it in that fragment.
For this I created a dialog class and a special layout for it (I think it's not neccessary to post it here):
public class IntervalsDialog extends DialogFragment {
private TextView interval1, interval2, interval3, interval4;
private EditText weight1, weight2, weight3, weight4;
private IntervalDialogListener listener;
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
try {
listener = (IntervalDialogListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + "you must implement IntervalsDialogListener");
}
}
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_layout, null);
builder.setView(view).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).setPositiveButton("Go further", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (weight1.getText().toString().trim().matches("") || weight2.getText().toString().trim().matches("") ||
weight3.getText().toString().trim().matches("") || weight4.getText().toString().trim().matches("")){
Toast.makeText(getContext(), "You must fill in all the blanks to continue", Toast.LENGTH_SHORT).show();
}
else{
int w1 = Integer.valueOf(weight1.getText().toString().trim());
int w2 = Integer.valueOf(weight2.getText().toString().trim());
int w3 = Integer.valueOf(weight3.getText().toString().trim());
int w4 = Integer.valueOf(weight4.getText().toString().trim());
listener.onPositiveButtonClicked(w1, w2, w3, w4);
}
}
});
interval1 = view.findViewById(R.id.interval1);
interval2 = view.findViewById(R.id.interval2);
interval3 = view.findViewById(R.id.interval3);
interval4 = view.findViewById(R.id.interval4);
weight1 = view.findViewById(R.id.weight1);
weight2 = view.findViewById(R.id.weight2);
weight3 = view.findViewById(R.id.weight3);
weight4 = view.findViewById(R.id.weight4);
setIntervals();
return builder.create();
}
public interface IntervalDialogListener{
void onPositiveButtonClicked(int weigh1, int weight2, int weight3, int weight4);
}
private void setIntervals(){
int dayStart = 360;
int dayEnd = 1320;
ArrayList<Interval> idealInt = new ArrayList<>();
int dayInterval = (dayEnd - dayStart)/4;
for (int i = dayStart; i < dayEnd; i+= dayInterval) {
idealInt.add(new Interval(i, i + dayInterval));
}
interval1.setText(idealInt.get(0).toString());
interval2.setText(idealInt.get(1).toString());
interval3.setText(idealInt.get(2).toString());
interval4.setText(idealInt.get(3).toString());
}
}
class Interval{
private int start, end;
Interval(int start, int end){
this.start = start;
this.end = end;
}
public String toString() {
return (toTime(start) + " - " + toTime(end));
}
private static String toTime (int a) {
String s = "";
int b = a/60;
int c = a%60;
if (c < 10) {
s = b + " : " + 0 + c;
}
else {
s = b + " : " + c;
}
return s;
}
}
I faced a problem that my MainActivity could not be casted to a listener. I followed this answer and sended data first to my MainActivity:
#Override
public void onPositiveButtonClicked(int weigh1, int weight2, int weight3, int weight4) {
AddDataFragment fragment = new AddDataFragment();
fragment.getDataFromMainActivity(weigh1, weight2, weight3, weight4);
}
Then wrote a method for getting this data in my fragment (I hope, I did everything right up to this moment):
public void getDataFromMainActivity(int weigh1, int weight2, int weight3, int weight4){
Toast.makeText(getContext(), weigh1 + " -- " + weight2 + " -- " + weight3 + " -- " + weight4, Toast.LENGTH_LONG).show();
AddDataFragmentDirections.ActionSort action = AddDataFragmentDirections.actionSort();
action.setCurrentDate(currentDateGot);
action.setWeight1(weigh1);
action.setWeight2(weight2);
action.setWeight3(weight3);
action.setWeight4(weight4);
Navigation.findNavController(getView()).navigate(action);
}
Then I simply want to check if the data is saved correctly via Toast message. And then I get this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.widget.Toast.<init>(Toast.java:114)
at android.widget.Toast.makeText(Toast.java:277)
at android.widget.Toast.makeText(Toast.java:267)
at com.example.chronosaur.ui.AddDataFragment.getDataFromMainActivity(AddDataFragment.java:232)
at com.example.chronosaur.ui.MainActivity.onPositiveButtonClicked(MainActivity.java:44)
at com.example.chronosaur.ui.IntervalsDialog$1.onClick(IntervalsDialog.java:64)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
...
Why does this error occur? What did I miss? Please, help me. Thanks for any help.
Your DialogFragment was never attached to your activity. After instantiating your AddDataFragment use following way to attach it with your activity.
FragmentManager fm = getSupportFragmentManager();
fragment.show(fm, "tag");
Ignore the following part if your minSdk is not below 23.
getContext() is an API 23+ method which may produce exceptions on lower API devices.
Create a Context variable in your class to store the context.
...
private Context context; //add this
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
this.context = context; //add this
...
}
And replace getContext() with context e.g. Toast by using:
Toast.makeText(context, weigh1 + " -- " + weight2 + " -- " + weight3 + " -- " + weight4, Toast.LENGTH_LONG).show();
I have a variable of its kind int.
I've allocated value in it through another value from within another object ,but there's a problem.
The problem is happening when i press the button 3
after i set the required time values for each object.
I'll show you the wrong message ,and the code used.
I want to change the code to work properly.
// Logcat:
java.lang.NullPointerException: Attempt to read from field 'int com.ahmedco.testcode2.TimePickerDialog.hourOfDay' on a null object reference
at com.ahmedco.testcode2.MainActivity$3.onClick(MainActivity.java:65)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24701)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
// class 1
public class MainActivity extends AppCompatActivity {
Button b1, b2, b3;
DialogFragment timePickerDialog1, timePickerDialog2;
int hourTimer1, hourTimer2, minuteTimer1, minuteTimer2;
String time1Format, time2Format, AM_PMTimer1, AM_PMTimer2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button);
b2 = (Button) findViewById(R.id.button2);
b3 = (Button) findViewById(R.id.button3);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
timePickerDialog1 = new TimePickerDialog(1);
timePickerDialog1.show(getSupportFragmentManager(), "timePicker");
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
timePickerDialog2 = new TimePickerDialog(2);
timePickerDialog2.show(getSupportFragmentManager(), "timePicker");
}
});
b3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
hourTimer1 = ((TimePickerDialog) timePickerDialog1).hourOfDay;
hourTimer2 = ((TimePickerDialog) timePickerDialog2).hourOfDay;
minuteTimer1 = ((TimePickerDialog) timePickerDialog1).minute;
minuteTimer2 = ((TimePickerDialog) timePickerDialog2).minute;
AM_PMTimer1 = ((TimePickerDialog) timePickerDialog1).AM_PM;
AM_PMTimer2 = ((TimePickerDialog) timePickerDialog2).AM_PM;
//Log.i("trace1","test "+((TimePickerDialog) timePickerDialog1).hourOfDay);
//Log.i("trace2","test "+((TimePickerDialog) timePickerDialog2).hourOfDay);
time1Format = "" + hourTimer1 + ":" + minuteTimer1 + " " + AM_PMTimer1;
time2Format = "" + hourTimer1 + ":" + minuteTimer1 + " " + AM_PMTimer2;
Log.i("time1Format", "" + time1Format);
Log.i("time2Format", "" + time2Format);
}
});
}
}
// class 2
public class TimePickerDialog extends DialogFragment implements android.app.TimePickerDialog.OnTimeSetListener {
public String AM_PM = "";
public int hourOfDay = 0;
public int minute = 0;
public TimePickerDialog(int id) {
// currentEditText = id;
}
#Override
public Dialog onCreateDialog(#Nullable 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);
return new android.app.TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay_, int minute_) {
// "11:06 PM"
if (hourOfDay_ > 12) {
AM_PM = "PM";
hourOfDay_ = hourOfDay_ - 12;
} else {
AM_PM = "AM";
}
///Log.i("hourOfDay",""+hourOfDay_+":"+hourOfDay_+" "+AM_PM);
hourOfDay = hourOfDay_;
minute = minute_;
}
}
You having problem inside b3.setOnClickListener because you are not initialized object so you have to initialize objects timePickerDialog1 and timePickerDialog2 globally.
DialogFragment timePickerDialog1=new TimePickerDialog(1), timePickerDialog2=new TimePickerDialog(2);
or
b3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(timePickerDialog1==null)
timePickerDialog1=new TimePickerDialog(1);
if(timePickerDialog2==null)
timePickerDialog1=new TimePickerDialog(2);
hourTimer1 = ((TimePickerDialog) timePickerDialog1).hourOfDay;
hourTimer2 = ((TimePickerDialog) timePickerDialog2).hourOfDay;
minuteTimer1 = ((TimePickerDialog) timePickerDialog1).minute;
minuteTimer2 = ((TimePickerDialog) timePickerDialog2).minute;
AM_PMTimer1 = ((TimePickerDialog) timePickerDialog1).AM_PM;
AM_PMTimer2 = ((TimePickerDialog) timePickerDialog2).AM_PM;
//Log.i("trace1","test "+((TimePickerDialog) timePickerDialog1).hourOfDay);
//Log.i("trace2","test "+((TimePickerDialog) timePickerDialog2).hourOfDay);
time1Format = "" + hourTimer1 + ":" + minuteTimer1 + " " + AM_PMTimer1;
time2Format = "" + hourTimer1 + ":" + minuteTimer1 + " " + AM_PMTimer2;
Log.i("time1Format", "" + time1Format);
Log.i("time2Format", "" + time2Format);
}
});
You declare your TimePickerDialog in the beginning (DialogFragment timePickerDialog1, timePickerDialog2;)
But only initialise it when Button 1 or 2 are pressed respectively
timePickerDialog2 = new TimePickerDialog(2);
Therefore timePickerDialog2is nulluntil Button 2 was pressed.
When trying to call .hourOfDay in Button 3 when timePickerDialog2has not been initialised yet, you get a NullPointerException. You can't call methods on an object that is null.
Trying to insert chosen date and time, from datepicker/time picker into SQLite. Am getting error NewMeetingActivity.AddData(NewMeetingActivity.java:156) - boolean insertData = myDB.addData(newDate,newTime);
I currently have my chosen date and time saved to textviews. How do i then add them to my DB? I've tried turning them into strings however i don't think im doing it correctly as the app crashes
public class NewMeetingActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener {
private Button btn_date, btn_time, btn_confirm_meeting, btn_back_to_meetings, btn_location;
private CalendarView calendarView;
private TextView myDate, myTime;
DataBaseHelper myDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_meetings);
myDate = findViewById(R.id.myDate);
myTime = findViewById(R.id.myTime);
btn_date = findViewById(R.id.button_add_Date);
btn_time = findViewById(R.id.button_add_Time);
btn_confirm_meeting = findViewById(R.id.button_confirm_meeting);
btn_back_to_meetings = findViewById(R.id.button_back_to_meetings);
btn_back_to_meetings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(NewMeetingActivity.this,
MeetingActivity.class);
startActivity(intent);
}
});
btn_date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment datePicker = new DateFragment();
datePicker.show(getSupportFragmentManager(), "date picker");
}
});
btn_time.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment timePicker = new TimeFragment();
timePicker.show(getSupportFragmentManager(), "time picker");
}
});
btn_confirm_meeting.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newDate = myDate.getText().toString();
String newTime = myTime.getText().toString();
if (myDate.length() == 0) {
Toast.makeText(NewMeetingActivity.this, "Enter a date for your meeting", Toast.LENGTH_LONG).show();
}
if (myTime.length() == 0) {
Toast.makeText(NewMeetingActivity.this, "Enter a time for your meeting", Toast.LENGTH_LONG).show();
} else if (myDate.length() != 0 && myTime.length() != 0) {
AddData(newDate, newTime);
myDate.setText("");
myTime.setText("");
}
}
});
}
public void AddData(String newDate, String newTime) {
boolean insertData = myDB.addData(newDate, newTime);
if (insertData == true) {
Toast.makeText(NewMeetingActivity.this, "New Meeting Created!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(NewMeetingActivity.this, "Something went wrong, Try again", Toast.LENGTH_LONG).show();
}
}
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 textView = findViewById(R.id.myDate);
textView.setText(currentDateString);
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
TextView textView1 = findViewById(R.id.myTime);
textView1.setText("Hour: " + hourOfDay + "Minute: " + minute);
}
}
This is addData is in my database class
public boolean addData(String item1, String item2) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item1);
contentValues.put(COL3, item2);
long result = db.insert(TABLE_NAME, null, contentValues);
//if date as inserted incorrectly it will return -1
if (result == -1) {
return false;
} else {
return true;
}
}
database creation
public static final String DATABASE_NAME = "mylist.db";
public static final String TABLE_NAME = "mylist_data";
public static final String COL1 = "ID";
public static final String COL2 = "ITEM1";
public static final String COL3 = "ITEM2";
public DataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY
KEY
AUTOINCREMENT, " +
" ITEM1 TEXT, " + "ITEM2 TEXT)";
db.execSQL(create)}
Read the error:
Attempt to invoke virtual method 'boolean C/.myapplication.DataBaseHelper.addData(java.lang.String, java.lang.String)' on a null object reference
It's saying you're trying to call the method addData on an object that is null. In this case, it's the following line:
boolean insertData = myDB.addData(newDate, newTime);
myDb is never instantiated in your code, so attempting to call a method on it will surely not work.
I have an input form in an activity where I'd like to retrieve the start time and end time of an event. I am using a timepicker displayed in a dialog fragment to get the start time and return it to the main activity, but how do re use the same logic to retrieve the end time of the event? My code:
Main Activity:
public class AddEventActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener{
private int pickerHour = 0;
private int pickerMin = 0;
//code ommitted for length
public void showTimePickerDialog(View v) {
TimePickerFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "timePicker");
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
String amOrPm = "am";
pickerHour = hourOfDay;
pickerMin = minute;
String minutesString = "";
if (hourOfDay > 12){ //translate to 12 hr clock. Little workaround to get both timepicker and am/pm label to show up correctly.
amOrPm = "pm";
pickerHour-=12;
}
if (pickerMin < 10) {
minutesString = "0"; //fix weird bug where only one zero is shown on times ending in :00
}
startTimeView.setText(pickerHour + " : " + minutesString + pickerMin + " " +amOrPm );
}
TimePickerFragment:
public class TimePickerFragment extends DialogFragment {
int hour,minute;
private Activity mActivity;
private TimePickerDialog.OnTimeSetListener mListener;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mActivity = activity;
try {
mListener = (TimePickerDialog.OnTimeSetListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnTimeSetListener");
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
return new TimePickerDialog(mActivity, mListener, hour, minute,
DateFormat.is24HourFormat(mActivity));
}
}
I need to be able to differentiate between the start time and the end time, but I am not sure how to differentiate them without repeating myself. I am pretty new to Java and Android. Thank you so much for any help.
Possibly something as simple as a boolean?
public class AddEventActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener{
...
boolean isSettingStartTime = true;
//code ommitted for length
public void showTimePickerDialog(View v) {
TimePickerFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "timePicker");
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
...
if (isSettingStartTime) {
startTimeView.setText(pickerHour + " : " + minutesString + pickerMin + " " +amOrPm );
isSettingStartTime = false;
} else {
endTimeView.setText(pickerHour + " : " + minutesString + pickerMin + " " +amOrPm );
}
}
}
This would require you being able to retrieve the TimePicker from your TimePickerFragment
You either need to get the TimePicker instance when you create both TimePickerFragments and store them in two fields such as startTimePicker and finishTimePicker.
Then when the TimePicker is passed in through the onTimeSet you then check to see which TimePicker it is like so.
if ( timePicker == startTimePicker ) {
startTimeTextView.setText....
} else {
finishTimeTextView.setText...
}
I have implemented a date picker as following.
private void updateDisplay() {
String str_date = "";
if ((Month + 1) >= 10) {
if (Day < 10) {
str_date = Year + "-" + (Month + 1) + "-0" + Day;
} else {
str_date = Year + "-" + (Month + 1) + "-" + Day;
}
} else {
if (Day < 10) {
str_date = Year + "-0" + (Month + 1) + "-0" + Day;
} else {
str_date = Year + "-0" + (Month + 1) + "-" + Day;
}
}
date.setText("" + str_date);
}
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case DATE_DIALOG_ID:
((DatePickerDialog) dialog).updateDate(Year, Month, Day);
break;
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(viewLoad.getContext(),
mDateSetListener, Year, Month, Day);
}
return null;
}
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
Year = year;
Month = monthOfYear;
Day = dayOfMonth;
updateDisplay();
}
};
Here is my code segment for button.
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnDate:
showDialog(DATE_DIALOG_ID);
break;
This works fine. Now the problem is I need to implement a date picker in a fragment. Can anyone plz explain how to do it.
Edited Code
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
Year = year;
Month = monthOfYear;
Day = dayOfMonth;
updateDisplay();
}
};
Thanx in advance.
Use this CustomDialogFragment that contains use of
TimePicker Dialog fragment
DatePicker Dialog fragment
Simple Dialog Fragment
CustomeDialogFragment Class
public class CustomDialogFragment extends DialogFragment
{
public static final int DATE_PICKER = 1;
public static final int TIME_PICKER = 2;
public static final int DIALOG = 3;
Context mContext;
String mMessage;
boolean finishActivity;
// private Fragment mCurrentFragment;
Activity mActivity;
/**
* this constructor is used for datepicker & Timepicker
*/
public CustomDialogFragment (Fragment fragment ) {
// mCurrentFragment = fragment;
}
public CustomDialogFragment (Activity mActivity ) {
this.mActivity = mActivity;
}
/**
* this constructor is used for simple dialog fragment
*/
public CustomDialogFragment(Context context, String message, final boolean finishActivity) {
mContext = context;
mMessage = message;
this.finishActivity = finishActivity;
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
Bundle bundle = new Bundle();
bundle = getArguments();
int id = bundle.getInt("dialog_id");
switch (id) {
case DATE_PICKER:
return new DatePickerDialog(getActivity(),
(OnDateSetListener)mActivity, bundle.getInt("year"),
bundle.getInt("month"), bundle.getInt("day"));
case TIME_PICKER:
return new TimePickerDialog(getActivity(),
(OnTimeSetListener)mActivity,bundle.getInt("hour"),
bundle.getInt("minute"), true);
case DIALOG:
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext);
alertDialogBuilder.setTitle(R.string.app_name);
alertDialogBuilder.setMessage(mMessage);
alertDialogBuilder.setIcon(R.drawable.ic_launcher);
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setPositiveButton(
getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int arg1) {
dialog.dismiss();
if (finishActivity == true) {
Activity act = (Activity) mContext;
act.finish();
}
}
});
alertDialogBuilder.setNegativeButton(getResources().getString(R.string.cancel_btn_title), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
CustomDialogFragment.this.dismiss();
}
});
return alertDialogBuilder.create();
}
//Define your custom dialog or alert dialog here and return it.
return new Dialog(getActivity());
}
}
& Use date Picker this Way
1) In your Activity Or fragment Implement OnDateSetListener ( after done it will get back result to onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) method)
2) Call DatePicker From Fragment Like this way
CustomDialogFragment dialog = new CustomDialogFragment(YourFragment.this);
Bundle bundle = new Bundle();
bundle.putInt("dialog_id", CustomDialogFragment.DATE_PICKER);
bundle.putInt("year", mYear);
bundle.putInt("month", mMonth);
bundle.putInt("day", mDay);
dialog.setArguments(bundle);
dialog.show(getFragmentManager(), "dialog");
& Call DatePicker From Activity(or FragmentActivity) Like this Way
CustomDialogFragment dialog = new CustomDialogFragment(this);
Bundle bundle = new Bundle();
bundle.putInt("dialog_id", CustomDialogFragment.DATE_PICKER);
bundle.putInt("year", mYear);
bundle.putInt("month", mMonth);
bundle.putInt("day", mDay);
dialog.setArguments(bundle);
dialog.setCancelable(false);
dialog.show(this.getSupportFragmentManager(), "dialog");
& as per Set "dialog_id" u can use TIME_PICKER (for time picker dialog) & DIALOG(for simple dialog)
as per send "dialog_id" according to send data through bundle to CustomDialogFragment.
As my knowledge, cannot use showDialog() in Fragment. It's also deprecated.
Use DialogFragment.
Learn from this tutorial as you need
http://www.kylebeal.com/2011/11/android-datepickerdialog-and-the-dialogfragment/