timePicker with multiple buttons - java

I hope someone can help me. I lack in OOP knowledge and am a newbie in android.
I have 6 buttons. Each button will call the timePicker and display the time on the button.
How do i want to differentiate each buttons?
Thank you.....
Here's the code..:
public class TabTwo extends Activity implements OnClickListener {
private Button btnBrfkst;
private Button btnMtea;
private Button btnLunch;
private Button btnAftea;
private Button btnDinner;
private Button btnSupper;
private Calendar mCalen;
private int hourOfDay;
private int minute;
private int ampm;
int timePickerInput ;
private static final int Time_PICKER_ID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab_two);
btnBrfkst = (Button) findViewById(R.id.button1);
btnMtea = (Button) findViewById(R.id.button2);
btnLunch = (Button) findViewById(R.id.button3);
btnAftea = (Button) findViewById(R.id.button4);
btnDinner = (Button) findViewById(R.id.button5);
btnSupper = (Button) findViewById(R.id.button6);
mCalen = Calendar.getInstance();
hourOfDay = mCalen.get(Calendar.HOUR_OF_DAY);
minute = mCalen.get(Calendar.MINUTE);
ampm = mCalen.get(Calendar.AM_PM);
btnBrfkst.setOnClickListener(this);
btnMtea.setOnClickListener(this);
btnLunch.setOnClickListener(this);
btnAftea.setOnClickListener(this);
btnDinner.setOnClickListener(this);
btnSupper.setOnClickListener(this);
}
#Override
#Deprecated
protected Dialog onCreateDialog(int id) {
switch (id) {
case Time_PICKER_ID:
return new TimePickerDialog(this, TimePickerListener,
hourOfDay, minute, false);
}
return null;
}
private TimePickerDialog.OnTimeSetListener TimePickerListener =
new TimePickerDialog.OnTimeSetListener() {
// while dialog box is closed, below method is called.
public void onTimeSet(TimePicker view, int hour, int minute) {
switch (timePickerInput) {
case R.id.button1:
mCalen.set(Calendar.HOUR_OF_DAY, hour);
mCalen.set(Calendar.MINUTE, minute);
int hour12format = mCalen.get(Calendar.HOUR);
hourOfDay = mCalen.get(Calendar.HOUR_OF_DAY);
minute = mCalen.get(Calendar.MINUTE);
ampm = mCalen.get(Calendar.AM_PM);
String ampmStr = (ampm == 0) ? "AM" : "PM";
// Set the Time String in Button
btnBrfkst.setText(hour12format + " : " + minute + " / " + ampmStr);
break;
case R.id.button2:
mCalen.set(Calendar.HOUR_OF_DAY, hour);
mCalen.set(Calendar.MINUTE, minute);
int hour12format2 = mCalen.get(Calendar.HOUR);
hourOfDay = mCalen.get(Calendar.HOUR_OF_DAY);
minute = mCalen.get(Calendar.MINUTE);
ampm = mCalen.get(Calendar.AM_PM);
String ampmStr2 = (ampm == 0) ? "AM" : "PM";
btnMtea.setText(hour12format2 + " : " + minute + " / " + ampmStr2);
break;
case R.id.button3:
mCalen.set(Calendar.HOUR_OF_DAY, hour);
mCalen.set(Calendar.MINUTE, minute);
int hour12format3 = mCalen.get(Calendar.HOUR);
hourOfDay = mCalen.get(Calendar.HOUR_OF_DAY);
minute = mCalen.get(Calendar.MINUTE);
ampm = mCalen.get(Calendar.AM_PM);
String ampmStr3 = (ampm == 0) ? "AM" : "PM";
btnLunch.setText(hour12format3 + " : " + minute + " / " + ampmStr3);
break;
case R.id.button4:
mCalen.set(Calendar.HOUR_OF_DAY, hour);
mCalen.set(Calendar.MINUTE, minute);
int hour12format4 = mCalen.get(Calendar.HOUR);
hourOfDay = mCalen.get(Calendar.HOUR_OF_DAY);
minute = mCalen.get(Calendar.MINUTE);
ampm = mCalen.get(Calendar.AM_PM);
String ampmStr4 = (ampm == 0) ? "AM" : "PM";
btnAftea.setText(hour12format4 + " : " + minute + " / " + ampmStr4);
break;
case R.id.button5:
mCalen.set(Calendar.HOUR_OF_DAY, hour);
mCalen.set(Calendar.MINUTE, minute);
int hour12format5 = mCalen.get(Calendar.HOUR);
hourOfDay = mCalen.get(Calendar.HOUR_OF_DAY);
minute = mCalen.get(Calendar.MINUTE);
ampm = mCalen.get(Calendar.AM_PM);
String ampmStr5 = (ampm == 0) ? "AM" : "PM";
btnDinner.setText(hour12format5 + " : " + minute + " / " + ampmStr5);
break;
case R.id.button6:
mCalen.set(Calendar.HOUR_OF_DAY, hour);
mCalen.set(Calendar.MINUTE, minute);
int hour12format6 = mCalen.get(Calendar.HOUR);
hourOfDay = mCalen.get(Calendar.HOUR_OF_DAY);
minute = mCalen.get(Calendar.MINUTE);
ampm = mCalen.get(Calendar.AM_PM);
String ampmStr6 = (ampm == 0) ? "AM" : "PM";
btnSupper.setText(hour12format6 + " : " + minute + " / " + ampmStr6);
break;
}
}
};
#Override
public void onClick(View v) {
showDialog(Time_PICKER_ID);
}
}

