Waiting for TimePickerFragment to return time - java

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.

Related

Auto Silent android device with timer set my user

I have 2 buttons in my app
starttime and endtime
Now I want the device to turn in silent mode during the start and end time duration set by the user.....how can I do this?
My code for taking input for starttime and endtime
mainactivity.java code
package com.example.h.manualsilent;
public class MainActivity extends AppCompatActivity {
TimePickerDialog tpd;
SimpleDateFormat simpleDateFormat;
String time;
Button sttime;
Button entime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sttime=(Button)findViewById(R.id.startbtn);
entime=(Button)findViewById(R.id.endbtn);
}
public void starttime(View view){
Calendar cal=Calendar.getInstance();
simpleDateFormat=new SimpleDateFormat("hh:mm a");
int hour=cal.get(Calendar.HOUR);
int minute=cal.get(Calendar.MINUTE);
//int inst=cal.get(Calendar.AM_PM);
tpd=new TimePickerDialog(MainActivity.this, new
TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Time time = new Time(hourOfDay, minute,0);
//little h uses 12 hour format and big H uses 24 hour format
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("h:mm a");
//format takes in a Date, and Time is a sublcass of Date
String s = simpleDateFormat.format(time);
sttime.setText(s);
}
},hour,minute,false);
tpd.show();
}
public void endtime(View view){
Calendar cal=Calendar.getInstance();
int hour=cal.get(Calendar.HOUR);
int minute=cal.get(Calendar.MINUTE);
//int inst=cal.get(Calendar.AM_PM);
tpd=new TimePickerDialog(MainActivity.this, new
TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Time time = new Time(hourOfDay, minute,0);
//little h uses 12 hour format and big H uses 24 hour format
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("h:mm a");
//format takes in a Date, and Time is a sublcass of Date
String s = simpleDateFormat.format(time);
entime.setText(s);
}
},hour,minute,false);
tpd.show();
}
}
You can use the AudioManager class.
In this class you're looking for setRingerMode() function.
AudioManager audiomanage = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
audiomanage.setRingerMode(AudioManager.RINGER_MODE_SILENT);
The values you can pass into the function are:
The ringer mode, one of RINGER_MODE_NORMAL, RINGER_MODE_SILENT, or
RINGER_MODE_VIBRATE.
You have to add this into the manifest file:
android.permission.MODIFY_AUDIO_SETTINGS
I saw this here - https://stackoverflow.com/a/3738768/8214839
You can use AudioManager for changing from genral mode to silent mode.
Code:
AudioManager audioManager;
audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
// changing to silent mode
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
You have to give the required permission also in manifest file.
android.permission.MODIFY_AUDIO_SETTINGS
You can use the above code to set the phone to silent based on the condition that you need.
You can also change back to VIBRATE or GENERAL using AudioManager.RINGER_MODE_VIBRATE or AudioManager.RINGER_MODE_NORMAL respectively.

Calling nonstatic function when TimePicker is done

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();

Open DatePicker with suggested date

I need to open a DatePicker with a default date based on the YEAR-MONTH-DAY_OF_MONTH properties of a GregorianCalendar.
Here is the code where I open the DatePicker:
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
For exemple, if my values are like this:
MyCalendar.YEAR = 2017
MyCalendar.MONTH = 2
MyCalendar.DAY_OF_MONTH = 22
The default value set when I open the DatePicker would be:
What do I have to add to do that?
Basically straight from Android | Pickers
Plus, just like any other Fragment, you can use set and get-Arguments to pass data into the fragment.
Details: Best practice for instantiating a new Android Fragment
public static class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
public static DatePickerFragment newInstance(int year,int month,int day) {
Bundle b = new Bundle();
b.putInt("year", year);
// put others...
Fragment f = new DatePickerFragment();
f.setArguments(b);
return f;
}
#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);
// Update using the arguments
Bundle args = getArguments();
if (args != null) {
year = args.getInt("year");
// get others...
}
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
}
}
And use that newInstance method.
DialogFragment newFragment = DatePickerFragment.newInstance(2017,02,07);
newFragment.show(getFragmentManager(), "datePicker");

Unable to call object method

