Execute a method according to device's time - java

I have a timePicker
String mName = input.getText().toString();
if (input.getParent() != null)
((ViewGroup) input.getParent()).removeView(input);
if (layout.getParent() != null)
((ViewGroup) layout.getParent()).removeView(layout);
mAlertDialog.dismiss();
Calendar mcurrentTime = Calendar.getInstance();
int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
int minute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(Chat.this, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
Toast.makeText(getApplicationContext(), "Make sure you have internet access at this time selected",
Toast.LENGTH_LONG).show();
}
}, hour, minute, true);// Yes 24 hour time
mTimePicker.setTitle("Select Time");
mTimePicker.show();
I want a method to execute at the time picked by the user. How can i achieve this. Say i want to change a particular data in firebase at the given time how can i do that? Please help me out

Related

change current date to new selected date for retrieving firebase data

I'm trying to display data from firebase using dates. But I only know how to display data for the current date. I would like to change the dates so I can display data from firebase with different dates. The current code I have is only displaying the data on a recyclerView from 8-9-2020. I would like to get the data from the previous day which is 7-9-2020.
firebaseAuth= FirebaseAuth.getInstance();
FirebaseUser user = firebaseAuth.getCurrentUser();
calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String currentDate = sdf.format(calendar.getTime());
mDatabase = FirebaseDatabase.getInstance().getReference().child(user.getUid()).child("food").child(currentDate);
buttonCalendar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openCalendar();
}
});
Intent incomingIntent = getIntent();
String date = incomingIntent.getStringExtra("date");
theDate.setText(date);
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(#NonNull CalendarView view, int year, int month, int dayOfMonth) {
month = month +1;
String date = String.format("%02d-%02d-%d", dayOfMonth, month, year);
Intent intent = new Intent(CalendarActivity.this, Breakfast.class);
intent.putExtra("date", date);
startActivity(intent);
}
});
What I'm trying to do is it will display the current date data, then when I select a new date from the calendar, it will retrieve data of the newly selected date.
I would like to somehow update the .child(currentDate) to .child(date) in which the date contains the newly selected date.
As per your code, you're opening a calendar in the new activity I can suggest if you want to use android DatePickerDialog to get a date in the same activity.
And if you want to get a date back from a particular activity you can use a startActivityForResult(yourIntent,request_code); and get result and data in
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
And after getting a successful result you can use the below method to get your firebase data.
private void getFirebaseData(String date){
mDatabase = FirebaseDatabase.getInstance().getReference().child(user.getUid()).child("food").child(date);
// rest is your code
}
I figured out simple way to do it:
setDate();
String date = setDate();
if (date == null || date.equals("")){
date = currentDate;
}
mDatabase = FirebaseDatabase.getInstance().getReference().child(user.getUid()).child("food").child(date);
made a method for setting the new date:
public String setDate(){
Intent incomingIntent = getIntent();
String date = incomingIntent.getStringExtra("date");
theDate.setText(date);
return date;
}

How to pass time value from timepicker to textView in another activity in Android studio(Java)?

I did everything when it comes to creating notification on selected time in timepicker but I cannot pass it to textview in another activity. Can someone help me with this?
I want to pass time value from SecondActivity to textView named textviewAlarm in HomeActivity when clicking button Done.
public class Second extends AppCompatActivity implements View.OnClickListener{
private int notificationId = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_layout);
// Set Onclick Listener.
findViewById(R.id.setBtn).setOnClickListener(this);
findViewById(R.id.cancelBtn).setOnClickListener(this);
}
#Override
public void onClick(View view) {
EditText editText = findViewById(R.id.editText);
TimePicker timePicker = findViewById(R.id.timePicker);
// Set notificationId & text.
Intent intent = new Intent(Second.this, AlarmReceiver.class);
intent.putExtra("notificationId", notificationId);
intent.putExtra("todo", editText.getText().toString());
// getBroadcast(context, requestCode, intent, flags)
PendingIntent alarmIntent = PendingIntent.getBroadcast(Second.this, 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
switch (view.getId()) {
case R.id.setBtn:
int hour = timePicker.getCurrentHour();
int minute = timePicker.getCurrentMinute();
// Create time.
Calendar startTime = Calendar.getInstance();
startTime.set(Calendar.HOUR_OF_DAY, hour);
startTime.set(Calendar.MINUTE, minute);
startTime.set(Calendar.SECOND, 0);
long alarmStartTime = startTime.getTimeInMillis();
// Set alarm.
// set(type, milliseconds, intent)
alarm.set(AlarmManager.RTC_WAKEUP, alarmStartTime, alarmIntent);
// Get TextView object which is used to show user pick date and time.
TextView textView = (TextView)findViewById(R.id.textViewAlarm);
StringBuffer strBuffer = new StringBuffer();
strBuffer.append("You selected date time : ");
strBuffer.append(this.notificationId);
textView.setText(strBuffer.toString());
break;
case R.id.cancelBtn:
alarm.cancel(alarmIntent);
Toast.makeText(this, "Canceled.", Toast.LENGTH_SHORT).show();
break;
}
}
}
I want my selected time to be shown in textViewAlarm in HomeActivity.
You can get the time from the time picker by adding a
timePicker.setOnTimeChangedListener( new TimePicker.onTimeChangedListener() {
#Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
time = String.valueOf(hourOfDay).toString() + ":" + String.valueOf(minute).toString();
}
}
When the user changes the time it will assign the time to a variable and pass that argument through intent as follow
Intent intent = new Intent(Second.this, AlarmReceiver.class);
intent.putExtra("notificationId", notificationId);
intent.putExtra("time", time);
Take that passed argument from the HomeActivity and set it to the TextView as follow
textviewAlarm.setText(time.toSring());

