Null values in service class android - java

I am getting null values in service class :-
if (intent != null && intent.getAction() != null) {
matchName = intent.getStringExtra("match");
matchDate = intent.getStringExtra("time");
Log.d(" Service Match ", intent.getExtras().toString());
}
//onCreate Code
#Override
protected void onCreate(Bundle savedInstanceState) {
Button match1 = (Button) findViewById(R.id.match1);
match1.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Calendar endTime = Calendar.getInstance();
SimpleDateFormat inputFormat = new SimpleDateFormat(
"yyyy-MM-dd hh:mm:ss a");
inputFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat nativeFormat = new SimpleDateFormat(
"yyyy-MM-dd hh:mm:ss a");
nativeFormat.setTimeZone(TimeZone.getDefault());
SimpleDateFormat nativeFormat1 = new SimpleDateFormat(
"yyyy-MM-dd hh:mm a");
String inpt = matchTimeInGMT(v); // "2014-03-22 8:45:00 PM";
Button matchButton = (Button) v;
String matchName = "ABC vs DEF";
try {
inptdate = inputFormat.parse(inpt);
date2 = nativeFormat.format(inptdate);
endTime.setTime(nativeFormat.parse(date2));
// endTime.add(Calendar.HOUR_OF_DAY, 3);
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime", endTime.getTimeInMillis());
intent.putExtra("allDay", false);
intent.putExtra("rrule", "FREQ=YEARLY;COUNT=1");
intent.putExtra("endTime", endTime.getTimeInMillis());
intent.putExtra("title", matchName);
startActivity(intent);
Calendar cal = Calendar.getInstance();
cal.setTime(endTime.getTime());
Intent svc = new Intent(this,MyAlarmService.class);
svc.setAction("matchTime");
svc.putExtra("match", matchName.toString());
svc.putExtra("time", nativeFormat1.format(cal.getTime()).toString());
startService(svc);
PendingIntent alarmIntent;
Intent myIntent1 = new Intent(FIXTURE.this, MyReceiver.class);
alarmIntent = PendingIntent.getBroadcast(FIXTURE.this, 0,
myIntent1, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, endTime.getTimeInMillis(),
alarmIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
Log output -Bundle[{time=2014-03-25 12:20 AM, match=ABC Vs DEF}]
I am getting values for match and time but not getting assigned to matchName and matchDate variables. Please help.

Related

I keep getting "Event not found" when I want to open calendar by EventId

this is my code for adding an event to my calendar(MyFragment):
int id = 20002000;
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(Intent.ACTION_INSERT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra(CalendarContract.Events._ID, id);
intent.putExtra(CalendarContract.Calendars.ACCOUNT_NAME,"xxxx#hotmail.com");
intent.putExtra(CalendarContract.Calendars.ACCOUNT_TYPE,CalendarContract.ACCOUNT_TYPE_LOCAL);
intent.putExtra(CalendarContract.Events.TITLE, myTitle);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
Date date = new Date();
GregorianCalendar calDate = new GregorianCalendar();
try {
date = sdf.parse(stringtodate);
calDate.setTime(date);
} catch (ParseException e) {
e.printStackTrace();
}
if (date.before(new Date())) {
intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME,new Date().getTime());
intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, new Date().getTime());
}else{
intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, calDate.getTimeInMillis());
intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, calDate.getTimeInMillis());
}
intent.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, true);
startActivity(intent);
this is my method for retrieving an event by the given id(MainActivity)
Uri uri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, 20002000);
Intent intent = new Intent(Intent.ACTION_VIEW).setData(uri);
startActivity(intent);

Getting all notifications at same time

