如何将数据库表中的数据添加到ListView C#Xamarin Android App

几天前我问过如何在活动之间共享数据,一个用户告诉我使用SQLite,所以我做了.我想让用户点击MainLayout中的按钮,它会将他重定向到AddTaskLayout,在那里他可以添加任务名称,按下Save按钮应用程序会将他重定向回MainLayout,他的任务将在ListView中列出.

到目前为止,我创建了数据库,表格和我需要的一切.我的问题是:如何将存储在数据库表中的数据添加到ListView?我发现的每个答案都是用Java编写的,所以搜索旧的StackOverflow问题并没有那么有用:/

这是代码:

我的DBRepository是表示创建数据库,创建表,向表插入数据以及获取相同数据的类:

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类:

[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()方法以返回List(不像以前那样对象),然后在ListView中显示List.这是代码:

    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中,您可以在其中执行以下操作

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);
}

如果您的活动继承自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/

点赞