how can i check a time more than one time - android

I have a class that takes a time from a user by time picker ,the time picker action should be compared with current phone time ,when current phone time is same with which user set ,the app should trigger a media player called mediaplayer like an alarm .now the problem is I cant check the timepicker time with the current phone time more than one time .
import java.util.Calendar;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TimePicker;
import android.widget.Toast;
public class Sabah2 extends Activity {
Button btn;
Intent i;
int hour,min;
static TimePicker picker;
private Handler hh;
private Runnable rr;
Calendar c = Calendar.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sabah2);
final MediaPlayer mp = MediaPlayer.create(Sabah2.this, R.raw.salam);
picker = (TimePicker) findViewById(R.id.timePicker1);
btn = (Button) findViewById(R.id.sabah_save);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
hour=picker.getCurrentHour();
min=picker.getCurrentMinute();
Toast.makeText(getApplicationContext(), "The Alarm has been
Activated At "+hour+":"+min, Toast.LENGTH_SHORT).show();
}
});
if(hour==c.get(Calendar.HOUR)&&min==c.get(Calendar.MINUTE))
{
mp.start();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.sabah2, menu);
return true;
}
}

You have to set the alarmanager for the time in the timepicker.If the time matches with current time it will trigger the alarm and play the mediaplayer .something like this
AlarmManager alarmanager=(AlarmManager) getSystemService(Context.ALARM_SERVICE);
TimePicker ti = (TimePicker) findViewById(R.id.time_alarm);
ti.setOnTimeChangedListener(new OnTimeChangedListener() {
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
// TODO Auto-generated method stub
selectedhour = hourOfDay;
selectedminute = minute;
count = 2;
}
});
now convert the selectedhour and selectedminute into millisecond and set it to alarmanager
alarmanager.set(AlarmManager.RTC_WAKEUP, time in millisec,pndingIntent) ;

You have to use a service to check for the time.In this service check your time with current time.This will be in background and thus will try to check the instance of time even when your ap is not running.

Related

How do I calculate time difference between two time pickers in android?

I am able to find out the difference between two time intervals, but when the time 1st 12:00am or 00:00 and 2nd time is any other time, I am not getting accurate difference. Instead I am getting a negative difference. Upon debugging I figured out the time is actually taking of the year 1970 January. I am unable to correct it by taking today's time and calculate the difference.
package com.cksapp.memoryin;
import androidx.appcompat.app.AppCompatActivity;
import android.app.TimePickerDialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.google.firebase.Timestamp;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreSettings;
import java.security.CodeSigner;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
//import java.util.Date;
public class HourlyCalculator extends AppCompatActivity {
EditText wage;
TextView t1, t2, t3;
ImageView i1, i2;
Button b1;
int minutestotal;
String timex, timey;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calculator_hourly);
wage = findViewById(R.id.hourlyrate);
t1 = findViewById(R.id.starttimetext);
t2 = findViewById(R.id.endtimetext);
t3 = findViewById(R.id.finaltime);
i1 = findViewById(R.id.startimage);
i2 = findViewById(R.id.endimage);
b1 = findViewById(R.id.calculatebutton);
Calendar c = Calendar.getInstance();
final int hour = c.get(Calendar.HOUR_OF_DAY);
final int mins = c.get(Calendar.MINUTE);
i1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final TimePickerDialog time = new TimePickerDialog(HourlyCalculator.this, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay1, int minute1) {
timex = hourOfDay1 + ":" + minute1;
t1.setText(timex);
Log.d("Time1", timex);
}
},hour, mins, true);
time.show();
}
});
i2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final TimePickerDialog time2 = new TimePickerDialog(HourlyCalculator.this, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
timey = hourOfDay + ":" + minute;
t2.setText(timey);
Log.d("Time1", timey);
}
},hour,mins,true);
time2.show();
}
});
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
try {
Date a = sdf.parse(timex);
Date b = sdf.parse(timey);
long difference = a.getTime() - b.getTime();
Log.d("Time", String.valueOf(difference));
/* minutestotal = (int) (difference/60000);
Log.d("Timearey", String.valueOf(minutestotal));
int totalwageinitital = Integer.parseInt(wage.getText().toString());
double totalwagepermin = totalwageinitital/60;
double finalprice = minutestotal * totalwagepermin;
t3.setText(String.valueOf(finalprice));*/
} catch (ParseException e) {
e.printStackTrace();
}
}
});
}
}
You are parsing the time using only hours and minutes, without providing the year, month and day the sdf will assume Jan 1st, 1970.
You should do this in a different way: initialize a calendar object for each date using Calendar.getInstance(), this will give you an instance with today's date, then set the hours and minutes for those 2 instances according to the hours and minutes in the picker and check the difference between their timeInMilliseconds.
Calendar time = Calendar.getInstance();
time.set(Calendar.HOUR_OF_DAY, hour);
time.set(Calendar.MINUTE, minute);