delay in silent device

I am developing an app in which user can input times to set device in silent mode and back to normal when timer ends. Until now I can get the device in silent mode and back to normal mode but there is a delay after which silent mode is activated, delay is about of 10 or 15 seconds. I dont understand why silent mode is activated with a delay. Below is my code of start() and end() time functions.
start():
public void start()
{
Calendar cal=Calendar.getInstance();
// simpleDateFormat=new SimpleDateFormat("hh:mm a");
Date date = new Date();
//String time=simpleDateFormat.format(date);
int hour=cal.get(Calendar.HOUR);
int minute=cal.get(Calendar.MINUTE);
timePickerDialog=new TimePickerDialog(MainActivity.this, new
TimePickerDialog.OnTimeSetListener()
{
#Override
public void onTimeSet(TimePicker view, final int hourOfDay1,final int minute1) {
Time time = new Time(hourOfDay1, minute1,0);
GregorianCalendar j2=new GregorianCalendar(hourOfDay1,minute1,0);
System.out.println(j2);
//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);
start.setText(s);
//dp.getDayOfMonth();
Calendar calNow = Calendar.getInstance();
Calendar calSet = (Calendar) calNow.clone();
calSet.set(Calendar.HOUR_OF_DAY, hourOfDay1);
calSet.set(Calendar.MINUTE, minute1);
Toast.makeText(MainActivity.this,"Starting Pending intent started",Toast.LENGTH_LONG).show();
//final int _id = (int) System.currentTimeMillis();
Intent intent = new Intent(getBaseContext(), SilenceBroadCastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calNow.getTimeInMillis(), pendingIntent);
//final long sttimer=((shour)*60*60*1000)+((sminute)*60*1000);
}
},hour,minute,false);
timePickerDialog.setTitle("Set Start time");
timePickerDialog.show();
}
end()
public void end(){
Calendar cal1=Calendar.getInstance();
//simpleDateFormat1=new SimpleDateFormat("hh:mm a");
Date date1 = new Date();
//String time=simpleDateFormat1.format(date1);
int hour=cal1.get(Calendar.HOUR);
int minute=cal1.get(Calendar.MINUTE);
secondtimepickerdialog=new TimePickerDialog(MainActivity.this, new
TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, final int hourOfDay1,final int minute1) {
Time time = new Time(hourOfDay1, minute1,0);
GregorianCalendar j3=new GregorianCalendar(hourOfDay1,minute1,0);
//little h uses 12 hour format and big H uses 24 hour format
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("h:mm a");
//format takes in a Date, and Time is a sublcass of Date
String s1 = simpleDateFormat1.format(time);
end.setText(s1);
Calendar calNow1 = Calendar.getInstance();
Calendar calSet1 = (Calendar) calNow1.clone();
calSet1.set(Calendar.HOUR_OF_DAY, hourOfDay1);
calSet1.set(Calendar.MINUTE, minute1);
Toast.makeText(MainActivity.this,"End Pending intent started",Toast.LENGTH_LONG).show();
Intent intent = new Intent(getBaseContext(), UnsilenceBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_2, intent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, j3.getTimeInMillis(), pendingIntent);
//final long sttimer=((shour)*60*60*1000)+((sminute)*60*1000);
}
},hour,minute,false);
secondtimepickerdialog.setTitle("Set End time");
secondtimepickerdialog.show();
}
Solved......
In both the functions at onTimeset() I removed the final keyword and now somehow the delay is gone and device gets silent on the spot.

Cancel an AlarmManager

