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.
Related
How to get duration between selected time (using graphical date and time picker) and date and time now in seconds?
Both methods getSelectedDate() and getSelectedTime() look fine, selected date and time is fine. But there is something wrong with the method getCountDuration(). The value is incorrect. And I can't find an error.
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
int YEAR = 0, DATE = 0, MONTH = 0, HOUR = 0, MINUTE = 0;
Button dateButton;
TextView dateTextView, timeTextView, textViewDateAndTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dateButton = findViewById(R.id.dateButton);
dateTextView = findViewById(R.id.dateTextView);
timeTextView = findViewById(R.id.timeTextView);
textViewDateAndTime = findViewById(R.id.textViewDateTimeDuration);
dateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getSelectData();
getSelectTime();
getCountDuration();
}
});
}
public LocalDate getSelectData() {
final Calendar calendarDate = Calendar.getInstance();
YEAR = calendarDate.get(Calendar.YEAR);
MONTH = calendarDate.get(Calendar.MONTH);
DATE = calendarDate.get(Calendar.DATE);
DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int date) {
Calendar calendar1 = Calendar.getInstance();
calendar1.set(Calendar.YEAR, year);
calendar1.set(Calendar.MONTH, month);
calendar1.set(Calendar.DATE, date);
String dateText = DateFormat.format("dd.MM.yyyy", calendar1).toString();
dateTextView.setText(dateText);
}
}, YEAR, MONTH, DATE);
datePickerDialog.show();
return null;
}
public LocalTime getSelectTime() {
Calendar calendar = Calendar.getInstance();
final LocalDateTime nowIs = LocalDateTime.now();
Date currentDate = new Date();
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");//("dd.MM.yyyy HH:mm"
final LocalDateTime dateTime = currentDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
HOUR = calendar.get(Calendar.HOUR);
MINUTE = calendar.get(Calendar.MINUTE);
boolean is24HourFormat = DateFormat.is24HourFormat(this);
final TimePickerDialog timePickerDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int hour, int minute) {
Log.i(TAG, "onTimeSet: " + hour + minute);
Calendar calendar1 = Calendar.getInstance();
calendar1.set(Calendar.HOUR, hour);
calendar1.set(Calendar.MINUTE, minute);
String dateText = DateFormat.format("hh:mm", calendar1).toString();
timeTextView.setText(dateText);
String dateNowText = formatter.format(dateTime).toString();
}
}, HOUR, MINUTE, is24HourFormat);
timePickerDialog.show();
return null;
}
public void getCountDuration() {
final Calendar setDate = Calendar.getInstance();
setDate.set(YEAR, MONTH, DATE, HOUR, MINUTE, 0);
long subs = Calendar.getInstance().getTimeInMillis() - setDate.getTimeInMillis();
textViewDateAndTime.setText(subs + " duration in milliseconds");
}
}
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).
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)
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.
I had already tried the first two suggestions below, but I tried again and sincerely thanks for the help! The result is the same though. I´ll just edit the post to add more code info.
Hello there! I´m experimenting with a simple ToDo application and managed to change almost everything I wanted besides the date formatted that´s displayed once the user saves the task.
The task itself is added via the AddToDoActivity class which has the following resumed code:
public class AddToDoActivity extends Activity {
// 7 days in milliseconds - 7 * 24 * 60 * 60 * 1000
private static final int SEVEN_DAYS = 604800000;
private static final String TAG = "Lab-UserInterface";
private static String timeString;
private static String dateString;
private static TextView dateView;
private static TextView timeView;
private Date mDate;
private RadioGroup mPriorityRadioGroup;
private RadioGroup mStatusRadioGroup;
private EditText mTitleText;
private RadioButton mDefaultStatusButton;
private RadioButton mDefaultPriorityButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_todo);
mTitleText = (EditText) findViewById(R.id.title);
mDefaultStatusButton = (RadioButton) findViewById(R.id.statusNotDone);
mDefaultPriorityButton = (RadioButton) findViewById(R.id.medPriority);
mPriorityRadioGroup = (RadioGroup) findViewById(R.id.priorityGroup);
mStatusRadioGroup = (RadioGroup) findViewById(R.id.statusGroup);
dateView = (TextView) findViewById(R.id.date);
timeView = (TextView) findViewById(R.id.time);
// Set the default date and time
setDefaultDateTime();
// OnClickListener for the Date button, calls showDatePickerDialog() to show
// the Date dialog
final Button datePickerButton = (Button) findViewById(R.id.date_picker_button);
datePickerButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDatePickerDialog();
}
});
// OnClickListener for the Time button, calls showTimePickerDialog() to show
// the Time Dialog
final Button timePickerButton = (Button) findViewById(R.id.time_picker_button);
timePickerButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showTimePickerDialog();
}
});
// OnClickListener for the Cancel Button,
final Button cancelButton = (Button) findViewById(R.id.cancelButton);
cancelButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
log("Entered cancelButton.OnClickListener.onClick()");
finish();
}
});
//OnClickListener for the Reset Button
final Button resetButton = (Button) findViewById(R.id.resetButton);
resetButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
log("Entered resetButton.OnClickListener.onClick()");
setDefaultDateTime();
mTitleText.setText("");
mDefaultStatusButton.setChecked(true);
mDefaultPriorityButton.setChecked(true);
}
});
// OnClickListener for the Submit Button
// Implement onClick().
final Button submitButton = (Button) findViewById(R.id.submitButton);
submitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
log("Entered submitButton.OnClickListener.onClick()");
// Gather ToDoItem data
Priority priority = getPriority();
Status status = getStatus();
String titleString = mTitleText.getText().toString();
// Date
String fullDate = dateString + " " + timeString;
// Package ToDoItem data into an Intent
Intent data = new Intent();
ToDoItem.packageIntent(data, titleString, priority, status, fullDate);
setResult(Activity.RESULT_OK, data);
finish();
}
});
}
// Do not modify below here
// Use this method to set the default date and time
private void setDefaultDateTime() {
// Default is current time + 7 days
mDate = new Date();
mDate = new Date(mDate.getTime() + SEVEN_DAYS);
Calendar c = Calendar.getInstance();
c.setTime(mDate);
setDateString(c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.MONTH),
c.get(Calendar.YEAR));
dateView.setText(dateString);
setTimeString(c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE),
c.get(Calendar.MILLISECOND));
timeView.setText(timeString);
}
private static void setDateString(int dayOfMonth, int monthOfYear, int year) {
// Increment monthOfYear for Calendar/Date -> Time Format setting
monthOfYear++;
String mon = "" + monthOfYear;
String day = "" + dayOfMonth;
if (monthOfYear < 10)
mon = "0" + monthOfYear;
if (dayOfMonth < 10)
day = "0" + dayOfMonth;
dateString = year + "-" + mon + "-" + day;
}
private static void setTimeString(int hourOfDay, int minute, int mili) {
String hour = "" + hourOfDay;
String min = "" + minute;
if (hourOfDay < 10)
hour = "0" + hourOfDay;
if (minute < 10)
min = "0" + minute;
timeString = hour + ":" + min + ":00";
}
private Priority getPriority() {
switch (mPriorityRadioGroup.getCheckedRadioButtonId()) {
case R.id.lowPriority: {
return Priority.LOW;
}
case R.id.highPriority: {
return Priority.HIGH;
}
default: {
return Priority.MED;
}
}
}
private Status getStatus() {
switch (mStatusRadioGroup.getCheckedRadioButtonId()) {
case R.id.statusDone: {
return Status.DONE;
}
default: {
return Status.NOTDONE;
}
}
}
// DialogFragment used to pick a ToDoItem deadline date
public static 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 day = c.get(Calendar.DAY_OF_MONTH);
int month = c.get(Calendar.MONTH);
int year = c.get(Calendar.YEAR);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
#Override
public void onDateSet(DatePicker view, int dayOfMonth, int monthOfYear,
int year) {
setDateString(dayOfMonth, monthOfYear, year);
dateView.setText(dateString);
}
}
// DialogFragment used to pick a ToDoItem deadline time
public static class TimePickerFragment extends DialogFragment implements
TimePickerDialog.OnTimeSetListener {
#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
return new TimePickerDialog(getActivity(), this, hour, minute,
true);
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
setTimeString(hourOfDay, minute, 0);
timeView.setText(timeString);
}
}
private void showDatePickerDialog() {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
}
private void showTimePickerDialog() {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "timePicker");
}
private void log(String msg) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i(TAG, msg);
}
}
Here´s the ToDoItem, that actually reads the info from AddToDoActivity:
public class ToDoItem {
public static final String ITEM_SEP = System.getProperty("line.separator");
public enum Priority {
LOW, MED, HIGH
};
public enum Status {
NOTDONE, DONE
};
public final static String TITLE = "title";
public final static String PRIORITY = "priority";
public final static String STATUS = "status";
public final static String DATE = "date";
public final static String FILENAME = "filename";
public final static SimpleDateFormat FORMAT = new SimpleDateFormat(
"dd/MM/yyyy HH:mm:ss", Locale.US);
private String mTitle = new String();
private Priority mPriority = Priority.LOW;
private Status mStatus = Status.NOTDONE;
private Date mDate = new Date();
ToDoItem(String title, Priority priority, Status status, Date date) {
this.mTitle = title;
this.mPriority = priority;
this.mStatus = status;
this.mDate = date;
}
// Create a new ToDoItem from data packaged in an Intent
ToDoItem(Intent intent) {
mTitle = intent.getStringExtra(ToDoItem.TITLE);
mPriority = Priority.valueOf(intent.getStringExtra(ToDoItem.PRIORITY));
mStatus = Status.valueOf(intent.getStringExtra(ToDoItem.STATUS));
try {
mDate = ToDoItem.FORMAT.parse(intent.getStringExtra(ToDoItem.DATE));
} catch (ParseException e) {
mDate = new Date();
}
}
public String getTitle() {
return mTitle;
}
public void setTitle(String title) {
mTitle = title;
}
public Priority getPriority() {
return mPriority;
}
public void setPriority(Priority priority) {
mPriority = priority;
}
public Status getStatus() {
return mStatus;
}
public void setStatus(Status status) {
mStatus = status;
}
public Date getDate() {
return mDate;
}
public void setDate(Date date) {
mDate = date;
}
// Take a set of String data values and
// package them for transport in an Intent
public static void packageIntent(Intent intent, String title,
Priority priority, Status status, String date) {
intent.putExtra(ToDoItem.TITLE, title);
intent.putExtra(ToDoItem.PRIORITY, priority.toString());
intent.putExtra(ToDoItem.STATUS, status.toString());
intent.putExtra(ToDoItem.DATE, date);
}
public String toString() {
return mTitle + ITEM_SEP + mPriority + ITEM_SEP + mStatus + ITEM_SEP
+ FORMAT.format(mDate);
}
public String toLog() {
return "Title:" + mTitle + ITEM_SEP + "Priority:" + mPriority
+ ITEM_SEP + "Status:" + mStatus + ITEM_SEP + "Date:"
+ FORMAT.format(mDate);
}
}
Oh well, after hours tweaking the
public final static SimpleDateFormat FORMAT = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss", Locale.US);
method from ToDoItem, I still cannot successfully convert yyyy-MM-dd to dd/MM/yyyy.
First, I´ve tried the obvious, and changed the expression yyyy-MM-dd to dd/MM/yyyy.
After that, all I got after saving the task was today´s date, even though the date inputted on AddToDoActivity is months or years ahead. If I revert back to yyyy-MM-dd, the date shown on the Task List is the same inputted on AddToDoActivity.
Then I tried to change all mentions of dates on every class to match the exact format that I wanted.
That made everything look good on AddToDoActivity, but again, when I transported the date back to ToDoItem, the app just ignored the previously inputted date and showed today´s date again.
Can anyone help me with this one??
Thanks!!
You are calling setDateString with arguments in the order of year, month, day:
setDateString(c.get(Calendar.YEAR), c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH));
But your method has parameters in the order of day, month, year:
private static void setDateString(int dayOfMonth, int monthOfYear, int year) {
...
}
I also think you made some errors while copying your code into the question, since the setDateString method is duplicated and there is no setTimeString method.
Change:
setDateString(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
to:
setDateString(c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.MONTH), c.get(Calendar.YEAR));
Modify the code as follows in the ToDoListAdapter file getView method
// TODO - Display Time and Date.
// Hint - use ToDoItem.FORMAT.format(toDoItem.getDate()) to get date and time String
final TextView dateView = (TextView) itemLayout.findViewById(R.id.dateView);
dateView.setText(ToDoItem.FORMAT.format(toDoItem.getDate()));
The output will be something similar the the following
Reference:
Completing UI Activity assignment