Your activity or fragment should implements View.OnClickListener.
Then each button should register each button like so:
Button buttonOne = (Button) findViewById(R.id.button_one);
Button buttonTwo = (Button) findViewById(R.id.button_two);
buttonOne.setOnClickListener(this);
buttonTwo.setOnClickListener(this);
Then in your onClick method:
#Override
public void onClick(View temp)
{
switch(temp.getId()) {
case R.id.button_one:
//do something
break;
case R.id.button_two:
//do something
break;
}
}
An other option is to set the method to be called in the layout file for each button using android:onClick="myMethodOne". This way you can call different methods if you want or even the same method and differentiate on ids like you do in the onClick methods.

Change this:
#Override
public void onClick(View v) {
showDialog(Time_PICKER_ID);
}
to
#Override
public void onClick(View v) {
timePickerInput = v.getId();
showDialog(Time_PICKER_ID);
}
You need to set the timerPickerInput to be the id of the button so you know which button to display the time in.

Related

setOnClickListener in Android for Two TextViews

I have a Simple Date Picker App in Android and it's working fine when I click on First TextView.
How Can I activate the same Calendar with a second TextView. One TextView shows the Long Date and other shows the Short Date
public class MainActivity extends AppCompatActivity {
private TextView mDisplayLongDate;
TextView mDisplayShortDate;
CheckBox checkBoxVisibility;
private DatePickerDialog.OnDateSetListener mDateSetListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDisplayLongDate = findViewById(R.id.tvLDate);
mDisplayShortDate = findViewById(R.id.tvSDate);
//View checkBox = findViewById(R.id.checkBox);
checkBoxVisibility = findViewById(R.id.checkBox_visibility);
//boolean isChecked = checkBoxVisibility.isClickable();
boolean isChecked = checkBoxVisibility.isChecked();
updateTextVisibility(isChecked);
checkBoxVisibility.setOnCheckedChangeListener((buttonView, isChecked1) -> {
//Step 05 - Updating UI according to the currently changed state
updateTextVisibility(isChecked1);
});
mDisplayLongDate.setOnClickListener(view -> {
Calendar cal = Calendar.getInstance();
With a CheckBox, the TextView Shows Long Date and Short Date.
I cannot click on the short date to edit the Calendar. How to activate the Calendar in both situation.
String dateLong = monthStr + "/" + day + "/" + year;
String dateShort = monthStr + "/" + day;
mDisplayLongDate.setText(dateLong);
mDisplayShortDate.setText(dateShort);
};
}
private void updateTextVisibility(boolean isChecked) // When checking the trigger (checkbox)
{
if (isChecked)
{
mDisplayShortDate.setVisibility(View.VISIBLE);
mDisplayLongDate.setVisibility(View.GONE);
}
else
{
mDisplayShortDate.setVisibility(View.GONE);
mDisplayLongDate.setVisibility(View.VISIBLE);
}
You can use this type of method and call it where you need .
private void getCal() {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int monthStr = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dPDialog = new DatePickerDialog(MainActivity.this, android.R.style.Theme_Holo_Light_Dialog,
new DatePickerDialog.OnDateSetListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
public void onDateSet(DatePicker datepicker, int selectedY, int selectedM, int selectedD) {
String[] months = new DateFormatSymbols(Locale.ENGLISH).getMonths();
String dateLong = months[selectedM] + "/" + selectedD + "/" + selectedY;
String dateShort = months[selectedM] + "/" + selectedD;
// String dateLong = (selectedM + 1) + "/" + selectedD + "/" + selectedY;
//String dateShort = (selectedM + 1) + "/" + selectedD;
mDisplayLongDate.setText(dateLong);
mDisplayShortDate.setText(dateShort);
}
}, year, monthStr, day);
dPDialog.show();
}
Example class-
public class MainActivity extends AppCompatActivity {
private TextView mDisplayLongDate;
TextView mDisplayShortDate;
CheckBox checkBoxVisibility;
private DatePickerDialog.OnDateSetListener mDateSetListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDisplayLongDate = findViewById(R.id.tvLDate);
mDisplayShortDate = findViewById(R.id.tvSDate);
mDisplayLongDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getCal();
}
});
mDisplayShortDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getCal();
}
});
}
private void getCal() {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int monthStr = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dPDialog = new DatePickerDialog(MainActivity.this, android.R.style.Theme_Holo_Light_Dialog,
new DatePickerDialog.OnDateSetListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
public void onDateSet(DatePicker datepicker, int selectedY, int selectedM, int selectedD) {
String[] months = new DateFormatSymbols(Locale.ENGLISH).getMonths();
String dateLong = months[selectedM] + "/" + selectedD + "/" + selectedY;
String dateShort = months[selectedM] + "/" + selectedD;
// String dateLong = (selectedM + 1) + "/" + selectedD + "/" + selectedY;
//String dateShort = (selectedM + 1) + "/" + selectedD;
mDisplayLongDate.setText(dateLong);
mDisplayShortDate.setText(dateShort);
}
}, year, monthStr, day);
dPDialog.show();
}
}