I´ve got a method that sets the time I want an alarm to fire.
In this method I also got a Stop button that cancels the alarm
if(alarmManager != null){
alarmManager.cancel(pi);
}
My problem is that when I set the alarm, go out of the app and in again to cancel the alarm I get a nullPointer. Im guessing it is because the PendingIntent also closes when I leave the app (get set to null).
How can I prevent this from happening, so that I can cancel the alarm?
Heres the whole method:
#SuppressWarnings("deprecation")
public void setTime(){
Calendar mcurrentTime = Calendar.getInstance();
int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
int minute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener()
{
int callCount = 0; //To track number of calls to onTimeSet()
#Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute)
{
if(callCount == 1) // On second call
{
String timeString = "";
timeString = selectedHour + ":" + selectedMinute + ":00";
Log.d("TEST", "Chosen time : "+ timeString);
setAlarm(timePicker, selectedHour, selectedMinute);
}
callCount++; // Incrementing call count.
}
}, hour, minute, true);
mTimePicker.setButton(DialogInterface.BUTTON_POSITIVE, "Set", mTimePicker);
mTimePicker.setButton(DialogInterface.BUTTON_NEGATIVE, "Stop", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(alarmManager != null){
alarmManager.cancel(pi);
}
}
});
mTimePicker.setTitle(R.string.time);
mTimePicker.show();
}
You can save the data that is used to construct your PendingIntent in a Bundle like shown here
So when you open up your app again, you will be able to reconstruct the PendingIntent and cancel the alarm if needed.
EDIT: First of all you have to override onSaveInstanceState and save the data that is used to create your PendingIntent object like shown below:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the pending intent id
savedInstanceState.putInt(PENDING_INTENT_ID, mPendingIntentId);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
After that, in your onCreate method you will check if the savedInstanceState is not null. If not null, restore the items from the savedInstanceState (Bundle) object like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Always call the superclass first
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
mPendingIntentId = savedInstanceState.getInt(PENDING_INTENT_ID);
} else {
// Probably initialize members with default values for a new instance
mPendingIntentId = YOUR_DEFAULT_INT_VALUE;
}
mPendingIntent = PendingIntent.getBroadcast(this, mPendingIntentId, YOUR_INTENT, PendindIntent.FLAG_UPDATE_CURRENT);
}
PendingIntent will be recreated every time you will enter your app, so you will be able to cancel the same alarm that has been triggered in a previous step.
EDIT 2 : Another approach in your case would be that since you have only one alarm, and it's id is always the same (which should be used for the PendingIntent's requestId), than you can simply recreate the PendingIntent whenever you want to add or cancel an alarm. A method like the one below would help you out.
private PendingIntent getPendingIntent(Context context){
return PendingIntent.getBroadcast(context, 0, new Intent(context, YourBroadcastReceiver.class), PendingIntent.FLAG_CANCEL_CURRENT);
}

How to set an alarm for a selected date and time?

I have this code from where I can set a time and date from date picker and time picker at once:
private void dialoguetime() {
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.custom_dialogue);
dialog.setCancelable(true);
dialog.setTitle("This is Dialog 1");
dialog.show();
TimePicker time_picker = (TimePicker) dialog
.findViewById(R.id.timePicker1);
hours = time_picker.getCurrentHour();
minute = time_picker.getCurrentMinute();
time_picker.setOnTimeChangedListener(new OnTimeChangedListener() {
public void onTimeChanged(TimePicker view, int hourOfDay,
int minutes) {
// TODO Auto-generated method stub
// Toast.makeText(CustomDialog.this,
// "hourOfDay = "+hourOfDay+"minute = "+minute , 1000).show();
hours = hourOfDay;
minute = minutes;
}
});
final DatePicker date_picker = (DatePicker) dialog
.findViewById(R.id.datePicker1);
Button btn = (Button) dialog.findViewById(R.id.button2);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
xDate = date_picker.getYear() + "-"+ (date_picker.getMonth() + 1) + "-"+ date_picker.getDayOfMonth() + " " + hours+ ":" + minute + ":00";
Toast.makeText(
getApplicationContext(),
xDate, Toast.LENGTH_LONG)
.show();
dialog.cancel();
}
}
);
}
From this I can get a string as a date format like this yyyy-mm-dd hh:mm:ss, now I want to give an alert (as alarm) to the user of that selected time. I have used alarm manager for this but it didn't allow me to select that date?
How can I do this?
If you look at the API for AlarmManager (http://developer.android.com/reference/android/app/AlarmManager.html) you can see that the method
set()
requires the following parameters:
public void set (int type, long triggerAtMillis, PendingIntent operation)
where
int type = One of ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC or RTC_WAKEUP.
long triggerAtMillis = time in milliseconds that the alarm should go off, using the appropriate clock (depending on the alarm type).
PendingIntent operation = Action to perform when the alarm goes off
So basicly what you should do, is to get the time between the selected date (DateFormat.parse() to parse the date-formated string to date) and the current date. Something like this:
Date now = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
Date parsedDate = format.parse(YOUR_PICKED_DATE_AS_STRING);
long alertTime = parsedDate.getTime() - now.getTime();
Intent someIntent = new Intent(getApplicationContext(), YourClass.class);
PendingIntent pending = PendingIntent.getBroadcast(getApplicationContext(), 0, someIntent, 0);
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
manager.set(AlarmManager.

Categories