You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# Android应用SQLite数据表项的编辑与删除实现咨询

实现C# Android应用的数据编辑与删除功能方案

嘿,你已经把基础的存储和展示框架搭得挺完整了!要给现有功能加上编辑和删除其实不难,咱们一步步来,从数据库操作扩展、界面交互控件、跨Activity数据传递这几个核心环节入手:

一、先给公共类Class1完善数据库操作方法

因为两个Activity都依赖Class1来操作数据库,所以先把「更新」「删除」「获取单条数据」这几个关键方法加上——毕竟编辑需要先拿到原有数据,删除和更新都要和数据库交互:

// 假设你的数据模型是UserInput,包含Id(主键)、Content等字段
public class Class1
{
    private SQLiteConnection _dbConnection;

    // 你的数据库初始化代码(比如打开/创建数据库)这里就不重复了

    // 更新数据方法
    public int UpdateUserInput(UserInput input)
    {
        string updateQuery = "UPDATE UserInputs SET Content = @Content WHERE Id = @Id";
        return _dbConnection.Execute(updateQuery, new { input.Content, input.Id });
    }

    // 删除数据方法
    public int DeleteUserInput(int inputId)
    {
        string deleteQuery = "DELETE FROM UserInputs WHERE Id = @Id";
        return _dbConnection.Execute(deleteQuery, new { Id = inputId });
    }

    // 根据Id获取单条数据(用于编辑前加载原有内容)
    public UserInput GetUserInputById(int inputId)
    {
        return _dbConnection.Table<UserInput>().FirstOrDefault(input => input.Id == inputId);
    }
}

二、在展示数据的Second Activity中添加交互控件

假设你是用RecyclerView来展示列表的,那先给每个列表项加上「编辑」和「删除」按钮(在Item布局里添加两个Button),然后在Adapter里处理点击事件:

1. Adapter的核心代码

public class UserInputAdapter : RecyclerView.Adapter
{
    private List<UserInput> _inputList;
    private Class1 _dbHelper;
    private Action<int> _onEditTriggered;
    private Action<int> _onDeleteTriggered;

    // 构造方法传入数据、数据库助手、点击回调
    public UserInputAdapter(List<UserInput> inputList, Class1 dbHelper, Action<int> editCallback, Action<int> deleteCallback)
    {
        _inputList = inputList;
        _dbHelper = dbHelper;
        _onEditTriggered = editCallback;
        _onDeleteTriggered = deleteCallback;
    }

    // 重写OnCreateViewHolder、GetItemCount这些基础方法(你应该已经有了)

    public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
    {
        var viewHolder = holder as UserInputViewHolder;
        var currentInput = _inputList[position];

        // 展示内容
        viewHolder.ContentTextView.Text = currentInput.Content;

        // 编辑按钮点击:触发回调,传入当前数据的Id
        viewHolder.EditButton.Click += (s, e) => _onEditTriggered?.Invoke(currentInput.Id);

        // 删除按钮点击:先弹确认框,再执行删除
        viewHolder.DeleteButton.Click += (s, e) =>
        {
            var confirmDialog = new AlertDialog.Builder(holder.ItemView.Context)
                .SetTitle("确认删除")
                .SetMessage("确定要删除这条记录吗?")
                .SetPositiveButton("删除", (dialog, which) =>
                {
                    // 从数据库删除
                    _dbHelper.DeleteUserInput(currentInput.Id);
                    // 更新列表并通知Adapter刷新
                    _inputList.RemoveAt(position);
                    NotifyItemRemoved(position);
                })
                .SetNegativeButton("取消", null)
                .Create();
            confirmDialog.Show();
        };
    }

    // ViewHolder类,绑定Item布局里的控件
    public class UserInputViewHolder : RecyclerView.ViewHolder
    {
        public TextView ContentTextView;
        public Button EditButton;
        public Button DeleteButton;