How to set 1 timepicker in 2 different EditText?

I have 2 edit text fields one for starting time and one for ending time. And I have written
a single java function for time picker for both of the edit text fields.
The issue is when I try to set time in the ending time edit text field it sets time to the starting time
edit text field.
This my xml code:
<androidx.appcompat.widget.AppCompatEditText
android:id="#+id/starting_time_et"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="305dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:hint="Click To Add Starting Time Of Course"
android:textStyle="bold">
</androidx.appcompat.widget.AppCompatEditText>
<androidx.appcompat.widget.AppCompatEditText
android:id="#+id/ending_time_et"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="355dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:hint="Click To Add Ending Time Of Course"
android:textStyle="bold">
This is my java code for time picker:
Button backButton;
EditText startingTime;
EditText endingTime;
TimePickerDialog timePickerDialog;
Calendar calender;
int currentHour;
int currentMinute;
String amPm;
String minuteWith_0_OnLeft;
startingTime = findViewById(R.id.starting_time_et);
startingTime.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
startingTimeAndEndingTime();
timePickerDialog.show();
}
});
endingTime = findViewById(R.id.ending_time_et);
endingTime.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
startingTimeAndEndingTime();
timePickerDialog.show();
}
});
public void startingTimeAndEndingTime(){
calender = Calendar.getInstance();
currentHour = calender.get(Calendar.HOUR_OF_DAY);
currentMinute = calender.get(Calendar.MINUTE);
timePickerDialog = new TimePickerDialog(AddCourses.this, new
TimePickerDialog.OnTimeSetListener(){
#Override
public void onTimeSet(TimePicker timePicker, int hourOfDay, int minute){
if(hourOfDay > 12)
{
hourOfDay -= 12;
amPm = "Pm";
}
else if(hourOfDay == 0)
{
hourOfDay += 12;
amPm = "Am";
}
else if(hourOfDay == 12)
{
amPm = "Pm";
}
else
{
amPm = "AM";
}
if( minute < 10 )
{
minuteWith_0_OnLeft = "0" + minute;
}
else
{
minuteWith_0_OnLeft = String.valueOf(minute);
}
startingTime.setText(MessageFormat.format("{0}:{1}{2}", hourOfDay, minuteWith_0_OnLeft, amPm));
}
}, currentHour, currentMinute, false);
}
The code is working as expected. You are setting the text of the startingTime EditText in startingTimeAndEndingTime() function and calling it from both startingTime and endingTime click listener. To fix this you can modify your your startingTimeAndEndingTime() function like this.
public void startingTimeAndEndingTime(boolean isStart) {
calender = Calendar.getInstance();
currentHour = calender.get(Calendar.HOUR_OF_DAY);
currentMinute = calender.get(Calendar.MINUTE);
timePickerDialog = new TimePickerDialog(AddCourses.this, new TimePickerDialog.OnTimeSetListener()
{
#Override
public void onTimeSet(TimePicker timePicker, int hourOfDay, int minute)
{
if(hourOfDay > 12)
{
hourOfDay -= 12;
amPm = "Pm";
}
else if(hourOfDay == 0)
{
hourOfDay += 12;
amPm = "Am";
}
else if(hourOfDay == 12)
{
amPm = "Pm";
}
else
{
amPm = "AM";
}
if( minute < 10 )
{
minuteWith_0_OnLeft = "0" + minute;
}
else
{
minuteWith_0_OnLeft = String.valueOf(minute);
}
if (isStart) {
startingTime.setText(MessageFormat.format("{0}:{1}{2}", hourOfDay, minuteWith_0_OnLeft, amPm));
} else {
endingTime.setText(MessageFormat.format("{0}:{1}{2}", hourOfDay, minuteWith_0_OnLeft, amPm));
}
}
}, currentHour, currentMinute, false);
}
Let my startingTimeAndEndingTime Function accept an EditText parameter like this:
public void startingTimeAndEndingTime(EditText editText)
And then inside that method, replace startingTime.setText(MessageFormat.format("{0}:{1}{2}", hourOfDay, minuteWith_0_OnLeft, amPm)); with this:
editText.setText(MessageFormat.format("{0}:{1}{2}", hourOfDay, minuteWith_0_OnLeft, amPm));
Now in onClick of startingTime and endingTime, call the method like this, for startingTime:
startingTimeAndEndingTime(startingTime);
and for endingTime:
startingTimeAndEndingTime(endingTime);
SO my code will be like this:
startingTime = findViewById(R.id.starting_time_et);
startingTime.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
startingTimeAndEndingTime( startingTime );
timePickerDialog.show();
}
});
endingTime = findViewById(R.id.ending_time_et);
endingTime.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
startingTimeAndEndingTime( endingTime );
timePickerDialog.show();
}
});
public void startingTimeAndEndingTime( EditText startingAndEndingTImeEt )
{
calender = Calendar.getInstance();
currentHour = calender.get(Calendar.HOUR_OF_DAY);
currentMinute = calender.get(Calendar.MINUTE);
timePickerDialog = new TimePickerDialog(AddCourses.this, new TimePickerDialog.OnTimeSetListener()
{
#Override
public void onTimeSet(TimePicker timePicker, int hourOfDay, int minute)
{
if(hourOfDay > 12)
{
hourOfDay -= 12;
amPm = "Pm";
}
else if(hourOfDay == 0)
{
hourOfDay += 12;
amPm = "Am";
}
else if(hourOfDay == 12)
{
amPm = "Pm";
}
else
{
amPm = "AM";
}
if( minute < 10 )
{
minuteWith_0_OnLeft = "0" + minute;
}
else
{
minuteWith_0_OnLeft = String.valueOf(minute);
}
//startingTime.setText(hourOfDay + ":" + minute + amPm);
startingAndEndingTImeEt.setText(MessageFormat.format("{0}:{1}{2}", hourOfDay, minuteWith_0_OnLeft, amPm));
}
}, currentHour, currentMinute, false);
}