I have set notifications using alarm manager for events. If I set multiple notifications at different times then last all notifications also arise at last notification with the last one.
Also I want to cancel the particular notification if the switch is off. I have given the same intent to cancel the notification. But I think all the notifications got cancelled.
Also I have created time tables and events are created using the time table's id. Now if I delete one time table I want to delete all the notifications set to the events that belongs to the deleted time table.
setting alarm:
public void setNotificationTime(Calendar c)
{
Date dateFrom = new Date();
df = new SimpleDateFormat("E MMM dd HH:mm:ss zzzz yyyy");
try {
dateFrom = df.parse(startTime);
}
catch (ParseException ex) {
}
dateFrom.getTime();
c.setTime(dateFrom);
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
if(notificationTime !=null && !notificationTime.isEmpty()) {
if (notificationTime.equals("10 Minutes Before")) {
FLAG = 1;
c.set(Calendar.HOUR_OF_DAY, hour);
c.set(Calendar.MINUTE, minute - 10);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
c.set(Calendar.DATE, day);
// c.set(Calendar.DAY_OF_WEEK,);
SetDay(c);
notification = c.getTime();
notificationTime = df.format(notification);
// setAlarm(c, FLAG);
Intent intent = new Intent(getBaseContext(), NotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_DAY * 7, pendingIntent);
Toast.makeText(getApplicationContext(), notificationTime, Toast.LENGTH_SHORT).show();
} else if (notificationTime.equals("30 Minutes Before")) {
FLAG = 2;
c.set(Calendar.HOUR_OF_DAY, hour);
c.set(Calendar.MINUTE, minute - 30);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
c.set(Calendar.DATE, day);
// c.set(Calendar.DAY_OF_WEEK,);
SetDay(c);
notification = c.getTime();
notificationTime = df.format(notification);
Intent intent = new Intent(getBaseContext(), NotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_DAY * 7, pendingIntent);
Toast.makeText(getApplicationContext(), notificationTime, Toast.LENGTH_SHORT).show();
// setAlarm(c,FLAG);
}
Notification Receiver
public class NotificationReceiver extends BroadcastReceiver {
public static int MY_NOTIFICATION_ID = 0;
NotificationManager notificationManager;
Notification myNotification;
EventTableHelper db;
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Time is set", Toast.LENGTH_LONG).show();
db = new EventTableHelper(context);
List<EventData> testSavings = db.getAllEvents();
for (EventData ts : testSavings) {
String log = "from date:" + ts.getFromDate()
+ " ,to date: " + ts.getToDate()
+ " ,location: " + ts.getLocation()
+ " ,title " + ts.getTitle();
Calendar c = Calendar.getInstance();
Date date = new Date();
Date date1 = new Date();
Log.d("Result: ", log);
SimpleDateFormat df = new SimpleDateFormat("E MMM dd hh:mm:ss zzzz yyyy");
SimpleDateFormat df2 = new SimpleDateFormat("hh:mm a");
try {
date = df.parse(ts.getFromDate());
date1 = df.parse(ts.getToDate());
} catch (ParseException ex) {
}
String timeFrom = df2.format(date);
// String startTime = String.valueOf(timeFrom);
String timeTo = df2.format(date1);
// String endTime = String.valueOf(timeTo);
String location = ts.getLocation();
String title = ts.getTitle();
Intent myIntent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
context,
0,
myIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
if(location.equals(""))
{
String msg = "From : " + timeFrom + "\nTo : " + timeTo;
myNotification = new NotificationCompat.Builder(context)
.setContentTitle("Event : " + title)
.setContentText(msg)
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setSmallIcon(R.drawable.eventicon)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setDefaults(Notification.DEFAULT_SOUND)
.build();
}
else
{
String msg = "From : " + timeFrom + "\nTo : " + timeTo + "\nAt : " + location;
myNotification = new NotificationCompat.Builder(context)
.setContentTitle("Event : " + title)
.setContentText(msg)
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setSmallIcon(R.drawable.eventicon)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setDefaults(Notification.DEFAULT_SOUND)
.build();
}
Log.i("Notify", "Notification");
notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(MY_NOTIFICATION_ID, myNotification);
myNotification.flags=Notification.FLAG_AUTO_CANCEL;
Intent i = new Intent();
i.putExtra("notificationId",MY_NOTIFICATION_ID);
MY_NOTIFICATION_ID ++;
}
}
}
You reset MY_NOTIFICATION_ID every time the broadcastReceiver is called so all the notifications have the same id, which is 0.
What I did to avoid it was to use:
Random rand = new Random();
int id = rand.nextInt(1000000) + 1;
so that every notification will definitely get a different id number (chance of 1 in a million it will repeat itself).

Cancelling multiple alarms?

I have created an events. I have given option for notification before 10 minutes, 30 minutes and before every hour till 12 hours before. I have to set notification for all these intervals.
Now I want to cancel the particular notification if the switch is off. I have given the same intent to cancel the notification. But I think all the notifications got cancelled.
Also I have created time tables and events are created using the time table's id. Now if I delete one time table I want to delete all the notifications set to the events that belongs to the deleted time table.
How can I do this?
Set notification time function:
public void setNotificationTime(Calendar c)
{
Date dateFrom = new Date();
df = new SimpleDateFormat("E MMM dd HH:mm:ss zzzz yyyy");
try {
dateFrom = df.parse(startTime);
}
catch (ParseException ex) {
}
dateFrom.getTime();
c.setTime(dateFrom);
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
if(notificationTime !=null && !notificationTime.isEmpty()) {
if (notificationTime.equals("10 Minutes Before")) {
c.set(Calendar.HOUR_OF_DAY, hour);
c.set(Calendar.MINUTE, minute - 10);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
c.set(Calendar.DATE, day);
// c.set(Calendar.DAY_OF_WEEK,);
SetDay(c);
notification = c.getTime();
notificationTime = df.format(notification);
setAlarm(c);
Toast.makeText(getApplicationContext(), notificationTime, Toast.LENGTH_SHORT).show();
} else if (notificationTime.equals("30 Minutes Before")) {
c.set(Calendar.HOUR_OF_DAY, hour);
c.set(Calendar.MINUTE, minute - 30);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
c.set(Calendar.DATE, day);
// c.set(Calendar.DAY_OF_WEEK,);
SetDay(c);
notification = c.getTime();
notificationTime = df.format(notification);
Toast.makeText(getApplicationContext(), notificationTime, Toast.LENGTH_SHORT).show();
setAlarm(c);
} else if (notificationTime.equals("1 Hour Before")) {
c.set(Calendar.HOUR_OF_DAY, hour - 1);
c.set(Calendar.MINUTE, minute);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
c.set(Calendar.DATE, day);
// c.set(Calendar.DAY_OF_WEEK,);
SetDay(c);
notification = c.getTime();
notificationTime = df.format(notification);
Toast.makeText(getApplicationContext(), notificationTime, Toast.LENGTH_SHORT).show();
setAlarm(c);
}
Set Alarm function:
#SuppressLint("NewApi")
private void setAlarm(Calendar targetmCalen) {
intent = new Intent(getBaseContext(), NotificationReceiver.class);
pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_DAY * 7, pendingIntent);
}
Notification cancel on switch off:
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
intent = new Intent(getApplicationContext(), NotificationReceiver.class);
pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), RQS_1, intent, 0);
alarmManager.cancel(pendingIntent);
Notification receiver:
public class NotificationReceiver extends BroadcastReceiver {
public static int MY_NOTIFICATION_ID = 0;
NotificationManager notificationManager;
Notification myNotification;
EventTableHelper db;
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Time is set", Toast.LENGTH_LONG).show();
db = new EventTableHelper(context);
List<EventData> testSavings = db.getAllEvents();
for (EventData ts : testSavings) {
String log = "from date:" + ts.getFromDate()
+ " ,to date: " + ts.getToDate()
+ " ,location: " + ts.getLocation()
+ " ,title " + ts.getTitle();
Calendar c = Calendar.getInstance();
Date date = new Date();
Date date1 = new Date();
Log.d("Result: ", log);
SimpleDateFormat df = new SimpleDateFormat("E MMM dd hh:mm:ss zzzz yyyy");
SimpleDateFormat df2 = new SimpleDateFormat("hh:mm a");
try {
date = df.parse(ts.getFromDate());
date1 = df.parse(ts.getToDate());
} catch (ParseException ex) {
}
String timeFrom = df2.format(date);
// String startTime = String.valueOf(timeFrom);
String timeTo = df2.format(date1);
// String endTime = String.valueOf(timeTo);
String location = ts.getLocation();
String title = ts.getTitle();
Intent myIntent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
context,
0,
myIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
if(location.equals(""))
{
String msg = "From : " + timeFrom + "\nTo : " + timeTo;
myNotification = new NotificationCompat.Builder(context)
.setContentTitle("Event : " + title)
.setContentText(msg)
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setSmallIcon(R.drawable.eventicon)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setDefaults(Notification.DEFAULT_SOUND)
.build();
}
else
{
String msg = "From : " + timeFrom + "\nTo : " + timeTo + "\nAt : " + location;
myNotification = new NotificationCompat.Builder(context)
.setContentTitle("Event : " + title)
.setContentText(msg)
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setSmallIcon(R.drawable.eventicon)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setDefaults(Notification.DEFAULT_SOUND)
.build();
}
Log.i("Notify", "Notification");
notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(MY_NOTIFICATION_ID, myNotification);
myNotification.flags=Notification.FLAG_AUTO_CANCEL;
Intent i = new Intent();
i.putExtra("notificationId",MY_NOTIFICATION_ID);
MY_NOTIFICATION_ID ++;
}
}
}
Which changes should I do to achieve the desired result?
you need to create different pending intents and then use particular pending intent to cancel specific alarm .Create your pending intent as usual but add the different flag for different alarm.
pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, FLAG);//Set different value of Flag at the time creating alarm
So to make it generic just add one more params in your
setAlarm(Calendar targetmCalen,int flag)

