【问题标题】:Xamarin Forms consuming Web Service使用 Web 服务的 Xamarin 表单
【发布时间】:2020-09-19 10:41:00
【问题描述】:

我是移动应用程序的新手,现在正在使用 xamarin 表单开发应用程序。我用 django (sqlite3 db) 开发了一个网站,现在我正在尝试从中获取数据并在我的移动应用程序中显示在 listvew 中。任何想法如何实现它。我已经尝试过了,但它不起作用。我应该使用rest api吗?

public class LandingViewModel : INotifyPropertyChanged
{
    private List<Dishes> _menuList { set; get; }
    public List<Dishes> MenuList 
    {
        get
        {
            return _menuList;
        }
        set
        {
            if(value != _menuList)
            {
                _menuList = value;
                NotifyPropertyChanged();
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    

    public LandingViewModel()
    {
        GetDataAsync();
    }

    private async void GetDataAsync()
    {
        HttpClient client = new HttpClient();

        var response = await client.GetAsync("https://mysite.ru/project/");
        if (response.IsSuccessStatusCode)
        {
            var content = await response.Content.ReadAsStringAsync();
            var menu = JsonConvert.DeserializeObject<List<Dishes>>(content);
            MenuList = new List<Dishes>(menu);
        }
    }

型号:

 public class Dishes
{
    public int id { get; set; }

    public string description { get; set; }

    public string image { get; set; }

    public DateTime published { get; set; }

}

我在 django 中的数据库:

operations = [
    migrations.CreateModel(
        name='Post',
        fields=[
            ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
            ('description', models.TextField(blank=True)),
            ('image', models.ImageField(blank=True, upload_to='pictures/')),
            ('published', models.DateTimeField(verbose_name='publishing date')),
        ],
    ),
]

【问题讨论】:

  • 是检索数据的问题还是在Listview中绑定问题?
  • “它不起作用”不是对问题的有用描述。您是否收到错误或异常?您是否收到来自服务器的响应?如果您希望我们能够为您提供帮助,您需要更具体地了解正在发生或未发生的事情。
  • 这是我在手机上部署它时遇到的异常 Newtonsoft.Json.JsonReaderException: '解析值时遇到意外字符:<.>
  • 如果您设置断点并检查content,您会得到预期的结果吗?
  • 部署后立即抛出异常

标签: xamarin


【解决方案1】:

我解决了问题

  1. 在 postgresql 数据库中允许远程连接:在 postgresql.conf 中将行 listen_addresses = 'localhost' 替换为 listen_addresses = '*'

  2. 端口 5432 上允许的 tcp\ip 连接

  3. 在我的 web api 中建立了连接宽度 db

     NpgsqlConnection connection;
    
     public string _name;
     public string _description;
     public string _image;
    
     private readonly MenuContext _context;
    
     public MenuController(MenuContext context)
     {
         _context = context;
    
         string connectionString = "Server=server; Port=5432; User Id=user; 
         Password=password; Database=database";
    
         try
         {
             connection = new NpgsqlConnection(connectionString);
             connection.Open();
         }
         catch (Exception ex)
         {
             Console.WriteLine(ex.ToString());
         }
    
         NpgsqlCommand command = connection.CreateCommand();
         command.CommandText = "SELECT * FROM table";
         try
         {
             NpgsqlDataReader reader = command.ExecuteReader();
    
             while (reader.Read())
             {
                 _name = reader[1].ToString();
                 _image = reader[2].ToString();
                 _description = reader[3].ToString();
    
                 _context.Menus.Add(new Menu { name = _name, description = 
                 _description, image = "https://mysite.ru/media/" + _image });
                 _context.SaveChanges();
             }
         }
         catch (Exception ex)
         {
             Console.WriteLine(ex.ToString());
         }
     }
    
     // GET: api/Menu
     [HttpGet]
     public async Task<ActionResult<IEnumerable<Menu>>> GetMenus()
     {
         return await _context.Menus.ToListAsync();
     }
    

我的应用中的代码:

 private async void GetDataAsync()
    {
        HttpClient httpClient = new HttpClient();
        var content = await httpClient.GetStringAsync("https://locahost/api/Menu");
        var menu = JsonConvert.DeserializeObject<List<Dishes>>(content);
        MenuList = new ObservableCollection<Dishes>(menu);
    }

然后在列表视图中显示

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-17
    • 1970-01-01
    • 2018-01-15
    相关资源
    最近更新 更多