What is the cause of the int variable problem?

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.

How to calculate the current millisecond provided if there is old millisecond in java

I making a timer in my android app. I have a scenario where I dont need to stop the timer even if the app is closed. If the timer is running and user closes the app and reopen it after sometime. He should see the latest time on the timer. But currently I am not able to show the latest time. I am only able to show the time when the user killed the app. I am storing the time of the timer and when the user open the app I am putting the stored time back to the timer. But I want to show the latest time. Here what I have done till now. I am using chronometer widget.
MainActivity.class:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = MainActivity.class.getSimpleName();
Chronometer tvTextView;
Button btnStart, btnStop;
private int state = 0; //0 means stop state,1 means play, 2 means pause
SharedPreferences sharedPreferences;
private boolean running = false;
private long pauseOffSet = -1;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvTextView = findViewById(R.id.textview);
progressBar = findViewById(R.id.puzzleProgressBar);
btnStart = findViewById(R.id.button1);
btnStop = findViewById(R.id.button2);
btnStart.setOnClickListener(this);
btnStop.setOnClickListener(this);
sharedPreferences = getSharedPreferences("myprefs", MODE_PRIVATE);
state = sharedPreferences.getInt("state", 0);
tvTextView.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
#Override
public void onChronometerTick(Chronometer chronometer) {
long time = SystemClock.elapsedRealtime() - chronometer.getBase();
pauseOffSet=time;
Log.e(TAG,"pauseOffSet "+pauseOffSet);
if (time >= 79200000) {
tvTextView.setBase(SystemClock.elapsedRealtime());
tvTextView.stop();
running = false;
progressBar.setProgress(0);
} else {
chronometer.setText(setFormat(time));
int convertTime = (int) time;
progressBar.setProgress(convertTime);
}
}
});
if (state == 1) { // its in play mode
running = true;
tvTextView.setBase(SystemClock.elapsedRealtime() - sharedPreferences.getLong("milli", 0));
tvTextView.start();
} else if (state == 2) { //its in pause mode
running = false;
pauseOffSet = sharedPreferences.getLong("milli", -1);
long time = SystemClock.elapsedRealtime() - pauseOffSet;
tvTextView.setBase(time);
int convertTime = (int) pauseOffSet;
progressBar.setProgress(convertTime);
} else {
running = false;
tvTextView.setBase(SystemClock.elapsedRealtime());
}
}
public void onClick(View v) {
if (btnStart == v) {
if (!running) {
if (pauseOffSet != -1) {
pauseOffSet = sharedPreferences.getLong("milli", -1);
}
tvTextView.setBase(SystemClock.elapsedRealtime() - pauseOffSet);
tvTextView.start();
state = 1;
pauseOffSet = 0;
running = true;
}
} else if (btnStop == v) {
if (running) {
tvTextView.stop();
pauseOffSet = SystemClock.elapsedRealtime() - tvTextView.getBase();
state = 2;
running = false;
}
}
}
#Override
protected void onStop() {
super.onStop();
sharedPreferences.edit().putLong("milli", pauseOffSet).commit();
sharedPreferences.edit().putInt("state", state).commit();
}
#Override
protected void onDestroy() {
Log.e(TAG, "onDestroy called, state: " + state);
super.onDestroy();
}
String setFormat(long time) {
int h = (int) (time / 3600000);
int m = (int) (time - h * 3600000) / 60000;
int s = (int) (time - h * 3600000 - m * 60000) / 1000;
String hh = h < 10 ? "0" + h : h + "";
String mm = m < 10 ? "0" + m : m + "";
String ss = s < 10 ? "0" + s : s + "";
return hh + ":" + mm + ":" + ss;
}
}

Retrieving times from two TimePickers in DialogFragments

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...
}

Categories

Resources