Why dose notification raise while setting time of notification?

I have used time picker to set the time of notification by user. I have used alarm manager and notification builder.
I have called the setAlarm method on clickListener of a button to save data. So when this setAlarm method gets called Notification raises at the same time as well as it raises at the time user have set.
I don't want it to be raised when I save the data.
Can anyone tell why this is happening?
setAlarm method
#SuppressLint("NewApi")
private void setAlarm(Calendar targetmCalen) {
AlarmManager alarmMgr;
PendingIntent alarmIntent;
alarmMgr = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), NotificationReceiver.class);
alarmIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
Toast.makeText(getBaseContext(),
"call alarmManager.setExact()",
Toast.LENGTH_LONG).show();
intent.putExtra("title",eventTitle);
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, targetmCalen.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, alarmIntent);
ComponentName receiver = new ComponentName(getApplicationContext(),NotificationReceiver.class);
PackageManager pm = getApplicationContext().getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
}
NotificationReceiver
public class NotificationReceiver extends BroadcastReceiver {
private static final int MY_NOTIFICATION_ID = 0;
NotificationManager notificationManager;
Notification myNotification;
EventTableHelper db;
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Time is set", Toast.LENGTH_LONG).show();
db = new EventTableHelper(context);
List<EventData> testSavings = db.getAllEvents();
for (EventData ts : testSavings) {
String log = "from date:" + ts.getFromDate()
+ " ,to date: " + ts.getToDate()
+ " ,location: " + ts.getLocation()
+ " ,title " + ts.getTitle();
Date date = new Date();
Date date1 = new Date();
Log.d("Result: ", log);
SimpleDateFormat df = new SimpleDateFormat("E MMM dd HH:mm:ss zzzz yyyy");
SimpleDateFormat df2 = new SimpleDateFormat("HH:mm a");
try {
date = df.parse(ts.getFromDate());
date1 = df.parse(ts.getToDate());
} catch (ParseException ex) {
}
String timeFrom = df2.format(date);
String startTime = String.valueOf(timeFrom);
String timeTo = df2.format(date1);
String endTime = String.valueOf(timeTo);
String location = ts.getLocation();
String title = ts.getTitle();
Intent myIntent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
context,
0,
myIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
if(location.equals(""))
{
String msg = "From : " + startTime + "\nTo : " + endTime;
myNotification = new NotificationCompat.Builder(context)
.setContentTitle("Event : " + title)
.setContentText(msg)
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setSmallIcon(R.drawable.eventicon)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setDefaults(Notification.DEFAULT_SOUND)
.build();
}
else
{
String msg = "From : " + startTime + "\nTo : " + endTime + "\nAt : " + location;
myNotification = new NotificationCompat.Builder(context)
.setContentTitle("Event : " + title)
.setContentText(msg)
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setSmallIcon(R.drawable.eventicon)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setDefaults(Notification.DEFAULT_SOUND)
.build();
}
Log.i("Notify", "Notification");
notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(MY_NOTIFICATION_ID, myNotification);
}
}
}
EDIT:
Calendar object Passed in setAlarm method
c.set(Calendar.HOUR_OF_DAY, hour);
c.set(Calendar.MINUTE, minute);
c.set(Calendar.SECOND,0);
c.set(Calendar.MILLISECOND,0);
c.set(Calendar.DATE, day);
c.set(Calendar.DAY_OF_WEEK,2);
notification = c.getTime();
notificationTime = df.format(notification);
Toast.makeText(getApplicationContext(),notificationTime,Toast.LENGTH_SHORT).show();
Thank you..

