如何将数据从数据库 table 添加到 ListView C# Xamarin Android App

How to add data from database table to ListView C# Xamarin Android App

几天前,我询问如何在活动之间共享数据,一位用户告诉我使用 SQLite,我就照做了。我想让用户单击 MainLayout 中的按钮,这会将他重定向到 AddTaskLayout,他可以在其中添加任务名称,然后按“保存”按钮应用程序会将他重定向回 MainLayout,他的任务将在 ListView 中列出。

到目前为止,我创建了数据库,table 以及我需要的一切。我的问题是:如何将存储在数据库table 中的数据添加到ListView?我找到的每个答案都写在 Java 中,因此搜索旧的 Whosebug 问题并不是很有帮助:/

代码如下:

我的 DBRepository 是 class,表示创建数据库、创建 table、向 table 插入数据并获取相同的数据:

public class DBRepository
{

    public void CreateDatabase()
    {
        string dbPath = Path.Combine(System.Environment.GetFolderPath
            (System.Environment.SpecialFolder.Personal), "database.db3");
        var db = new SQLiteConnection(dbPath);
    }

    public void CreateTable()
    {
        string dbPath = Path.Combine(System.Environment.GetFolderPath
           (System.Environment.SpecialFolder.Personal), "database.db3");
        var db = new SQLiteConnection(dbPath);
        db.CreateTable<ToDoTasks>();
    }

    public string InsertRecord(string task)
    {
        string dbPath = Path.Combine(System.Environment.GetFolderPath
           (System.Environment.SpecialFolder.Personal), "database.db3");
        var db = new SQLiteConnection(dbPath);
        ToDoTasks item = new ToDoTasks();
        item.Task = task;
        db.Insert(item);
        return task;
    }

    public string GetData()
    {
        string dbPath = Path.Combine(System.Environment.GetFolderPath
           (System.Environment.SpecialFolder.Personal), "database.db3");
        var db = new SQLiteConnection(dbPath);
        string output = "";
        var table = db.Table<ToDoTasks>();
        foreach(var item in table)
        {
            output += item;

        }            
        return output;
    }
}

ToDoTasks class 我在其中创建 table:

[Table("ToDo")]
public class ToDoTasks
{
    [PrimaryKey, AutoIncrement, Column("_Id")]
    public int Id { get; set; }

    [MaxLength(100)]
    public string Task { get; set; }
}

我的 AddTaskActivity 表示用户输入任务名称的第二个布局:

protected override void OnCreate(Bundle bundle)
{

    base.OnCreate(bundle);
    SetContentView(Resource.Layout.AddTask);

    //define buttons
    Button save, cancel;
    save = FindViewById<Button>(Resource.Id.save);
    cancel = FindViewById<Button>(Resource.Id.cancel);

    save.Click += save_click;
    cancel.Click += cancel_click;
}

private void save_click(object sender, EventArgs e)
{
    DBRepository dbr = new DBRepository();
    EditText name = FindViewById<EditText>(Resource.Id.taskName);
    //enter user's input(task name) to table

    var result = dbr.InsertRecord(name.Text);
    StartActivity(typeof(MainActivity));
}

private void cancel_click(object sender, EventArgs e)
{
    StartActivity(typeof(MainActivity));
}

我要填充 listView 的 MainActivity:

protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);

    // Set view
    SetContentView(Resource.Layout.Main);

    //create database if it doesn't exist
    DBRepository dbr = new DBRepository();
    dbr.CreateDatabase();

    //create table (if it doesn't exist)
    dbr.CreateTable();

    //Define buttons
    Button addTask;
    ListView list;
    addTask = FindViewById<Button>(Resource.Id.addTask);
    addTask.Click += addTask_click;
}             

private void addTask_click(object sender, EventArgs e)
{
    StartActivity(typeof(AddTaskActivity));
}

非常感谢您的帮助。我知道这些是非常基本的问题,但必须有人为自己和许多其他(未来的)C# android 开发人员提出这些问题。谢谢!

////////////////////

更新: 我检查了 Johan 的回答是正确的,但这是(在我的例子中)正确的代码:

我需要将 GetData() 方法更改为 return 列表(不是以前的对象),然后在 ListView 中显示该列表。这是代码:

    You helped me a lot, but I had to make few changes, so here they are for the record:

在 DBRepository 中需要将 GetData() 方法更改为:

    public List<string> GetData()
    {
        string dbPath = Path.Combine(System.Environment.GetFolderPath
           (System.Environment.SpecialFolder.Personal), "database.db3");
        var db = new SQLiteConnection(dbPath);
        List<string> data = new List<string>();
        foreach (var item in db.Table<ToDoTasks>())
        {
            var zad = item.Task.ToString();

            data.Add(zad);
        }
        return data;

    }

然后,在 MainActivity 的 ListView 代码中只添加:

    var items = dbr.GetData();
        var listView = FindViewById<ListView>(Resource.Id.listView);

        listView.Adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, items);

希望以后能对其他人有所帮助。再次感谢大家。

根据我的意见,您需要进行以下更改。

public List<ToDoTasks> GetData()
{
    string dbPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "database.db3");
    var db = new SQLiteConnection(dbPath);
    return db.Table<ToDoTasks>().ToList();
}

然后在您的 Activity 中有一个 ListView 的地方,您可以执行以下操作

protected override void OnCreate(Bundle bundle)
{
   base.OnCreate(bundle);

   // Set view
   SetContentView(Resource.Layout.Main);

   //create database if it doesn't exist
   DBRepository dbr = new DBRepository();
   dbr.CreateDatabase();

   //create table (if it doesn't exist)
   dbr.CreateTable();

   var items = dbr.GetData();
   var listView = FindViewById<ListView>(Android.Resource.Id.ListView);
   listView.Adapter = new ArrayAdapter<String>(this, Android.Resource.Layout.SimpleListItem1, items);
}

如果您的 Activity 继承自 ListActivity,您只需执行以下操作

protected override void OnCreate(Bundle bundle)
{
   base.OnCreate(bundle);

   // Set view
   SetContentView(Resource.Layout.Main);

   //create database if it doesn't exist
   DBRepository dbr = new DBRepository();
   dbr.CreateDatabase();

   //create table (if it doesn't exist)
   dbr.CreateTable();

   var items = dbr.GetData();
   ListAdapter = new ArrayAdapter<String>(this, Android.Resource.Layout.SimpleListItem1, items);
}

我从 Xamarin 提供的示例中提取了部分代码,可以在这里找到:https://developer.xamarin.com/guides/android/user_interface/working_with_listviews_and_adapters/