如何将数据添加到SQLite离线数据库表并在listView Xamarin上显示-问答-阿里云开发者社区-阿里云

开发者社区> 问答> 正文

如何将数据添加到SQLite离线数据库表并在listView Xamarin上显示

保持可爱mmm 2019-11-18 13:55:07 130

我正在Xamarin.Forms中进行Weather应用程序项目。在成功将用户添加到数据库并在“登录”上验证现有用户之后,现在我正在努力在SQLite数据库内部添加一个城镇(带有3个变量),然后在内容页面的ListView中显示信息。问题是当我单击“天气”按钮时,ListView中没有显示任何内容,并且还触发了第二个捕获-Temp =“无法获取天气”;

让我们从我的城镇模型开始:

public class Town {
[PrimaryKey] public int ID { get; set; } public string TownName { get; set; } public string Temp { get; set; } public string searchTime { get; set; }

public Town() { }

} 创建这个简单的类之后,我将实现一个控制器类来处理Town数据:

SQLiteConnection database;

public SearchHistoryDataController()
{

    database = DependencyService.Get<ISQLite>().GetConnection();

    database.CreateTable<Town>();

}

IEnumerable<Town> orderItemCollection;
public IEnumerable<Town> OrderItemCollection
{
    get
    {
        if (orderItemCollection == null)
            orderItemCollection = GetTowns();
        return orderItemCollection;
    }
}

public IEnumerable<Town> GetTowns()
{
    // Changing the database table items as ObservableCollection
    var table = (from i in database.Table<Town>() select i);
    ObservableCollection<Town> TownList = new ObservableCollection<Town>();
    foreach (var town in table)
    {
        TownList.Add(new Town()
        {
            ID = town.ID,
            TownName = town.TownName,
            Temp = town.Temp,
            searchTime = town.searchTime
        });
    }
    return TownList;
}

public Town GetTown(int id)
{

    return database.Table<Town>().FirstOrDefault(t => t.ID == id);

}


public void DeleteTown(int id)
{

    database.Delete<Town>(id);

}

public string AddTown(Town town)
{
    var data = database.Table<Town>();
    var d1 = data.Where(x => x.TownName == town.TownName && x.searchTime == town.searchTime).FirstOrDefault();

    if (d1 == null)
    {           

        database.Insert(town);

        return "Successfully Added";

    }
    else
    {
        return "Invalid Town id Exist";
    }
}

从这里开始,最后两件事是:创建城镇,插入一些信息,将城镇存储在数据库中,只要单击“显示天气”按钮,就可以在命令中完成。有代码:

             //Get weather information for the Weather view
        Temp = $"{weatherRoot?.MainWeather?.Temperature ?? 0}°C";
        Condition = $"{weatherRoot?.Weather?[0]?.Description ?? string.Empty}";
        Name = $"{weatherRoot.Name}, {weatherRoot.System.Country}";
        Humidity = $"{weatherRoot.MainWeather.Humidity}%";
        Pressure = $"{weatherRoot.MainWeather.Pressure} hpa";
        Clouds = $"{weatherRoot.Clouds.CloudinessPercent}%";
        Wind = $"{weatherRoot.Wind.Speed} m/s";


        town.TownName = $"{weatherRoot.Name}";
        town.Temp = Temp;
        town.searchTime = DateTime.Parse(weatherRoot.Date).ToLocalTime().ToString("g");;

        //history database push               
        try
        {
            SearchHistoryDataController searchHistoryDataController = new SearchHistoryDataController();
            var returnvalue = searchHistoryDataController.AddTown(town);

            if (returnvalue == "Sucessfully Added")
            {

                Console.WriteLine("Success");

            }
            else
            {
                Console.WriteLine("Fail");
            }
        }
        catch (Exception es)
        {
            Debug.WriteLine(es.Message);
        }


        await TextToSpeech.SpeakAsync(Temp + " " + Condition);
        IsBusy = false;

    }
    catch (Exception ex)
    {
        Temp = "Unable to get Weather";
        Debug.WriteLine(ex.Message);
    }
    finally
    {
        IsBusy = false;
    }
}

最终的XAML文件的结构如下:

<ListView.SeparatorColor> </ListView.SeparatorColor> <ListView.ItemTemplate> <Grid.ColumnDefinitions> </Grid.ColumnDefinitions> </ListView.ItemTemplate> 想法是当单击“天气”按钮时自动更新历史记录列表。历史记录将在文本字段中存储城镇名称,确切时间以及温度。该列表将不会用于其他任何事情,它是一个选项卡。

非常感谢你!

问题来源于stack overflow

view数据库 添加数据表 数据库listview 数据库list 数据表显示
分享到
取消 提交回答
全部回答(1)
  • 保持可爱mmm
    2019-11-18 13:55:30

    我确实解决了问题。第一个问题是这条线:town.searchTime = DateTime.Parse(weatherRoot.Date).ToLocalTime().ToString("g");

    由于无法访问此日期变量,导致命令失败。我用以下方法修复了它:town.searchTime = DateTime.Now.ToString();

    下一步-如何显示保存在SQLite数据库中的数据:

    将Town插入数据库,然后进行轮询并将其存储在TownList下:

    town.TownName = $"{weatherRoot.Name}"; town.Temp = Temp; town.searchTime = DateTime.Now.ToString();

                //history database push               
                try
                {      
                    var returnvalue = searchHistoryDataController.AddTown(town);
    
                    if (returnvalue == "Sucessfully Added")
                    {
    
                        Console.WriteLine("Success");
                    }
                    else
                    {
                        Console.WriteLine("Fail");
                    }                
                }
                catch (Exception es)
                {
                    Debug.WriteLine(es.Message);
                }
    
                TownList = searchHistoryDataController.OrderItemCollection;
    

    最后但并非最不重要的XAML和SearchHistoryController:

    <ListView.SeparatorColor> </ListView.SeparatorColor> <ListView.ItemTemplate> <Grid.ColumnDefinitions> </Grid.ColumnDefinitions> </ListView.ItemTemplate> 将信息从SQL提取到列表的方法:

    IEnumerable orderItemCollection; public IEnumerable OrderItemCollection { get { if (orderItemCollection == null) orderItemCollection = GetTowns(); return orderItemCollection; } }

        public IEnumerable<Town> GetTowns()
        {
            // Changing the database table items as ObservableCollection
            var table = (from i in database.Table<Town>() select i);
            ObservableCollection<Town> TownList = new ObservableCollection<Town>();
            foreach (var town in table)
            {
                TownList.Add(new Town()
                {
                    ID = town.ID,
                    TownName = town.TownName,
                    Temp = town.Temp,
                    searchTime = town.searchTime
                });
            }
            return TownList;
        }
    

    只是要提醒大家,如果将对象的模型存储在SQL中,则始终包括AutoIncrement:

    [PrimaryKey, AutoIncrement] public int ID { get; set; } 希望这会帮助某人。:)

    0 0
数据库
使用钉钉扫一扫加入圈子
+ 订阅

分享数据库前沿,解构实战干货,推动数据库技术变革

相似问题
最新问题
推荐课程