myDate cannot be resolved to a variable

I'm getting an error on the line:
cal.setTime(myDate);
stating "myDate cannot be resolved to a variable" however when I attempt to move the line it references:
Date myDate = new Date(prefs.getLong("time", 0));
above it - I get a new error stating: "prefs cannot be resolved"
...any suggestions?
SOURCE:
public class WifiMonitor extends Activity {
Button sendButton;
EditText msgTextField;
private PendingIntent pendingIntent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView infoView = (TextView) findViewById(R.id.traffic_info);
// get traffic info
double totalBytes = (double) TrafficStats.getTotalRxBytes()
+ TrafficStats.getTotalTxBytes();
double mobileBytes = TrafficStats.getMobileRxBytes()
+ TrafficStats.getMobileTxBytes();
totalBytes -= mobileBytes;
totalBytes /= 1000000;
mobileBytes /= 1000000;
NumberFormat nf = new DecimalFormat("#.##");
String totalStr = nf.format(totalBytes);
String mobileStr = nf.format(mobileBytes);
String info = String.format(
"Wifi Data Usage: %s MB\tMobile Data Usage: %s MB", totalStr,
mobileStr);
infoView.setText(info);
// send traffic info via sms
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("7862611848", null, info, null, null);
String alarm = Context.ALARM_SERVICE;
// get the current date
Date date = new Date(System.currentTimeMillis());
// convert the date to milliseconds
long millis = date.getTime();
// save the date to shared preferences
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
// SharedPreferences prefs = millis;
// SharedPreferences.Editor editor = PreferenceManager
// .getDefaultSharedPreferences(getApplicationContext());
editor.putLong("time", date.getTime());
editor.commit();
// get the saved date
Date myDate = new Date(prefs.getLong("time", 0));
}
// set the alarm to expire 30 days from the date stored in sharePreferences
public void invokeAlarm(long invokeTime, long rowId) {
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent i = new Intent(this, Alarm.class);
i.putExtra("rowId", String.valueOf(rowId));
am.set(AlarmManager.RTC_WAKEUP, invokeTime, PendingIntent.getService(
this, (int) System.currentTimeMillis(), i, 0));
Calendar cal = Calendar.getInstance();
cal.setTime(myDate);
cal.add(Calendar.DATE, 30);
invokeAlarm(cal.getTimeInMillis(), rowId);
}
}
You have to declare Date myDate as a member of the class.
private Date myDate;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**/
myDate = new Date(prefs.getLong("time", 0));
}
public void invokeAlarm(long invokeTime, long rowId) {
/**/
Calendar cal = Calendar.getInstance();
if(myDate != null)
cal.setTime(myDate);
cal.add(Calendar.DATE, 30);
invokeAlarm(cal.getTimeInMillis(), rowId);
}
Or if you're getting your date directly from the sharedPrefs :
public void invokeAlarm(long invokeTime, long rowId) {
/**/
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(prefs.getLong("time", 0));
cal.add(Calendar.DATE, 30);
invokeAlarm(cal.getTimeInMillis(), rowId);
}
You have myDate declared in one function (local scope to function) and are trying to use it in another function (different scope).
To be able to do that, without major changes, declare myDate at a class level, assign it in one function, use it in the other. Be sure to change the line:
Date myDate = new Date(prefs.getLong("time", 0));
to:
myDate = new Date(prefs.getLong("time", 0));
when you do so.

Categories

Resources