My App does not load list of items

1

I have a App Xamarin.Forms that consumes two rest services. The first service, it consumes normally. But the second, I need to pass a parameter, it is not being consumed. I've tried it in many ways and it does not work. I know my code is buggy, but I do not know where, I do not know how to consume the service. The _data variable that will populate the Grid with the information is not filled in, but null. Below my codes: My data service that should load the items from the URL:

public async Task<List<ItensLib>> GetItensLibAsync(int idorcamento)
        {
            try
            {
                string url = "http://www.inetglobal.com.br/autorizador/api/itens/{idorcamento}";
                var response = await client.GetStringAsync(url);
                var itenslib = JsonConvert.DeserializeObject<List<ItensLib>>(response);
                return itenslib.ToList();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        } 

My call in the builder of my app's xaml.cs class

public MainPageItens(int idorcamento)
        {
            InitializeComponent();
            this.IdOrcamento = idorcamento;

            CarregaDados(idorcamento);
....

async void CarregaDados(int idorcamento)
        {
            _data = await dataService.GetItensLibAsync(idorcamento);
        }

My complete builder, with Grid assembly

public MainPageItens(int idorcamento)
        {
            InitializeComponent();
            this.IdOrcamento = idorcamento;

            CarregaDados(idorcamento);

            // Crete a grid for "title"
            Grid grid = CreateGrid();
            grid.Children.Add(new Label { Text = "Produto", TextColor = Color.Red, VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center }, 0, 1, 0, 1);
            grid.Children.Add(SeparatorV(), 1, 2, 0, 1);
            grid.Children.Add(new Label { Text = "Qtde", TextColor = Color.Red, VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center }, 2, 3, 0, 1);
            grid.Children.Add(SeparatorV(), 3, 4, 0, 1);
            grid.Children.Add(new Label { Text = "Unitário", TextColor = Color.Red, VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center }, 4, 5, 0, 1);
            grid.Children.Add(SeparatorV(), 5, 6, 0, 1);
            grid.Children.Add(new Label { Text = "Custo", TextColor = Color.Red, VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center }, 6, 7, 0, 1);
            grid.Children.Add(SeparatorV(), 7, 8, 0, 1);
            grid.Children.Add(new Label { Text = "Custo Dia", TextColor = Color.Red, VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center }, 8, 9, 0, 1);
            grid.Children.Add(SeparatorV(), 9, 10, 0, 1);
            grid.Children.Add(new Label { Text = "Ult. Vencto", TextColor = Color.Red, VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center }, 10, 11, 0, 1);
            grid.Children.Add(SeparatorV(), 11, 12, 0, 1);
            grid.Children.Add(new Label { Text = "Total", TextColor = Color.Red, VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center }, 12, 13, 0, 1);
            grid.Children.Add(SeparatorV(), 13, 14, 0, 1);

            grid.Children.Add(SeparatorH(), 0, 14, 1, 2);

            // Create the ListView to visualize my data
            ListView lv = new ListView() { HasUnevenRows = true, SeparatorVisibility = SeparatorVisibility.None };
            lv.ItemsSource = _data;
            lv.ItemTemplate = new DataTemplate(typeof(ListViewTemplateGrid));

            StackLayout sl = new StackLayout() { Children = { grid, lv }, Spacing = 0 };

            this.Content = sl;
        }

This is the declaration of property _data at the beginning of the class:

List<ItensLib> _data { get; set; }
List<ItensLib> _itens ;
DataService dataService;

Here is the error screenshot (does not say anything), as I know _data is null , I think that's the problem:

EDIT1IoverwrittentheOnApperingmethodandremovedthecallandbuildoftheGridfromtheconstructorandswitchedtothismethod.AndintheLoadDatamethod,IpassedittoasyncTaskCarregaDados(intidorcamento);.WhathappensisthecallintheOnApperingofthismethodisgivingthiserror:

  

The'wait'operatorcanonlybeusedinanasynchronousmethod.

Seehowitwent:

protectedoverridevoidOnAppearing(){base.OnAppearing();awaitCarregaDados(IdOrcamento);**Aquidáerro**//Creteagridfor"title"
            Grid grid = CreateGrid();
            grid.Children.Add(new Label { Text = "Produto", TextColor = Color.Red, VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center }, 0, 1, 0, 1);
            grid.Children.Add(SeparatorV(), 1, 2, 0, 1);
            grid.Children.Add(new Label { Text = "Qtde", TextColor = Color.Red, VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center }, 2, 3, 0, 1);
            grid.Children.Add(SeparatorV(), 3, 4, 0, 1);
            grid.Children.Add(new Label { Text = "Unitário", TextColor = Color.Red, VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center }, 4, 5, 0, 1);
            grid.Children.Add(SeparatorV(), 5, 6, 0, 1);
            grid.Children.Add(new Label { Text = "Custo", TextColor = Color.Red, VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center }, 6, 7, 0, 1);
            grid.Children.Add(SeparatorV(), 7, 8, 0, 1);
            grid.Children.Add(new Label { Text = "Custo Dia", TextColor = Color.Red, VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center }, 8, 9, 0, 1);
            grid.Children.Add(SeparatorV(), 9, 10, 0, 1);
            grid.Children.Add(new Label { Text = "Ult. Vencto", TextColor = Color.Red, VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center }, 10, 11, 0, 1);
            grid.Children.Add(SeparatorV(), 11, 12, 0, 1);
            grid.Children.Add(new Label { Text = "Total", TextColor = Color.Red, VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center }, 12, 13, 0, 1);
            grid.Children.Add(SeparatorV(), 13, 14, 0, 1);

            grid.Children.Add(SeparatorH(), 0, 14, 1, 2);

            // Create the ListView to visualize my data
            ListView lv = new ListView() { HasUnevenRows = true, SeparatorVisibility = SeparatorVisibility.None };
            lv.ItemsSource = _data;
            lv.ItemTemplate = new DataTemplate(typeof(ListViewTemplateGrid));

            StackLayout sl = new StackLayout() { Children = { grid, lv }, Spacing = 0 };

            this.Content = sl;
        }

And the LoadData method:

async Task CarregaDados(int idorcamento)
        {
            _data = await dataService.GetItensLibAsync(idorcamento);
        }
    
asked by anonymous 10.09.2017 / 23:27

2 answers

2

According to the response of the comment, a possible solution follows:

On android check the following:

  • You must have the internet permission on the manifest;

  • Every internet call has to be made in an AsyncTask or any other background task. In your case, by the code, it is being done directly on the screen. Then I recommend creating an AsyncTask (not the Xamarin task, but the android class AsyncTask) and then make the call inside it. Here is an example class.

  • public class BgTask : AsyncTask<String, Java.Lang.Void, String> { /// <summary> /// Método que vai fazer a chamada em background /// </summary> protected override String RunInBackground(params string[] @params) { } /// <summary> /// Executado depois que o RunInBackground terminar, geralmente usado para retornar o resultado. /// </summary> protected override void OnPostExecute(string result) { } }

    Call this task

    new BgTask().execute("param");
    
        
    11.09.2017 / 14:00
    2

    The problem is that when your code arrives here:

    lv.ItemsSource = _data;
    

    ... the CarregaDados(idorcamento) method that was called some lines above has not yet executed, nor populated the _data variable. You need to wait for this method to finish its execution, for example:

    Task.Run(async () => await CarregaDados(idorcamento)).GetAwaiter().GetResult();
    

    This is a way to synchronously execute an asynchronous method, which is the case of CarregaDados .

        
    11.09.2017 / 14:09