I'm working on an android app. That uses a 'datepicker' as part of a data entry form. I've written a getter method "onDateSet" to return data from the object but i'm unable to call the method from the instance of the class.
line: datePicker.getSelectedDate(); I'm getting a 'method cannot be resolved' error
I get the same message when I try and access the variable directly. datePicker.selecteddate
I would be grateful if someone could point me in the right direction.
public class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
#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(getActivity(), this, year, month, day);
}
int selectedDate;
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
selectedDate = day+month+year;
}
public int getSelectedDate() {
return selectedDate;
}
}
public void showDatePickerDialog(View view) {
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getFragmentManager(), "datePicker");
int output = datePicker.getSelectedDate();
}
You have:
DialogFragment datePicker = new DatePickerFragment();
You mean:
DatePickerFragment datePicker = new DatePickerFragment();
This is because your methods are members of your subclassed DatePickerFragment, not of the base class DialogFragment.
Essentially, when you refer to an object through its base type, the compiler only knows about the methods the base type declares. It has no way of knowing that an arbitrary DialogFragment is actually a DatePickerFragment (or any other derived type).
An alternative, if you know it is a DatePickerFragment, is to explicitly cast datePicker to a DatePickerFragment:
DialogFragment datePicker = new DatePickerFragment();
...
int output = ((DatePickerFragment)datePicker).getSelectedDate();
This, of course, will fail with a ClassCastException if datePicker isn't actually a DatePickerFragment.

DateFormat produces incorrect output

I've got a couple of Buttons that initially display the current date and the current time, respectively. When clicking in the Button that displays the date, it shows a DatePickerFragment that allows the user to choose a date, and then changes the Button's text to the date selected by the user. The other Button does exactly the same but with a TimePickerFragment.
To initialize the Buttons I use the following code:
protected void onCreate(Bundle savedInstanceState){
...
df = DateFormat.getDateInstance();
tf = DateFormat.getTimeInstance();
initDate = new GregorianCalendar();
...
updateDateButtons();
updateTimeButtons();
}
private void updateTimeButtons() {
tf.setCalendar(initDate);
String text = tf.format(initDate.getTime());
btnIniTime.setText(text.substring(0, text.lastIndexOf(":")));
}
private void updateDateButtons() {
df.setCalendar(initDate);
btnIniDate.setText(df.format(initDate.getTime()));
}
Initially, both buttons behave in an expected manner: btnIniTime shows the current time, and btnIniDate shows the current date.
As I said, when the user clicks the btnIniTime button, it shows a TimePickerFragment that prompts the user to choose a time, and the selected time is correctly displayed in btnIniTime.
The problem starts with btnIniDate, that should do the same, but using a DatePickerFragment instead of a TimePickerFragment. When the user selects a date, the button then displays an incorrect date. For example, if I choose 2013 Aug 30, the displayed date turns to be 2013 Aug. 26. If I choose 2013 Sep 1, it then shows 2013 Sep 29!
The classes and methods that I use to change the date ara arranged in the following way:
public abstract static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
protected TaskActivity activity;
protected Calendar c;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = (TaskActivity) activity;
}
#Override
public abstract Dialog onCreateDialog(Bundle savedInstanceState);
public void onDateSet(DatePicker view, int year, int month, int day) {
if(activity instanceof TaskActivity){
setDateResult(year, month, day);
}
}
protected abstract void setDateResult(int year, int month, int day);
}
public static class InitDatePickerFragment extends DatePickerFragment {
#Override
protected void setDateResult(int year, int month, int day) {
activity.setInitDate(year, month, day);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = activity.getInitDate();
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(getActivity(), this, year, month, day);
}
}
...
public Calendar getInitDate() {
return initDate;
}
public void setInitDate(int year, int month, int day){
Log.d("TaskActivity", "Year: " + year + "; Month: " + month + "; Day: " + day);
initDate.set(Calendar.YEAR, year);
initDate.set(Calendar.MONTH, month);
initDate.set(Calendar.DAY_OF_WEEK, day);
updateDateButtons();
}
When you push the button:
#Override
public void onClick(View v) {
if(v.equals(btnIniDate)){
DialogFragment newFragment = new InitDatePickerFragment();
newFragment.show(getSupportFragmentManager(), "initDatePicker");
}
...
}
By the way, when setting the date, LogCat produces the following output (I've chosen 2013 Aug 30):
Year: 2013; Month: 7; Day:30
The Problem might be
initDate.set(Calendar.DAY_OF_WEEK, day);
in your setInitDate(). This updates only the day of the week. So your date jumps +-6
use
initDate.set(Calendar.DAY_OF_MONTH, day);

Categories

Resources