Introduction
Let's build a simple reminder application that will remind the particular things (eg: shopping, particular office work/meeting, going to particular place etc.).
This application will take three inputs - Date, Time, and Content that is needed to be reminded.
On the particular date and time, it will notify you in the notification bar and when you click on the notification, it will show you the reminding content.
This article will cover the following,
- Android native application.
- DatePicker, TimePicker, Button Events in Xamarin android application.
- AlarmManager, Broadcast receiver.
- Scheduling of job with the help of AlarmManager.
- SQLite database basics operations.
- Navigation from one activity to another.
- Notification and task stack.
Prerequisites
- Basic programming knowledge of C# and knowledge of application creation and its flow.
- Knowledge of Xamarin is a plus.
- Before/After implementation, please go through the following topics- AlarmManager, BroadcastReceiver, NotificationManager, SQLite Database.
Implementation
I am using Visual Studio Community Edition.
Add a new project Xamarin.Native application with the help of below-given instructions. Click "Next" after selecting the blank Android app.
Give application name, say, “NotificationReminder” and click "Next".
Give the project a name and click "Create".
The directory structure of the project will be like below.
Add the following files under Model directory
Add Reminder.cs class file.
- using System;
- namespace NotificationReminder.Model
- {
- public class Reminder
- {
- public int Id { get; set; }
- public string Date { get; set; }
- public string Time { get; set; }
- public string Note { get; set; }
- public Reminder()
- {
- }
- }
- }
Add DatePickerFragment.cs
- using System;
- using Android.App;
- using Android.OS;
- using Android.Util;
- using Android.Widget;
-
- namespace NotificationReminder.Model
- {
-
- public class DatePickerFragment : DialogFragment,
- DatePickerDialog.IOnDateSetListener
- {
-
- public static readonly string TAG = "X:" + typeof(DatePickerFragment).Name.ToUpper();
-
- Action<DateTime> _dateSelectedHandler = delegate { };
- public static DatePickerFragment NewInstance(Action<DateTime> onDateSelected)
- {
- DatePickerFragment frag = new DatePickerFragment();
- frag._dateSelectedHandler = onDateSelected;
- return frag;
- }
- public override Dialog OnCreateDialog(Bundle savedInstanceState)
- {
- DateTime currently = DateTime.Now;
- DatePickerDialog dialog = new DatePickerDialog(Activity, this, currently.Year, currently.Month, currently.Day);
- return dialog;
- }
- public void OnDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
- {
-
- DateTime selectedDate = new DateTime(year, monthOfYear + 1, dayOfMonth);
- Log.Debug(TAG, selectedDate.ToLongDateString());
- _dateSelectedHandler(selectedDate);
- }
- }
- }
Add TimePickerFragment.cs
- using System;
- using Android.App;
- using Android.OS;
- using Android.Text.Format;
- using Android.Util;
- using Android.Widget;
-
- namespace NotificationReminder.Model
- {
- public class TimePickerFragment : DialogFragment, TimePickerDialog.IOnTimeSetListener
- {
- public static readonly string TAG = "MyTimePickerFragment";
- Action<DateTime> timeSelectedHandler = delegate { };
-
- public static TimePickerFragment NewInstance(Action<DateTime> onTimeSelected)
- {
- TimePickerFragment frag = new TimePickerFragment();
- frag.timeSelectedHandler = onTimeSelected;
- return frag;
- }
-
- public override Dialog OnCreateDialog(Bundle savedInstanceState)
- {
- DateTime currentTime = DateTime.Now;
- bool is24HourFormat = DateFormat.Is24HourFormat(Activity);
- TimePickerDialog dialog = new TimePickerDialog
- (Activity, this, currentTime.Hour, currentTime.Minute, is24HourFormat);
- return dialog;
- }
-
- public void OnTimeSet(TimePicker view, int hourOfDay, int minute)
- {
- DateTime currentTime = DateTime.Now;
- DateTime selectedTime = new DateTime(currentTime.Year, currentTime.Month, currentTime.Day, hourOfDay, minute, 0);
- Log.Debug(TAG, selectedTime.ToLongTimeString());
- timeSelectedHandler(selectedTime);
- }
- }
- }
Add the following files under Repository directory.
Add the file DataStore.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using Android.App;
- using Android.Content;
- using Android.OS;
- using Android.Runtime;
- using Android.Views;
- using Android.Widget;
- using Android.Database.Sqlite;
-
- namespace NotificationReminder.Repository
- {
- public class DataStore : SQLiteOpenHelper
- {
- private static string _DatabaseName = "reminderDB.db";
- public DataStore(Context context) : base(context, _DatabaseName, null, 1) {
-
- }
-
- public override void OnCreate(SQLiteDatabase db)
- {
- db.ExecSQL(ReminderHelper.CreateQuery);
- }
-
- public override void OnUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
- {
- db.ExecSQL(ReminderHelper.DeleteQuery);
- OnCreate(db);
- }
- }
- }
Add the file ReminderHelper.cs
This file contains the various database operations like insert, select, delete.
- using System;
- using System.Collections.Generic;
- using Android.Content;
- using Android.Database.Sqlite;
- using NotificationReminder.Repository;
- using NotificationReminder.Model;
- using Android.Database;
- namespace NotificationReminder.Repository
- {
- public class ReminderHelper
- {
- private const string TableName = "reminderTable";
- private const string ColumnID = "Id";
- private const string ColumnDate = "Date";
- private const string ColumnTime = "Time";
- private const string ColumnNote = "Note";
- public const string CreateQuery = "CREATE TABLE " + TableName + " ( "
- + ColumnID + " INTEGER PRIMARY KEY,"
- + ColumnDate + " TEXT,"
- + ColumnTime + " TEXT,"
- + ColumnNote + " TEXT)";
-
-
- public const string DeleteQuery = "DROP TABLE IF EXISTS " + TableName;
-
- public ReminderHelper()
- {
- }
-
- public static void InsertReminderData(Context context, Reminder reminder)
- {
- SQLiteDatabase db = new DataStore(context).WritableDatabase;
- ContentValues contentValues = new ContentValues();
- contentValues.Put(ColumnDate, reminder.Date);
- contentValues.Put(ColumnTime, reminder.Time);
- contentValues.Put(ColumnNote, reminder.Note);
-
- db.Insert(TableName, null, contentValues);
- db.Close();
- }
-
- public static List<Reminder> GetReminderList(Context context)
- {
- List<Reminder> reminder = new List<Reminder>();
- SQLiteDatabase db = new DataStore(context).ReadableDatabase;
- string[] columns = new string[] { ColumnID, ColumnDate, ColumnTime, ColumnNote };
-
- using (ICursor cursor = db.Query(TableName, columns, null, null, null, null, null))
- {
- while (cursor.MoveToNext())
- {
- reminder.Add(new Reminder
- {
- Id = cursor.GetInt(cursor.GetColumnIndexOrThrow(ColumnID)),
- Date = cursor.GetString(cursor.GetColumnIndexOrThrow(ColumnDate)),
- Time = cursor.GetString(cursor.GetColumnIndexOrThrow(ColumnTime)),
- Note = cursor.GetString(cursor.GetColumnIndexOrThrow(ColumnNote))
- });
- }
- }
- db.Close();
- return reminder;
- }
-
- public static void DeleteReminder(Context context, Reminder reminder )
- {
- SQLiteDatabase db = new DataStore(context).WritableDatabase;
- db.Delete(TableName, ColumnDate + "=? AND "+ ColumnTime +"=? OR " + ColumnID + "=" + reminder.Id, new string[] { reminder.Date, reminder.Time });
- db.Close();
- }
-
- public static Reminder SelectReminder(Context context)
- {
- Reminder reminder;
- SQLiteDatabase db = new DataStore(context).WritableDatabase;
- string[] columns = new string[] { ColumnID, ColumnDate, ColumnTime, ColumnNote };
- string datetime = DateTime.Now.ToString();
- string[] dt = datetime.Split(' ');
- var date = dt[0];
- var tt = dt[1].Split(':');
- var time = tt[0] + ":" + tt[1] + " " + dt[2];
-
-
- using (ICursor cursor = db.Query(TableName, columns, ColumnDate +"=? AND "+ ColumnTime +"=?", new string[]{date, time},null,null,null))
- {
- if (cursor.MoveToNext())
- {
- reminder = new Reminder
- {
- Id = cursor.GetInt(cursor.GetColumnIndexOrThrow(ColumnID)),
- Date = cursor.GetString(cursor.GetColumnIndexOrThrow(ColumnDate)),
- Time = cursor.GetString(cursor.GetColumnIndexOrThrow(ColumnTime)),
- Note = cursor.GetString(cursor.GetColumnIndexOrThrow(ColumnNote))
- };
- }
- else
- {
- reminder = null;
- }
- }
- return reminder;
- }
- }
- }
Add the following files in BroadcastNotification directory.
Add the file ReminderNotification.cs
We are inheriting the BroadcastReceiver, an abstract class, and implementing the OnReceive method that will execute when it is broadcasted from AlarmManager with its pending intent, that is, ReminderNotification.
- using System;
- using Android.App;
- using Android.Content;
- using Android.OS;
- using Android.Support.V4.App;
- using Newtonsoft.Json;
- using NotificationReminder.Model;
- using NotificationReminder.Repository;
-
- namespace NotificationReminder.BroadcastNotification
- {
- [BroadcastReceiver(Enabled = true)]
- public class ReminderNotification : BroadcastReceiver
- {
- Reminder reminder;
- public ReminderNotification()
- {
- }
-
- public override void OnReceive(Context context, Intent intent)
- {
- reminder = ReminderHelper.SelectReminder(context);
- if(reminder != null)
- {
- Intent newIntent = new Intent(context, typeof(ReminderContent));
- newIntent.PutExtra("reminder", JsonConvert.SerializeObject(reminder));
-
-
- Android.Support.V4.App.TaskStackBuilder stackBuilder = Android.Support.V4.App.TaskStackBuilder.Create(context);
- stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(ReminderContent)));
- stackBuilder.AddNextIntent(newIntent);
-
-
- PendingIntent resultPendingIntent = stackBuilder.GetPendingIntent(0, (int)PendingIntentFlags.UpdateCurrent);
-
- NotificationCompat.Builder builder = new NotificationCompat.Builder(context).SetAutoCancel(true)
- .SetDefaults((int)NotificationDefaults.All)
- .SetContentIntent(resultPendingIntent).SetContentTitle("Reminder!!")
- .SetSmallIcon(Resource.Drawable.Icon).SetContentText("Click for details..")
- .SetContentInfo("Start");
- NotificationManager notificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService);
- notificationManager.Notify(2, builder.Build());
- }
- }
- }
- }
Add the following files under Layout directory in Resource.
Main.axml [Already added. Just modify the content]
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
- <EditText
- android:id="@+id/date_display"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:hint="Date"
- android:focusable="false" />
- <EditText
- android:id="@+id/time_display"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:hint="Time"
- android:focusable="false" />
- <EditText
- android:id="@+id/txtNote"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:hint="Enter your reminder content!" />
- <Button
- android:id="@+id/save"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="@string/btn_save" />
- <Button
- android:id="@+id/btnList"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="@string/btn_list" />
- </LinearLayout>
ReminderAdded.axml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
- <TextView
- android:id="@+id/reminder_label"
- android:layout_width="match_parent"
- android:layout_height="wrap_content" />
- <TextView
- android:id="@+id/date_display"
- android:layout_width="match_parent"
- android:layout_height="wrap_content" />
- <TextView
- android:id="@+id/time_display"
- android:layout_width="match_parent"
- android:layout_height="wrap_content" />
- <TextView
- android:id="@+id/txt_note"
- android:layout_width="match_parent"
- android:layout_height="wrap_content" />
- <Button
- android:id="@+id/btn_back"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="@string/btn_list" />
- </LinearLayout>
AXML
The listReminder will have the ListView that will take the single item in form of table layout with the table row.
- <?xml version="1.0" encoding="utf-8"?>
- <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
- <TableRow>
- <TextView
- android:id="@+id/txtId"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
- <TextView
- android:id="@+id/txtDate"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
- <TextView
- android:id="@+id/txtTime"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
- <TextView
- android:id="@+id/txtNote"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
- </TableRow>
- </TableLayout>
ListReminder.axml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
- <ListView
- android:id="@+id/listReminder"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:background="#00FF00"
- android:layout_weight="1"
- android:drawSelectorOnTop="false"
- android:backgroundTint="#ff1b1111" />
- <TextView
- android:id="@+id/txt_label"
- android:layout_width="match_parent"
- android:layout_height="wrap_content" />
- <Button
- android:id="@+id/addNew"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="Add New" />
- </LinearLayout>
DeleteReminder.axml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
- <TextView
- android:id="@+id/txt_label"
- android:layout_width="match_parent"
- android:layout_height="wrap_content" />
- <Button
- android:id="@+id/btn_back"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="@string/btn_list" />
- </LinearLayout>
ReminderContent.axml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
- <TextView
- android:id="@+id/txt_note"
- android:layout_width="match_parent"
- android:layout_height="wrap_content" />
- <Button
- android:id="@+id/btn_back"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="@string/btn_back" />
- </LinearLayout>
Add the following activity files
Modify/Add MainActivity.cs file.
This is the MainLauncher activity and this is responsible for opening the main screen where we give the details regarding reminder.
- using System;
- using Android.App;
- using Android.Content;
- using Android.OS;
- using Android.Widget;
- using NotificationReminder.Model;
- using Newtonsoft.Json;
- using NotificationReminder.Repository;
- using NotificationReminder.BroadcastNotification;
-
- namespace NotificationReminder
- {
- [Activity(Label = "NotificationReminder", MainLauncher = true)]
- public class MainActivity : Activity
- {
- public Reminder reminder;
- EditText _dateDisplay;
- EditText _timeDisplay;
- EditText _txtNote;
- Button _saveButton;
- Button _btnList;
-
- #region DateOperation
- void DateSelect_OnClick(object sender, EventArgs eventArgs)
- {
- DatePickerFragment frag = DatePickerFragment.NewInstance(delegate (DateTime time)
- {
- _dateDisplay.Text = time.ToString().Split(' ')[0];
- reminder.Date = _dateDisplay.Text;
- });
- frag.Show(FragmentManager, DatePickerFragment.TAG);
- }
- #endregion
-
- #region TimeOperation
- void TimeSelectOnClick(object sender, EventArgs eventArgs)
- {
- TimePickerFragment frag = TimePickerFragment.NewInstance(
- delegate (DateTime time)
- {
- _timeDisplay.Text = time.ToShortTimeString();
- reminder.Time = _timeDisplay.Text;
- });
-
- frag.Show(FragmentManager, TimePickerFragment.TAG);
- }
- #endregion
-
- #region SaveDetails
- void SaveRecords(Object sender, EventArgs eventArgs)
- {
- reminder.Note = _txtNote.Text;
- if(Vaidate())
- {
- DateTime currentDT = DateTime.Now;
- DateTime selectedDT = Convert.ToDateTime(reminder.Date + " " + reminder.Time);
-
-
- if (selectedDT > currentDT)
- {
- ReminderHelper.InsertReminderData(this, reminder);
- ScheduleReminder(reminder);
- var reminderAdded = new Intent(this, typeof(ReminderAdded));
- reminderAdded.PutExtra("reminder", JsonConvert.SerializeObject(reminder));
- StartActivity(reminderAdded);
- }
- else
- {
- Toast.MakeText(this, "This is invalid selelction of Date, Time!", ToastLength.Short).Show();
- }
- }
-
- }
-
- bool Vaidate()
- {
- if(reminder.Date == string.Empty || reminder.Time == string.Empty || reminder.Note == string.Empty)
- {
- Toast.MakeText(this, "Enter the details of all fields!", ToastLength.Short).Show();
- return false;
- }
- return true;
- }
- #endregion
-
- protected override void OnCreate(Bundle savedInstanceState)
- {
- base.OnCreate(savedInstanceState);
- SetContentView(Resource.Layout.Main);
-
- reminder = new Reminder();
- _dateDisplay = FindViewById<EditText>(Resource.Id.date_display);
- _timeDisplay = FindViewById<EditText>(Resource.Id.time_display);
- _txtNote = FindViewById<EditText>(Resource.Id.txtNote);
-
- _saveButton = FindViewById<Button>(Resource.Id.save);
- _btnList = FindViewById<Button>(Resource.Id.btnList);
-
- _dateDisplay.Click += DateSelect_OnClick;
- _timeDisplay.Click += TimeSelectOnClick;
- _saveButton.Click += SaveRecords;
- _btnList.Click += (sender, e) => {
- StartActivity(new Intent(this, typeof(ListReminder)));
- };
- }
-
- #region ReminderNotification
- public void ScheduleReminder(Reminder reminder)
- {
- AlarmManager manager = (AlarmManager)GetSystemService(Context.AlarmService);
- Intent myIntent;
- PendingIntent pendingIntent;
- myIntent = new Intent(this, typeof(ReminderNotification));
-
-
-
- var t = reminder.Time.Split(':');
- var ampm = t[1].Split(' ')[1];
- var hrr = Convert.ToDouble(t[0]);
- var min = Convert.ToDouble(t[1].Split(' ')[0]);
-
- string dateString = Convert.ToString(reminder.Date + " " + hrr + ":" + min + ":00 " + ampm);
-
- DateTimeOffset dateOffsetValue = DateTimeOffset.Parse(dateString);
- var millisec = dateOffsetValue.ToUnixTimeMilliseconds();
-
- pendingIntent = PendingIntent.GetBroadcast(this, 0, myIntent, 0);
- manager.Set(AlarmType.RtcWakeup, millisec, pendingIntent);
- }
- #endregion
- }
- }
Add ReminderAdded.cs
Once you added the reminder from MainActivity, this activity will simply show you that the particular reminder is added and it contains the list button that will take you to the list of reminders you added.
- using System;
- using Android.App;
- using Android.Content;
- using Android.OS;
- using Android.Widget;
- using Newtonsoft.Json;
- using NotificationReminder.Model;
-
- namespace NotificationReminder
- {
- [Activity(Label = "ReminderAdded")]
- public class ReminderAdded : Activity
- {
- TextView _reminderLabel;
- TextView _dateDisplay;
- TextView _timeDisplay;
- TextView _txtNote;
- Button _backButton;
- Reminder reminder;
-
- protected override void OnCreate(Bundle savedInstanceState)
- {
- base.OnCreate(savedInstanceState);
- SetContentView(Resource.Layout.ReminderAdded);
-
- reminder = JsonConvert.DeserializeObject<Reminder>(Intent.GetStringExtra("reminder"));
-
- _reminderLabel = FindViewById<TextView>(Resource.Id.reminder_label);
- _dateDisplay = FindViewById<TextView>(Resource.Id.date_display);
- _timeDisplay = FindViewById<TextView>(Resource.Id.time_display);
- _txtNote = FindViewById<TextView>(Resource.Id.txt_note);
- _backButton = FindViewById<Button>(Resource.Id.btn_back);
-
- _reminderLabel.Text = "Reminder added successfully!!";
- _dateDisplay.Text = "Date : " + reminder.Date;
- _timeDisplay.Text = "Time : " + reminder.Time;
- _txtNote.Text = "Content: " + reminder.Note;
-
- _backButton.Click += (object obj, EventArgs e) => {
- StartActivity(new Intent(this, typeof(ListReminder)));
- };
- }
- }
- }
Add activity GridReminder.cs
We are inheriting the BaseAdapter an abstract class and implementing its abstract methods. The GetView method will be used to get the View that is single record in table layout. This method will be called and will return View for all items of the list that we pass in its constructor.
- using Android.App;
- using Android.Views;
- using Android.Widget;
- using NotificationReminder.Model;
-
- namespace NotificationReminder
- {
- public class GridReminder : BaseAdapter
- {
- private Activity context;
- private Reminder[] listitem;
- public override int Count
- {
- get
- {
- return listitem.Length;
- }
- }
- public GridReminder(Activity context, Reminder[] listitem )
- {
- this.context = context;
- this.listitem = listitem;
- }
- public override Java.Lang.Object GetItem(int position)
- {
- return null;
- }
- public override long GetItemId(int position)
- {
- return listitem.Length;
- }
- public override View GetView(int position, View convertView, ViewGroup parent)
- {
- var view = context.LayoutInflater.Inflate(Resource.Layout.Reminder_SingleItem, parent, false);
- TextView txtDate = (TextView)view.FindViewById(Resource.Id.txtDate);
- TextView txtTime = (TextView)view.FindViewById(Resource.Id.txtTime);
- TextView txtNote = (TextView)view.FindViewById(Resource.Id.txtNote);
- txtDate.Text = (listitem[position].Date).ToString();
- txtTime.Text = (listitem[position].Time).ToString();
- txtNote.Text = (listitem[position].Note == null?"no content":listitem[position].Note).ToString();
- return view;
- }
- }
- }
Add Activity ListReminder.cs
This is responsible for generating the list. Simply, we are using the list item as array and creating the adapter object that will use the same list array and apply that to the adapter of the list. Clicking on any item will ask you to delete the particular reminder if you want.
- using System;
- using Android.App;
- using Android.Content;
- using Android.OS;
- using Android.Widget;
- using NotificationReminder.Model;
- using NotificationReminder.Repository;
-
- namespace NotificationReminder
- {
- [Activity(Label = "ReminderList")]
- public class ListReminder : Activity
- {
- TextView _txtLabel;
- ListView list;
- Reminder reminder;
- Reminder[] listitem;
- Button addNew;
- GridReminder adapter;
- protected override void OnCreate(Bundle savedInstanceState)
- {
- base.OnCreate(savedInstanceState);
-
-
- SetContentView(Resource.Layout.ListReminder);
- _txtLabel = FindViewById<TextView>(Resource.Id.txt_label);
- list = (ListView)FindViewById(Resource.Id.listReminder);
- _txtLabel.Visibility = Android.Views.ViewStates.Invisible;
- BindData();
- addNew = FindViewById<Button>(Resource.Id.addNew);
- addNew.Click += (sender, e) => {
- StartActivity(typeof(MainActivity));
- };
- }
- private void List_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
- {
- Android.App.AlertDialog.Builder dialog = new AlertDialog.Builder(this);
- AlertDialog alert = dialog.Create();
- alert.SetTitle("Delete");
- alert.SetMessage("Are you sure!");
- alert.SetIcon(Resource.Drawable.Icon);
- alert.SetButton("yes", (c, ev) =>
- {
- reminder = listitem[e.Position];
- ReminderHelper.DeleteReminder(this,reminder);
- StartActivity(new Intent(this,typeof(DeleteReminder)));
- GC.Collect();
- });
- alert.SetButton2("no", (c, ev) => { });
- alert.Show();
- }
- private void BindData()
- {
- listitem = ReminderHelper.GetReminderList(this).ToArray();
- if(listitem.Length > 0)
- {
- adapter = new GridReminder(this, listitem);
- list.Adapter = adapter;
- list.ItemClick += List_ItemClick;
- }
- else
- {
- list.Visibility = Android.Views.ViewStates.Invisible;
- _txtLabel.Visibility = Android.Views.ViewStates.Visible;
- _txtLabel.Text = "No upcoming reminders!!";
- }
-
-
- }
- }
- }
Add Activity DeleteReminder.cs
This will simply give you the message that you have deleted the reminder.
- using Android.App;
- using Android.Content;
- using Android.OS;
- using Android.Widget;
-
- namespace NotificationReminder
- {
- [Activity(Label = "DeleteReminder")]
- public class DeleteReminder : Activity
- {
- TextView _txtLabel;
- Button _btn_back;
- protected override void OnCreate(Bundle savedInstanceState)
- {
- base.OnCreate(savedInstanceState);
- SetContentView(Resource.Layout.DeleteReminder);
-
- _txtLabel = FindViewById<TextView>(Resource.Id.txt_label);
- _btn_back = FindViewById<Button>(Resource.Id.btn_back);
- _txtLabel.Text = "Deleted!!";
- _btn_back.Click += (sender, e) => {
- StartActivity(new Intent(this,typeof(ListReminder)));
- };
- }
- }
- }
Add Activity cs
This is the content View of the reminder. This will activated when the Broadcast Receiver calls its OnReceive method for the particular reminder. This will show you the content you want the application to remind you.
After reminding, it will delete that reminder from the database.
- using Android.App;
- using Android.Content;
- using Android.OS;
- using Android.Widget;
- using Newtonsoft.Json;
- using NotificationReminder.Model;
- using NotificationReminder.Repository;
-
- namespace NotificationReminder
- {
- [Activity(Label = "ReminderContent")]
- public class ReminderContent : Activity
- {
- Reminder reminder;
- TextView _txtNote;
- Button _btnBack;
- protected override void OnCreate(Bundle savedInstanceState)
- {
- base.OnCreate(savedInstanceState);
- SetContentView(Resource.Layout.ReminderContent);
-
-
- reminder = JsonConvert.DeserializeObject<Reminder>(Intent.GetStringExtra("reminder"));
- ReminderHelper.DeleteReminder(this,reminder);
- _txtNote = FindViewById<TextView>(Resource.Id.txt_note);
- _txtNote.Text = reminder.Note;
- _btnBack = FindViewById<Button>(Resource.Id.btn_back);
- _btnBack.Click += (sender, e) => {
- StartActivity(new Intent(this, typeof(ListReminder)));
- };
- }
- }
- }
Modify the Strings.xml file in Resources/Values directory.
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
- <string name="app_name">NotificationReminder</string>
- <string name="btn_save">Save</string>
- <string name="btn_back">Back</string>
- <string name="btn_list">List</string>
- <string name="save_message">Saving...</string>
- </resources>
Application screens are as follow -