android datepickerfragment transfer information to main activity

I'm new in programming and android. I'm having problem with a datePickerfragment. Error when implementing DatePickerFragment.OnFragmentInteractionListener on mainActivity, it says that "Class MainActivity must either be declared abstract or implement abstract method 'returnDate(String)' in 'OnFragmentInteractionListener'."
I used the datePicker as shown in http://developer.android.com/guide/topics/ui/controls/pickers.html.
The datePicker works but I want to transfer the value selected to mainActivity and I took some tips in this other post: How to transfer the formatted date string from my DatePickerFragment?.
I don't really know what I'm missing. I would also like to know if its possible to transfer de Date value instead of a String value. I wanted to manipulate the Date in mainActivity. Hope someone can help me. Here is my code:
package com.example.android.datepickertest;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends FragmentActivity
implements DatePickerFragment.OnFragmentInteractionListener
{
private TextView dataSelecionada;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataSelecionada = (TextView)findViewById(R.id.data_selecionada);
}
public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
#Override
public void setTextDate (int year, int month, int day) {
TextView displayDataSelecionada = (TextView) findViewById(R.id.data_selecionada);
dataSelecionada.setText(day + "/" + month +"/" + year);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
and datePickerFragment:n
package com.example.android.datepickertest;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link DatePickerFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link DatePickerFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
OnFragmentInteractionListener listener;
public interface OnFragmentInteractionListener {
public void returnDate(String date);
};
#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);
listener=(OnFragmentInteractionListener)getActivity();
// 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
Calendar c= Calendar.getInstance();
c.set(year,month,day);
SimpleDateFormat date = new SimpleDateFormat();
String dateSet = date.format(c.getTime());
if (listener !=null){
listener.returnDate(dateSet);
}
}
}
The error has the answer, when you implement an interface, you should implement all the methods in the interface.
In your case there is no method returndate in your mainactivity.
1.Create the method returnDate or if you use Android studio, just go to file MainActivity and put your cursor over 'public class MainActivity' then press Alt+Enter, the method ll be automatically created, and you ll the date in your mainactivity through this method.
If you need date instead of string change the argument of returndate method to Date, and remove that Simpledateformat instead use
new Date (c.getTime())

Runtime Exception and Null Pointer exception while trying to create countdown timer in android

I'm trying to design a countdown timer for my activity. Whenever I try to run the below code, there is an error coming out. I will show the logcat for more error details.
02-16 18:12:07.535: E/AndroidRuntime(550): FATAL EXCEPTION: main
02-16 18:12:07.535: E/AndroidRuntime(550): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.onlineauction/com.example.onlineauction.Placed_Product_Details}: java.lang.NullPointerException
02-16 18:12:07.535: E/AndroidRuntime(550): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1569)
There are several more errors in the logcat, but due to space limitation, I'm skipping it. I don't know what is the possible error for this countdown timer. I need to start the countdown timer as soon as this activity is launched. Can some one please help me out.
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
#SuppressLint("SimpleDateFormat")
public class Placed_Product_Details extends Activity {
TextView timerv=(TextView)findViewById(R.id.timer);
public timer tim;
Intent i=getIntent();
final String productbiddate=i.getStringExtra("productbiddate");
final String productplaceddate=i.getStringExtra("productplaceddate");
TextView pbid=(TextView)findViewById(R.id.pbid);
TextView pplaced=(TextView)findViewById(R.id.pplaced);
SimpleDateFormat sdf=new SimpleDateFormat("dd-MMM-yy hh:mm:ss aa");
#SuppressLint("SimpleDateFormat")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_placed__product__details);
try
{
// Converting the two string dates into date time format and comparing the dates
Date dt1=sdf.parse(productbiddate);
Date dt2=sdf.parse(productplaceddate);
int val=dt1.compareTo(dt2);
if(val>0)
{
long diff=Math.abs(dt1.getTime()-dt2.getTime());
long seconds=(TimeUnit.MILLISECONDS.toSeconds(diff))%60;
long minutes=(TimeUnit.MILLISECONDS.toMinutes(diff))%60;
long hours=(TimeUnit.MILLISECONDS.toHours(diff))%24;
long days = TimeUnit.MILLISECONDS.toDays(diff);
//here I'm trying to start my timer in my activity.
tim=new timer(diff, 1000);
tim.start();
}
pbid.setText("Bid Ends On: "+productbiddate);
pplaced.setText("Product Was Placed For Bidding On: "+productplaceddate);
}
catch(Exception e)
{
Log.d("Exception:",e.toString());
}
}
public class timer extends CountDownTimer
{
public timer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
// TODO Auto-generated constructor stub
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
}
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
long seconds=(TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished))%60;
long minutes=(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))%60;
long hours=(TimeUnit.MILLISECONDS.toHours(millisUntilFinished))%24;
long days = TimeUnit.MILLISECONDS.toDays(millisUntilFinished);
timerv.setText("Time Remaining: "+days+" days "+hours+" hours "+hours+" minutes "+minutes+" seconds "+seconds);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.placed__product__details, menu);
return true;
}
}
Move the below inside onCreate after setContentView
TextView pbid=(TextView)findViewById(R.id.pbid);
TextView pplaced=(TextView)findViewById(R.id.pplaced);
TextView timerv=(TextView)findViewById(R.id.timer);
Intent i=getIntent();
final String productbiddate=i.getStringExtra("productbiddate");
final String productplaceddate=i.getStringExtra("productplaceddate");
findViewById looks for a view with the id mentioned in the current inflated layout. So you need to set the content of the activity first to the layout and then initialize views.
You need to wait till activity is created to use getIntent().

Alarm Clock app error

