Calling nonstatic function when TimePicker is done - java

I'm kind of new to Android, and I'm currently struggling with the TimePicker. So, I've got the TimePicker here:
public class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {
public String time;
#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
time = hourOfDay + ":" + minute;
//update global variable
MockDB.setCheckout(time);
}
}
This is working, but after the user selects a time I want to call a function in the activity the picker is in to change the button colors and text. This is in a function called ReserveProduct that extends AppCompatActivity.
public void animateButtons() {
//picker disappears until next button is clicked
Button picker = (Button) findViewById(R.id.button6);
picker.setVisibility(View.GONE);
Button picker1 = (Button) findViewById(R.id.button7);
picker1.setVisibility(View.GONE);
if (settingReturn == false) {
//first button turns gray
Button bttn1 = (Button) findViewById(R.id.buttonCheckIn);
bttn1.setBackgroundResource(R.drawable.button_inactive);
String time = ((MockDB) this.getApplication()).getCheckout();
bttn1.setText("Check Out: 12:27 PM");
//new button appears
Button bttn2 = (Button) findViewById(R.id.buttonCheckOut);
bttn2.setVisibility(View.VISIBLE);
settingReturn = true;
} else {
//make 2nd button inactive
Button bttn2 = (Button) findViewById(R.id.buttonCheckOut);
bttn2.setBackgroundResource(R.drawable.button_inactive);
String time = ((MockDB) this.getApplication()).getReturn();
bttn2.setText("Return: 1:27 PM");
//show new buttons
Button set = (Button) findViewById(R.id.buttonSet);
set.setVisibility(View.VISIBLE);
Button home = (Button) findViewById(R.id.buttonHome);
home.setVisibility(View.VISIBLE);
}
}
My issue is that this function is not static, so I'm not able to simply call it from the TimePicker class. I can't move the button changing functionality to the TimePicker class because I need to be able to extend AppCompatActivity, but AppCompatActivity and DialogFragment have a conflicting class. I also can't make the animateButtons() class static because then the findViewById() functionality throws an error.
Please help!!

Instantiate the class first, i.e.
(new SomeClass()).someMethod();

Related

Reset Horizontal Progress Bar to 0 every night 12oClock?

I want to reset my horizontal progressbar to 0 every night at 12.
Here is my code.
public class MainActivity extends AppCompatActivity {
private TextView textView;
Button btn;
private int Counter counter;
Progressbar progressbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.txtvw);
progressbar = findViewById(R.id.progressbar_Horizontal);
progressbar.setMax(10);
btn = findViewById(R.id.btn_clc);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
counter++;
textView.setText(String.valueOf(counter));
progressbar.setProgress(counter)
}
});
Calendar calendar = Calendar.getInstance();
int hour = 23;
int minute = 59;
int second = 59;
int curHour = calendar.get(Calendar.HOUR_OF_DAY);
int curMinute = calendar.get(Calendar.MINUTE);
int curSecond = calendar.get(Calendar.SECOND);
if (hour==curHour && minute==curMinute && second==curSecond) {
progressbar.setProgress(0);
}
}
}
In this method at the output there is no response to the progressbar! Is this the right way to do or is there any other way?
You don't get any response because you're defining the action in OnCreate method. This method is executed one time when you enter the Activity. So this action defined only works if you launch your Ativity exactly at 23:59:59.
If you want to do it right, implement AlarmManager. You can set the time you want (23:59:59) and do whatever you want (reset the bar) at that moment. You can implement it also when the app is closed, in the background or when the screen is off.
Take a look at this: Alarm Manager Example

