简体   繁体   中英

How to let user edit their input in Xamarin C#

I am making a Reminder App, and I want the user to be able to edit their reminders.

At the moment, when a user edits a reminder it edits all the reminders in the list of reminders like so:

Here is some parts of my code:

namespace ReminderApp.Models
{
    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()
        {
        }
    }
}

My database:

using Android.Content;
using Android.Database.Sqlite;

namespace ReminderApp.HelperRepository
{
    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);
        }
    }
}

My database helper to delete update and add reminders:

using System;
using System.Collections.Generic;
using Android.Content;
using Android.Database.Sqlite;
using ReminderApp.Models;
using Android.Database;
namespace ReminderApp.HelperRepository
{
    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 void EditReminderData(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.Update(TableName, contentValues, null, null);
            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;
        }
    }
}

在此处输入图片说明

How do I change my code so I only edit the reminder that the user wants to edit?

Any help appreciated!


EDIT!!

thanks @jai for the help!

But now I have another question at the moment when I choose to edit a reminder, all the fields are blank at the beginning. Like so:

在此处输入图片说明

However I want it to be more like this when I press edit: 在此处输入图片说明

When I put _dateDisplay = (EditText)"reminder.Date" like so: 在此处输入图片说明

I get an error "Object reference not set to an instant of on object"

Here is my full application if you need it: https://github.com/CrazyDanyal1414/ReminderApp

Again any help appreciated!

You will have to pass the Id of selected object from List Activity to Edit Activity that you want to Update.

ListReminder.cs

private void List_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
        {
            AlertDialog.Builder dialog = new AlertDialog.Builder(this);
            AlertDialog alert = dialog.Create();
            alert.SetTitle("Edit or Delete?");
            alert.SetMessage("Would you like to edit your reminder or delete it?");
            alert.SetIcon(Resource.Drawable.image_2020_09_29T09_45_02_165Z);
            alert.SetButton("Delete", (c, ev) =>
            {
                AlertDialog.Builder dialog2 = new AlertDialog.Builder(this);
                AlertDialog alert2 = dialog2.Create();
                alert2.SetTitle("Delete Reminder");
                alert2.SetMessage("Are you sure!");
                alert2.SetIcon(Resource.Drawable.Screenshot_2020_11_11_at_4_57_02_PM);
                alert2.SetButton("yes", (c, ev) =>  
                {
                    TextView _txtLabel;
                    reminder = listitem[e.Position];  
                    ReminderHelper.DeleteReminder(this,reminder);
                    _txtLabel = FindViewById<TextView>(Resource.Id.txt_label);
                    StartActivity(new Intent(this, typeof(ListReminder)));
                    Toast.MakeText(this, "Deleted Sucessfully!", ToastLength.Short).Show();
                    GC.Collect();  
                });
                alert2.SetButton2("no", (c, ev) => { });
                alert2.Show();
            });
            alert.SetButton2("Edit", (c, ev) =>
            {
                var intent = new Intent(this, typeof(EditActivity));
                intent.PutExtra("Id", listitem[e.Position].Id);
                StartActivity(intent);
            });
            alert.SetButton3("Cancel", (c, ev) => { });

            alert.Show();
        }

EditReminder.cs

protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.activity_main);
            reminder = new Reminder();
            var id = Intent.GetIntExtra("Id", 0);
            if (id != 0)
                reminder.Id = id;
            _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)));
            };
        }

ReminderHelper.cs

public static void EditReminderData(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.Update(TableName, contentValues, ColumnID + "=" + reminder.Id, null);
            db.Close();
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM