mardi 23 juin 2015

Populate UITableViewSource with data from Sqlite

Im using Xamarin and mono to create an iOS application. Im using a UITableView to display the records available in a collection. The problem Im having is getting the List I created with the data from an Sqlite database into the DataSource object to populate the table. I know the Sqlite queries work, I just can't populate the table.

Here is the default datasource that Xamarin built.

using System;
using System.Collections.Generic;

using Foundation;
using UIKit;

namespace RecordStore
{
    public class DataSource : UITableViewSource
    {
        static readonly NSString CellIdentifier = new NSString ("Cell");
        readonly List<object> objects = new List<object> ();
        readonly MasterViewController controller;

        public DataSource (MasterViewController controller)
        {
            this.controller = controller;
        }

        public IList<object> Objects {
            get { return objects; }
        }

        // Customize the number of sections in the table view.
        public override nint NumberOfSections (UITableView tableView)
        {
            return 1;
        }

        public override nint RowsInSection (UITableView tableview, nint section)
        {
            return objects.Count;
        }

        // Customize the appearance of table view cells.
        public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
        {
            var cell = tableView.DequeueReusableCell (CellIdentifier, indexPath);

            cell.TextLabel.Text = objects [indexPath.Row].ToString ();

            return cell;
        }

        public override bool CanEditRow (UITableView tableView, NSIndexPath indexPath)
        {
            // Return false if you do not want the specified item to be editable.
            return true;
        }

        public override void CommitEditingStyle (UITableView tableView, UITableViewCellEditingStyle editingStyle, NSIndexPath indexPath)
        {
            if (editingStyle == UITableViewCellEditingStyle.Delete) {
                // Delete the row from the data source.
                objects.RemoveAt (indexPath.Row);
                controller.TableView.DeleteRows (new [] { indexPath }, UITableViewRowAnimation.Fade);
            } else if (editingStyle == UITableViewCellEditingStyle.Insert) {
                // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
            }
        }
    }
}

Its called from the MasterViewController like so:

TableView.Source = dataSource = new DataSource (this);

Here is the database code:

using System;
using System.IO;
using System.Data;
using System.Collections.Generic;

using Mono.Data.Sqlite;

namespace RecordStore
{
    public class Database
    {
        public Database ()
        {
        }

        public List<string> GetItems() {
            List<string> list = new List<string> ();

            var connection = GetConnection ();
            using (var cmd = connection.CreateCommand ()) {
                connection.Open ();
                cmd.CommandText = "SELECT `Album` FROM Records";
                using (var reader = cmd.ExecuteReader ()) {
                    while (reader.Read ()) {
                        for (int i = 0; i < reader.FieldCount; ++i) {
                            list.Add (reader[i].ToString());
                        }
                    }
                }
                connection.Close ();
            }

            return list;
        }

        static SqliteConnection GetConnection()
        {
            var documents = Environment.GetFolderPath (
                Environment.SpecialFolder.Personal);
            string db = Path.Combine (documents, "mydb.db3");
            bool exists = File.Exists (db);
            if (!exists)
                SqliteConnection.CreateFile (db);
            var conn = new SqliteConnection("Data Source=" + db);
            if (!exists) {
                var commands = new[] {
                    "CREATE TABLE Records (ID INTEGER PRIMARY KEY AUTOINCREMENT, Artist ntext, Album ntext, Genre ntext, Year ntext)",

                    // @TODO: Remove at production
                    // WARNING: never insert user-entered data with embedded parameter values
                    "INSERT INTO Records (ID, Artist, Album, Genre, Year) VALUES (null, 'A Day to Remember', 'Homesick', 'Post-Hardcore', '2008')"
                };
                conn.Open ();
                foreach (var cmd in commands) {
                    using (var c = conn.CreateCommand()) {
                        c.CommandText = cmd;
                        c.CommandType = CommandType.Text;
                        c.ExecuteNonQuery ();
                    }
                }
                conn.Close ();
            }
            return conn;
        }

        static void Write(SqliteDataReader reader, int index)
        {
            Console.Error.Write("({0} '{1}')", reader.GetName(index), reader[index]);
        }
    }
}

Any help would be greatly appreciated, sadly I can't figure this out at all.

See more ..

Aucun commentaire:

Enregistrer un commentaire