public void pickTimeHandler(View target) {
Toast.makeText(Alarms1.this, "in PickTimehandler", Toast.LENGTH_LONG).show();
showDialog(0);
where you see Alarm1.this is always an error in all of my code that says
No enclosing instance of the type Alarms1 is accessible in scope
You would write Alarms1.this if that is the name of the enclosing class
What is the name of the class this is in? Use that name.
Example:
public class Alarms1 {
public void pickTimeHandler(View target) {
//code below would work, you could also just write "this" instead of "Alarms1.this"
Toast.makeText(Alarms1.this, "in PickTimehandler", Toast.LENGTH_LONG).show();
showDialog(0);
}
}
You only need to qualify the this value with the name of the class if it is made from an inner class.
Here is an example of when you need to qualify what "this" parameter you are using:
public class Alarms1 {
public void onCreate(Bundle state) {
Button button = (Button) findViewById(R.id.set_alarm);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(Alarms1.this, "Button clicked", Toast.LENGTH_LONG).show();
}
});
}
}
The difference is that in the above code in the second example you are creating an anonymous inner class when you put
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
And from within that code if you wrote this the java compiler/runtime would think you were referring to the instance of the inner class (as opposed to the Alarms1).
--- UPDATE ---
Given the code you sent me I came up with this:
package com.example;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TimePicker;
import android.widget.Toast;
public class AlarmActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void pickTimeHandler(View target) {
Toast.makeText(this, "in PickTimehandler",
Toast.LENGTH_LONG).show();
showDialog(0);
}
#Override
protected Dialog onCreateDialog(int id) {
Toast.makeText(this,
"- onCreateDialog(ID_TIMEPICKER) -",
Toast.LENGTH_LONG).show();
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
OnTimeSetListener theTimeSetListener = null;
return new TimePickerDialog(this,
theTimeSetListener,
hour, minute, false);
}
private TimePickerDialog.OnTimeSetListener theTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hour, int minute) {
String time = "User picked Hour: " + String.valueOf(hour) + "\n"
+ "Minute: " + String.valueOf(minute);
Toast.makeText(AlarmActivity.this, time, Toast.LENGTH_LONG).show();
int theHour = hour;
int theMinute = minute;
Intent alarmIntent = new Intent();
alarmIntent.putExtra("nel.example.alarms1", "My message");
Object pendingAlarmIntent = PendingIntent.getService(AlarmActivity.this, 0,
alarmIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar AlarmCal = Calendar.getInstance();
AlarmCal.setTimeInMillis(System.currentTimeMillis());
AlarmCal.set(Calendar.HOUR_OF_DAY, theHour); // set user selection
AlarmCal.set(Calendar.MINUTE, theMinute); // set user selection
AlarmCal.set(Calendar.SECOND, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
AlarmCal.getTimeInMillis(), AlarmManager.INTERVAL_FIFTEEN_MINUTES,
(PendingIntent) pendingAlarmIntent);
}
};
}
The changes I made are:
Renamed class form myMenu to AlarmActivity (The class has nothing to do with a menu, it is an alarm isn't it). Also classs names should start with a capital letter.
PendingIntent.getService need a context. This is EXACTLY the problem I described in my original solution. An Activity is a subclass of Context, which means you can pass an actvity to PendingIntent.getService in the first parameter. However when you created that inner class:
private TimePickerDialog.OnTimeSetListener theTimeSetListener = new TimePickerDialog.OnTimeSetListener(){
The code within that no longer was an Activity, it was a TimePickerDialog.OnTimeSetListener. You need to pass myMenu.this as the first parameter (or in my case, since I renamed your class to AlarmActivity, you would pass AlarmActivity.this). The same thing goes with Toasts that you create within an inner class.
I highly suggest you stop what you are doing and go learn java before continuing android development. Read a book, follow online tutorials, etc. But if you just dive into android without understanding java you will have a load of problems.

Time Picker widget - "id cannot be resolved or is not a field"

I'm getting the error for the following lines:
mTimeDisplay = (TextView) findViewById(R.id.timeDisplay);
mPickTime = (Button) findViewById(R.id.pickTime);
Although at this stage I'm merely copy-pasting stuff from the Tutorial, just to get a feel for it.. So where am I going wrong guys?
This is the .java file as a whole:
package com.example.hellotimepicker;
import java.util.Calendar;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class HelloTimePicker extends Activity {
/** Called when the activity is first created. */
private TextView mTimeDisplay;
private Button mPickTime;
private int mHour;
private int mMinute;
static final int TIME_DIALOG_ID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// capture our View elements
mTimeDisplay = (TextView) findViewById(R.id.timeDisplay);
mPickTime = (Button) findViewById(R.id.pickTime);
// add a click listener to the button
mPickTime.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(TIME_DIALOG_ID);
}
});
// get the current time
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
// display the current date
updateDisplay();
}
// updates the time we display in the TextView
private void updateDisplay() {
mTimeDisplay.setText(
new StringBuilder()
.append(pad(mHour)).append(":")
.append(pad(mMinute)));
}
private static String pad(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
}
sounds like you missed to copy the layout (xml code) from the tutorial
Just want to share my experience with the original tutorial version because this might be useful. Earlier I used:
import android.R;
But the main cannot be resolved at the line:
setContentView(R.layout.main);
So I changed the "import android.R;" to:
import com.example.hellodatepicker.R; //to match with the package name
and found out it is running fine.

Categories

Resources