Xamarin.forms应用在将数据插入SQLite数据库时崩溃

时间:2018-07-03 17:11:37

标签: xamarin xamarin.forms

我正在尝试获取用户在AddPage.Xaml.cs中输入的信息,并将其添加到SQLite数据库中。该代码运行良好,直到我按下添加按钮,然后它崩溃了,我无法真正弄清楚发生了什么,而且我也不知道自己在做什么。

这是必需的代码及其相应的类。

这在AddPage.xaml.cs中:

private async Task AddButton_Clicked(object sender, EventArgs e)
{
    App.characterDatabase.SaveCharacter(new Character()
    {
        Name = NameTxt.Text,
        Species = SpeciesTxt.Text,
        ImageUrl = ImageUrlTxt.Text
    });
}

CharacterDatabaseController.cs

public class CharacterDatabaseController
{

    static object locker = new object();

    SQLiteConnection database;

    public CharacterDatabaseController()
    {
        database = DependencyService.Get<IDatabaseConnection>().DbConnection();
        database.CreateTable<Character>();
    }

    public Character GetCharacter()
    {
        lock (locker)
        {
            if (database.Table<Character>().Count() == 0)
            {
                return null;
            }
            else
            {
                return database.Table<Character>().First();
            }
        }
    }

    public int SaveCharacter(Character character)
    {
        lock (locker)
        {
            if (character.Id != 0)
            {
                database.Update(character);
                return character.Id;
            }
            else
            {
                return database.Insert(character);
            }
        }
    }

    public int DeleteCharacter(int id)
    {
        lock (locker)
        {
            return database.Delete<Character>(id);
        }
    }
}

和App.cs:

public static CharacterDatabaseController characterDatabase
{
    get
    {
        if (characterDatabase == null)
        {
            CharacterDatabase = new CharacterDatabaseController();
        }
        return CharacterDatabase;
    }
}

0 个答案:

没有答案