        public UserInputViewHolder(View itemView) : base(itemView)
        {
            ContentTextView = itemView.FindViewById<TextView>(Resource.Id.tv_input_content);
            EditButton = itemView.FindViewById<Button>(Resource.Id.btn_edit);
            DeleteButton = itemView.FindViewById<Button>(Resource.Id.btn_delete);
        }
    }
}

2. 在Second Activity中配置Adapter并处理编辑跳转

public class SecondActivity : AppCompatActivity
{
    private Class1 _dbHelper;
    private RecyclerView _recyclerView;
    private UserInputAdapter _adapter;
    private List<UserInput> _inputList;

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.activity_second);

        _dbHelper = new Class1();
        _recyclerView = FindViewById<RecyclerView>(Resource.Id.rv_input_list);
        LoadUserInputs(); // 加载数据库数据的方法(你原来的代码)
    }

    private void LoadUserInputs()
    {
        _inputList = _dbHelper.GetAllUserInputs().ToList(); // 你原来的获取所有数据的方法
        _adapter = new UserInputAdapter(_inputList, _dbHelper, 
            // 编辑回调:跳转到输入页面并携带要编辑的Id
            (inputId) =>
            {
                var editIntent = new Intent(this, typeof(MainActivity));
                editIntent.PutExtra("EditInputId", inputId);
                StartActivityForResult(editIntent, 100); // 100是自定义的请求码
            },
            // 删除回调:这里可以做一些额外的刷新操作(比如重新加载数据)
            (inputId) => LoadUserInputs()
        );
        _recyclerView.Adapter = _adapter;
    }

    // 接收输入页面返回的修改结果,刷新列表
    protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
    {
        base.OnActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == Result.Ok)
        {
            LoadUserInputs(); // 重新加载数据,更新列表
        }
    }
}

三、改造输入Activity(Main/First Activity)支持编辑模式

原来的输入页面是用来新增数据的,现在要让它能接收编辑Id,加载原有内容,然后保存修改:

public class MainActivity : AppCompatActivity
{
    private Class1 _dbHelper;
    private EditText _inputEditText;
    private Button _saveButton;
    private int _editInputId = -1; // 默认是新增模式,Id为-1

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.activity_main);

        _dbHelper = new Class1();
        _inputEditText = FindViewById<EditText>(Resource.Id.et_user_input);
        _saveButton = FindViewById<Button>(Resource.Id.btn_save);

        // 检查是否是编辑模式:获取传递过来的Id
        _editInputId = Intent.GetIntExtra("EditInputId", -1);
        if (_editInputId != -1)
        {
            // 加载原有数据到输入框
            var existingInput = _dbHelper.GetUserInputById(_editInputId);
            if (existingInput != null)
            {
                _inputEditText.Text = existingInput.Content;
                _saveButton.Text = "保存修改"; // 把按钮文字改成编辑提示
            }
        }

        // 保存按钮点击事件
        _saveButton.Click += (s, e) =>
        {
            string inputContent = _inputEditText.Text.Trim();
            if (!string.IsNullOrEmpty(inputContent))
            {
                if (_editInputId != -1)
                {
                    // 编辑模式:更新数据库
                    var updatedInput = new UserInput { Id = _editInputId, Content = inputContent };
                    _dbHelper.UpdateUserInput(updatedInput);
                }
                else
                {
                    // 新增模式:插入数据库(你原来的代码)
                    var newInput = new UserInput { Content = inputContent };
                    _dbHelper.InsertUserInput(newInput);
                }
                // 返回成功结果给Second Activity
                SetResult(Result.Ok);
                Finish(); // 关闭当前页面
            }
        };
    }
}

四、一些需要注意的细节

  • 确保你的UserInput模型类有Id字段(主键),数据库表也要把Id设为主键自增,这样才能准确找到要编辑/删除的记录。
  • 可以给输入框加空值判断,避免保存空内容。
  • 删除时的确认对话框很重要,防止用户误操作。
  • 如果数据量较大,加载数据时可以考虑异步操作,避免UI卡顿。

内容的提问来源于stack exchange,提问作者Wassim01

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:47:14