NullPointerException when setting Date in Android app [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I am following this tutorial for implementing date and time on edit text click.
public class LoadActivity extends AppCompatActivity {
#SuppressLint("StaticFieldLeak")
static EditText DateEdit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_load);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
EditText startTimeEditText = (EditText) findViewById(R.id.start_time);
startTimeEditText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showTruitonTimePickerDialog(v);
showTruitonDatePickerDialog(v);
}
});
} // end onCreate
public void showTruitonDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
public static class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(requireActivity(), this, year, month, day);
}
}
#SuppressLint("SetTextI18n")
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
DateEdit.setText(day + ":" + (month + 1) + ":" + year);
}
}// end main class
I am able to see the date fragment in my app but when I press ok button the app crashes and I am getting error
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
at com.thumbsol.accuratemobileassetsmanagament.LoadActivity$DatePickerFragment.onDateSet(LoadActivity.java:300)
at android.app.DatePickerDialog.onClick(DatePickerDialog.java:134)
The line number 300 is DateEdit.setText(day + ":" + (month + 1) + ":" + year);
How can I get rid of this error? Any help would be highly appreciated.
You only define static EditText DateEdit, and also need to get it via findViewById.
for example:
DateEdit = (EditText) findViewById(R.id.date_edit);
That's because you're not setting the value of DateEdit anywhere in your code.
Tip: try to not use a view as static. It may cause leaks.

is accessing number pickers in TimePicker possible?

It seems TimePicker is made of three inner NumberPickers. Is it possible to access them? it's needed to access and modify each of them.
public static class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
TimePicker dialog = new TimePicker(getActivity(), this, 22, 30,
DateFormat.is24HourFormat(getActivity()));
// Create a new instance of TimePickerDialog and return it
return dialog;
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// Do something with the time chosen by the user
}
}
In dialog, I've created a TimePicker to be shown, but I have to modify TimePicker minutes column(spinner) and add 15min intervals. I want to know if there is any way to access those NumberPickers alone.
UPDATE
i posted answer below, however it was one of the hardest modification in android built-in components for me, i finally found the answer and shared it here but idk why it got down-vote?
finally i found a solution. i'm getting minute column here and setting a 15 minute interval there.
changeTimepicker(R.id.from_time_picker, 15);
method implementation:
try {
Class<?> rClass = Class.forName("com.android.internal.R$id");
// Field timePicker = rClass.getField(name);
TimePicker mTimePicker = (TimePicker) findViewById(id);
Field m = rClass.getField("minute");
NumberPicker mMinuteSpinner = (NumberPicker) mTimePicker.findViewById(m.getInt(null));
mMinuteSpinner.setMinValue(0);
mMinuteSpinner.setMaxValue((60 / increment) - 1);
List<String> displayedValues = new ArrayList<String>();
for (int i = 0; i < 60; i += increment) {
displayedValues.add(String.format("%02d", i));
}
mMinuteSpinner.setDisplayedValues(displayedValues.toArray(new String[0]));
} catch (Exception e) {
e.printStackTrace();
}
}

Waiting for TimePickerFragment to return time

