简体   繁体   English

如何让用户在 Xamarin C# 中编辑他们的输入

[英]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!感谢@jai 的帮助!

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:当我像这样放置_dateDisplay = (EditText)"reminder.Date" 在此处输入图片说明

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如果您需要,这是我的完整应用程序: 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.您必须将所选对象的 ID 从列表活动传递到要更新的编辑活动。

ListReminder.cs 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编辑提醒.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 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();
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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