-1

I'm new in mobile apps and now developing an app with xamarin forms. There is a website which i developed with django (sqlite3 db), and now i'am trying to consume data from it and display in my mobile app in listvew. Any thoughts how to achieve it. I've tried this but it doesn't work. Should i use 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);
        }
    }

models:

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

    public string description { get; set; }

    public string image { get; set; }

    public DateTime published { get; set; }

}

my database in 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')),
        ],
    ),
]
ilmir
  • 80
  • 7
  • Is the problem with retrieving the data or to Bind in Listview ? – Narendra Sharma Sep 19 '20 at 11:25
  • "it doesn't work" is not a helpful description of the problem. Do you get an error or exception? Are you getting a response from the server? You need to be a lot more specific about what is or is not happening if you want us to be able to help you. – Jason Sep 19 '20 at 11:55
  • this is exception i get when deploy it on my phone Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: <. Path '', line 0, position 0.' – ilmir Sep 19 '20 at 13:14
  • If you set a breakpoint and inspect `content` do you get what you expect? – Cheesebaron Sep 19 '20 at 14:11
  • it throws exception right after deployment – ilmir Sep 19 '20 at 15:12
  • is it a good solution to get data directly from db or better use rest api? – ilmir Sep 19 '20 at 15:15
  • have you actually checked the data your service returns? It sounds like is either invalid json or not json at all. Quite likely it is returning some sort of HTML error page – Jason Sep 19 '20 at 15:18
  • i've checked the content. it returns html page – ilmir Sep 19 '20 at 15:59
  • how can i get access to db? – ilmir Sep 19 '20 at 16:04
  • If it returns a HTML page, then that is your problem. You are probably hitting the wrong URL or not authenticated or some other issue with the url. – Cheesebaron Sep 19 '20 at 17:47
  • Hi, did you solve the issue? For this exception, please check if the declared types of the properties are correct. Related link:https://stackoverflow.com/questions/51925160/unexpected-character-encountered-while-parsing-api-response You could also set data binding from the database. – Jarvan Zhang Sep 21 '20 at 07:45
  • yes, i solved. i am using rest api – ilmir Sep 26 '20 at 15:57
  • Please post an answer and accept it. It will be beneficial for other community members who have similar questions. – Jarvan Zhang Sep 28 '20 at 05:36

1 Answers1

0

i solved the problem

  1. in postgresql database allowed remote connection: in postgresql.conf replaced line listen_addresses = 'localhost' with listen_addresses = '*'

  2. allowed tcp\ip connection on port 5432

  3. in my web api established connection width 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();
     }
    

code in my app:

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

and then displayed it in listview

ilmir
  • 80
  • 7