New to JAVA and Android coding and trying my first practical project.
I don't understand how to make processing wait until timekeeperdialog returns a value.
In my Main Activity I have created getters and setters to variables (first time doing this btw):
private int pickhour;
private int pickminute;
public MainActivity(){
pickhour = 0;
pickminute = 0;
}
public void setpickhour(int pickhour) {
this.pickhour = pickhour;
}
public int getpickhour(){
return this.pickhour;
}
public void setpickminute(int pickminute) {
this.pickminute = pickminute;
}
public int getPickminute(int pickminute) {
return this.pickminute;
}
I call the dialog box with this, and then expecting processing to pause until the TimePicker returns a value, I have a Toast to show results. The Toast fires as soon as the Timepicker appears.
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(),"TimePicker");
Toast.makeText(getApplicationContext(), "Time Picker" + String.valueOf(pickhour) + ":" + String.valueOf(pickminute), Toast.LENGTH_LONG).show();
And my fragment looks like this :
public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener{
private MainActivity ma = new MainActivity();
#Override
public Dialog onCreateDialog(Bundle savedInstanceState){
//Use the current time as the default values for the time picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
//Create and return a new instance of TimePickerDialog
return new TimePickerDialog(getActivity(),this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
//onTimeSet() callback method
public void onTimeSet(TimePicker view, int hourOfDay, int minute){
//Do something with the user chosen time
//Get reference of host activity (XML Layout File) TextView widget
ma.setpickhour(hourOfDay);
ma.setpickminute(minute);
}
}
I tried looping through a boolean set by the ontimeset method to force waiting on a return value, but my application just hung.
What fundamental concept am I missing? I'm on vacation, so spent a day & a half trying to figure this out.
You can try this -
public class TimePickerFragment extends DialogFragment implements
TimePickerDialog.OnTimeSetListener{
private MainActivity ma = new MainActivity();
#Override
public Dialog onCreateDialog(Bundle savedInstanceState){
//Use the current time as the default values for the time picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
//Create and return a new instance of TimePickerDialog
return new TimePickerDialog(getActivity(),this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
//onTimeSet() callback method
public void onTimeSet(TimePicker view, int hourOfDay, int minute){
//Do something with the user chosen time
//Get reference of host activity (XML Layout File) TextView widget
ma.setpickhour(hourOfDay);
ma.setpickminute(minute);
Toast.makeText(getApplicationContext(), "Time Picker" + String.valueOf(pickhour) + ":" + String.valueOf(pickminute), Toast.LENGTH_LONG).show();
}
}
And if you are only using fragment for timePicker there is no need of the fragment.
In this case you can try this in MainActivity -
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int hourOfDay, int minute) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, hourOfDay);
cal.set(Calendar.MINUTE, minute);
setpickhour(hourOfDay);
setpickminute(minute);
}
}, hour, minute, true);//Yes 24 hour time
mTimePicker.setTitle("Time Picker");
mTimePicker.show();
Does your code work? Because you cannot pass "this" as second argument in TimePickerDialog constructor.

Android DatePickerDialog parameters

I'm creating button dynamically at runtime which their click event opens a datepickerdialog. So like this:
Button btnDate = new Button(this);
btnDate.setText("Date");
btnDate.setTag(new UDAControlItemTag(q.getiQuestionID(),-1,f.getiSectionID(),f.getiGroup(),-1,"Date",""));
btnDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Button tempBtn = (Button)v;
UDAControlItemTag tempQ = (UDAControlItemTag)tempBtn.getTag();
showDialog(DATE_DIALOG_ID_Question);
//tempBtn.setText(Integer.toString(mTempMonth));
}
});
Then I have the listener where i can get the values and stuff but because I'm creating the controls dynamically, i keep these values of each control in an ArrayList with different properties. The issue I have is how to get the parameters i need to correctly determine which button was clicked in order to put in the correct properties for that question into the ArrayList.
private DatePickerDialog.OnDateSetListener mDateSetListenerQuestion =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
mTempYear = year;
mTempMonth = monthOfYear;
mTempDay = dayOfMonth;
}
};
So in there i have the value of the dialog, but i need to have a QuestionID which is associated to the button that the user clicked, in order to put the value into the ArrayList of all the answers for all that dynamic controls on the activity. I'd really appreciate any ideas, thanks.
Instead of that listener you could use your own class that implements the DatePickerDialog.OnDateSetListener interface and also has a constructor that takes an int, the QuestionID. Something like this:
public class TheSpecialListener implements
DatePickerDialog.OnDateSetListener {
private int id;
public TheSpecialListener(int id) {
this.id = id;
}
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mTempYear = year;
mTempMonth = monthOfYear;
mTempDay = dayOfMonth;
// id is the QuestionID so you now can identify the Button that started the dialog
}
};
Now when you click a Button you'll update a field with that Button's QuestionID that will be used in the onCreateDialog method(which I don't know how you implemented):
private int questionId;
and in the Button listener:
//...
Button tempBtn = (Button)v;
UDAControlItemTag tempQ = (UDAControlItemTag)tempBtn.getTag();
questionId = //here pass the Button's id or whatever
showDialog(DATE_DIALOG_ID_Question);
and in the onCreateDialog method instantiate the above special listener and pass it the questionId field which will hold the identifier, as it will be updated each time a Button is clicked:
DatePickerDialog spd = new DatePickerDialog(this,
new TheSpecialListener(questionId), 2012, 6, 16);

Categories

Resources