Issue while populating ListView with data that comes from an url

rootxrootx Member ✭✭

This app gets the device coordinates, what can take some seconds. Then it makes a request to an url that does some calcs and echoes a string where each property is separated by ',' and each item by '/'.
So I split the result and use foreach to loop by the items. As you can imagine, it takes a while and before things are ok the UI is completed but the data is not binding since it's not done yet, and it gets worst, because some times the app crashs throwing "Array index out of bounds" exception, it's because the foreach is reached without had received the result of the url request. I almost forget, at android emulator it works, I think it's because it runs really slowlly here, so the delay to url response doesn't matter too much but at a real device the UI is very fast so this problem happens.
I lost about 3 days with this, I'm loosing my hair, I really would apreciate if anybody could help me on this. God bless you.

Example of data that comes from url:

3,Name1,25/1,Name2,39/5,Name3,52/4,Name4,360

XAML File:

    <ScrollView>
        <StackLayout Orientation="Horizontal">
            <ListView x:Name="ListViewLista" ItemsSource="{Binding .}" ItemTapped="ListViewLista_ItemTapped">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell Height="30">
                            <ViewCell.View>
                                <StackLayout BackgroundColor="#eee" Orientation="Vertical" HeightRequest="30">
                                    <StackLayout Orientation="Horizontal" HeightRequest="30" Padding="0,6,0,0">
                                        <Image Source="example_com/img.png" HeightRequest="30" WidthRequest="30" Margin="5,0,5,0" VerticalOptions="Center" />
                                        <Label Text="{Binding Nick}" HorizontalOptions="StartAndExpand" TextColor="Black" VerticalOptions="Center" />
                                        <Label Text="{Binding Distancia}" HorizontalOptions="EndAndExpand" TextColor="Black" Margin="0,0,8,0" VerticalOptions="Center" />
                                    </StackLayout>
                                </StackLayout>
                            </ViewCell.View>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </StackLayout>
    </ScrollView>

Code Behind .cs:

        public partial class Listar : ContentPage
        {
            public Listar ()
            {
                InitializeComponent();
            }

            protected override async void OnAppearing()
            {
                string resultRequest= await GetOnlineUsers();

                Usuarios ListaUsers = new Usuarios();
                BindingContext = await ListaUsers.GetDefaults(resultRequest.Split('/'));
            }

            public class Usuarios
            {
                public async Task<List<Usuario>> GetDefaults(string[] UsuariosArgList)
                {
                    List<Usuario> lista = new List<Usuario>();
                    int i = 0;
                    foreach(string each in UsuariosArgList)
                    {
                        string[] DataInfo = each.Split(',');
                        lista.Add(new Usuario(){
                            Index = i,
                            DatabaseDeviceId = int.Parse(DataInfo[0]),
                            Nick = DataInfo[1],
                            Distancia = DataInfo[2]
                        });
                        i++;

                       //for debug purpose Console.WriteLine(each);

                    }
                    return lista;
                }
            }

            public class Usuario
            {
                public int Index { get; set; }
                public int DatabaseDeviceId { get; set; }
                public string Nick { get; set; }
                public string Distancia { get; set; }
            }


            private async Task<string> GetOnlineUsers()
            {
                try
                {
                    using (WebClient browser = new WebClient())
                    {
                        string resultado = await browser.DownloadStringTaskAsync("example_com/getUsers.php?lat=" + GetLatitude() + "&lon=" + GetLongitude() + "&raiokm=20000.0");
                        return resultado;
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }

Best Answer

  • rootxrootx ✭✭
    edited October 2018 Accepted Answer

    Hey, @BillyLiu I found the error. Oh god! It was two things:

    1. Coordinates were being passed using comma not dot, so SQL was not being able to calculate it.

    2. return lista was inside the foreach{ }, what was an incredible mistake and passed by me due my fatigue.

    thank you!!!!

Answers

  • BillyLiuBillyLiu Member, Xamarin Team Xamurai

    @rootx
    Which line do you get this exception? I can't reproduce your issue on my real device. How many items do you receive in your string?
    I think you could try to use ListViewLista.ItemsSource instead of using BindingContext.

  • rootxrootx Member ✭✭
    edited October 2018

    @BillyLiu I tried to change from Binding to ItemsSource and also changed from List to ObservableCollection but no success. Did you tried that by getting the real coordinates from gps? I think the major problem is this, the app tries to get the coordinates but it takes a while and the await signature is not being enough to hold the execution until have a result, so it reachs the split and has nothing that it can do, so it throws the exception. A think the real point here is how can I wait for the tasks to be really done, the one that gets the gps coordinates and also the one that gets the data from url and then bind the data.

  • BillyLiuBillyLiu Member, Xamarin Team Xamurai

    @rootx

    I think the major problem is this, the app tries to get the coordinates but it takes a while and the await signature is not being enough to hold the execution until have a result, so it reachs the split and has nothing that it can do, so it throws the exception.

    I'm using await Task.Delay(10000); instead. And could not reproduce your issue. GetDefaults() will not be executed until you get the data string. Do you share your demo that can reproduce this issue?

  • rootxrootx Member ✭✭
    edited October 2018 Accepted Answer

    Hey, @BillyLiu I found the error. Oh god! It was two things:

    1. Coordinates were being passed using comma not dot, so SQL was not being able to calculate it.

    2. return lista was inside the foreach{ }, what was an incredible mistake and passed by me due my fatigue.

    thank you!!!!

  • rootxrootx Member ✭✭

    @BillyLiu I was able to get an exception of what is causing the error.

    10-24 11:11:11.806 E/mono-rt ( 5146): [ERROR] FATAL UNHANDLED EXCEPTION: System.NullReferenceException: Object reference not set to an instance of an object.
    10-24 11:11:11.806 E/mono-rt ( 5146): at BatePapo.Listar+Usuarios+d__0.MoveNext () [0x00008] in <884331ffab654d389a65d99c011f1db7>:0
    10-24 11:11:11.806 E/mono-rt ( 5146): --- End of stack trace from previous location where exception was thrown ---
    10-24 11:11:11.806 E/mono-rt ( 5146): at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in :0
    10-24 11:11:11.806 E/mono-rt ( 5146): at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in :0
    10-24 11:11:11.806 E/mono-rt ( 5146): at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in :0
    10-24 11:11:11.806 E/mono-rt ( 5146): at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in :0
    10-24 11:11:11.806 E/mono-rt ( 5146): at BatePapo.Listar+d__2.MoveNext () [0x00066] in <884331ffab654d389a65d99c011f1db7>:0
    10-24 11:11:11.806 E/mono-rt ( 5146): --- End of stack trace from previous location where exception was thrown ---
    10-24 11:11:11.806 E/mono-rt ( 5146): at (wrapper dynamic-method) System.Object.53(intptr,intptr)

    Since I already lost all my hair with this problem, I will post here the real code and url, LOL. Since now, thank you for your time. At emulator it works smoothly but at real device not(tested on motog5 and galaxy s6). Please also add the https www to the url because this forum has a block for new users.

    this is the file App.Xaml.Cs where the url is loaded:

    using System;
    using System.Net;
    using System.Threading.Tasks;
    using Xamarin.Essentials;
    using Xamarin.Forms;
    using Xamarin.Forms.Xaml;

    [assembly: XamlCompilation(XamlCompilationOptions.Compile)]
    namespace BatePapo
    {
    public partial class App : Application
    {
    Location pontos;
    public static string[] dataList;
    public App(Location coords)
    {
    pontos = coords;
    InitializeComponent();
    MainPage = new MainPage();
    }

        protected async override void OnStart()
        {
            try
            {
                WebClient browser = new WebClient();
                string resultado = await browser.DownloadStringTaskAsync("comprarmusicas.com.br/chat/getOnlineUsersClose.php?lat=" + pontos.Latitude + "&lon=" + pontos.Longitude + "&raiokm=20000.0");
                string[] dataList = resultado.Split('/');
            }
            catch(Exception)
            {
                throw;
            }
        }
    
        protected override void OnSleep() {}
        protected override void OnResume() {}
    }
    

    }

    Listar.Xaml is the same I posted before, it contains the ListView and binds the values.

    Listar.Xaml.Cs is the file where I populate the list:

    using System.Collections.ObjectModel;
    using Xamarin.Forms;
    using Xamarin.Forms.Xaml;
    using System.Threading.Tasks;
    using System;

    namespace BatePapo
    {
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class Listar : ContentPage
    {
    public Listar ()
    {
    InitializeComponent();
    }

        public class Usuario
        {
            public int Index { get; set; }
            public int DatabaseDeviceId { get; set; }
            public string Nick { get; set; }
            public string Distancia { get; set; }
        }
    
        protected override async void OnAppearing()
        {
            Usuarios ListaUsers = new Usuarios();
            BindingContext = Task.Run(() => { return ListaUsers.GetDefaults(); });
        }
    
        public class Usuarios
        {
            public async Task<ObservableCollection<Usuario>> GetDefaults()
            {
                ObservableCollection<Usuario> lista = new ObservableCollection<Usuario>();
                int i = 0;
    
                if (App.dataList.Length > 0)
                {
                    try
                    {
                        foreach (string each in App.dataList)
                        {
                            string[] DataInfo = each.Split(',');
                            lista.Add(new Usuario()
                            {
                                Index = i,
                                DatabaseDeviceId = int.Parse(DataInfo[0]),
                                Nick = DataInfo[1],
                                Distancia = DataInfo[2]
                            });
                            i++;
                        }
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }
                return lista;
            }
        }
    
        private void ListViewLista_ItemTapped(object sender, ItemTappedEventArgs e)
        {
            Usuario item = (Usuario)e.Item;
            DisplayAlert("Dialog",item.Nick,"ok");
        }
    
    }
    

    }

    This is the MainActivity.cs:

    using System;
    using System.Threading;
    using System.Threading.Tasks;
    using Xamarin.Essentials;
    using Android;
    using Android.App;
    using Android.Runtime;
    using Android.Widget;
    using Android.OS;
    using Android.Content.PM;
    using Android.Support.V4.App;

    namespace BatePapo.Droid
    {
    [Activity(Label = "BatePapo", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity, ActivityCompat.IOnRequestPermissionsResultCallback
    {
    protected async override void OnCreate(Bundle savedInstanceState)
    {
    await TryToGetPermissions();

                TabLayoutResource = Resource.Layout.Tabbar;
                ToolbarResource = Resource.Layout.Toolbar;
                base.OnCreate(savedInstanceState);
                global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
                Xamarin.Essentials.Platform.Init(this, savedInstanceState);
    
                var request = new GeolocationRequest(GeolocationAccuracy.Medium, TimeSpan.FromSeconds(30));
                CancellationTokenSource source = new CancellationTokenSource();
                CancellationToken cancelToken = source.Token;
                var pontos = await Geolocation.GetLocationAsync(request, cancelToken);
    
            // THIS LINE IS NOT BEING WRITED TO CONSOLE 
            Console.WriteLine("************************** Coords: "+pontos.Latitude+", "+pontos.Longitude);
    
            LoadApplication(new App(pontos));
    
        }
    
        #region RuntimePermissions
        async Task TryToGetPermissions()
        {
            if ((int)Build.VERSION.SdkInt >= 23)
            {
                await GetPermissionsAsync();
                return;
            }
        }
        const int RequestLocationId = 0;
    
        readonly string[] PermissionsGroupLocation =
        {
            Manifest.Permission.AccessCoarseLocation,
            Manifest.Permission.AccessFineLocation,
            Manifest.Permission.Internet,
            Manifest.Permission.AccessNetworkState
        };
    
        async Task GetPermissionsAsync()
        {
            const string permission = Manifest.Permission.AccessFineLocation;
    
            if (CheckSelfPermission(permission) == (int)Android.Content.PM.Permission.Granted)
            {
                //TODO change the message to show the permissions name
                Toast.MakeText(this, "Permissões concedidas.", ToastLength.Short).Show();
                return;
            }
    
            if (ShouldShowRequestPermissionRationale(permission))
            {
                //set alert for executing the task
                AlertDialog.Builder alert = new AlertDialog.Builder(this);
                alert.SetTitle("Permissões necessárias");
                alert.SetMessage("Esta aplicação precisa de permissões para continuar.");
                alert.SetPositiveButton("Conceder permissões", (senderAlert, args) =>
                {
                    RequestPermissions(PermissionsGroupLocation, RequestLocationId);
                });
    
                alert.SetNegativeButton("Cancelar", (senderAlert, args) =>
                {
                    Toast.MakeText(this, "Cancelado!", ToastLength.Short).Show();
                });
    
                Dialog dialog = alert.Create();
                dialog.Show();
                return;
            }
            RequestPermissions(PermissionsGroupLocation, RequestLocationId);
        }
    
        public override async void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
            switch (requestCode)
            {
                case RequestLocationId:
                    {
                        if (grantResults[0] == (int)Android.Content.PM.Permission.Granted)
                        {
                            Toast.MakeText(this, "Permissões concedidas.", ToastLength.Short).Show();
                        }
                        else
                        {
                            //Permission Denied :(
                            Toast.MakeText(this, "Permissões negadas.", ToastLength.Short).Show();
                        }
                    }
                    break;
            }
        }
        #endregion
    }
    

    }

  • rootxrootx Member ✭✭

    @BillyLiu I was able to get an exception of what is causing the error.

    10-24 11:11:11.806 E/mono-rt ( 5146): [ERROR] FATAL UNHANDLED EXCEPTION: System.NullReferenceException: Object reference not set to an instance of an object.
    10-24 11:11:11.806 E/mono-rt ( 5146): at BatePapo.Listar+Usuarios+d__0.MoveNext () [0x00008] in <884331ffab654d389a65d99c011f1db7>:0
    10-24 11:11:11.806 E/mono-rt ( 5146): --- End of stack trace from previous location where exception was thrown ---
    10-24 11:11:11.806 E/mono-rt ( 5146): at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in :0
    10-24 11:11:11.806 E/mono-rt ( 5146): at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in :0
    10-24 11:11:11.806 E/mono-rt ( 5146): at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in :0
    10-24 11:11:11.806 E/mono-rt ( 5146): at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in :0
    10-24 11:11:11.806 E/mono-rt ( 5146): at BatePapo.Listar+d__2.MoveNext () [0x00066] in <884331ffab654d389a65d99c011f1db7>:0
    10-24 11:11:11.806 E/mono-rt ( 5146): --- End of stack trace from previous location where exception was thrown ---
    10-24 11:11:11.806 E/mono-rt ( 5146): at (wrapper dynamic-method) System.Object.53(intptr,intptr)

    Since I already lost all my hair with this problem, I will post here the real code and url, LOL. Since now, thank you for your time. At emulator it works smoothly but at real device not(tested on motog5 and galaxy s6). Please also add the https www to the url because this forum has a block for new users.

    this is the file App.Xaml.Cs where the url is loaded:

    using System;
    using System.Net;
    using System.Threading.Tasks;
    using Xamarin.Essentials;
    using Xamarin.Forms;
    using Xamarin.Forms.Xaml;

    [assembly: XamlCompilation(XamlCompilationOptions.Compile)]
    namespace BatePapo
    {
    public partial class App : Application
    {
    Location pontos;
    public static string[] dataList;
    public App(Location coords)
    {
    pontos = coords;
    InitializeComponent();
    MainPage = new MainPage();
    }

        protected async override void OnStart()
        {
            try
            {
                WebClient browser = new WebClient();
                string resultado = await browser.DownloadStringTaskAsync("comprarmusicas.com.br/chat/getOnlineUsersClose.php?lat=" + pontos.Latitude + "&lon=" + pontos.Longitude + "&raiokm=20000.0");
                string[] dataList = resultado.Split('/');
            }
            catch(Exception)
            {
                throw;
            }
        }
    
        protected override void OnSleep() {}
        protected override void OnResume() {}
    }
    

    }

    Listar.Xaml is the same I posted before, it contains the ListView and binds the values.

    Listar.Xaml.Cs is the file where I populate the list:

    using System.Collections.ObjectModel;
    using Xamarin.Forms;
    using Xamarin.Forms.Xaml;
    using System.Threading.Tasks;
    using System;

    namespace BatePapo
    {
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class Listar : ContentPage
    {
    public Listar ()
    {
    InitializeComponent();
    }

        public class Usuario
        {
            public int Index { get; set; }
            public int DatabaseDeviceId { get; set; }
            public string Nick { get; set; }
            public string Distancia { get; set; }
        }
    
        protected override async void OnAppearing()
        {
            Usuarios ListaUsers = new Usuarios();
            BindingContext = Task.Run(() => { return ListaUsers.GetDefaults(); });
        }
    
        public class Usuarios
        {
            public async Task<ObservableCollection<Usuario>> GetDefaults()
            {
                ObservableCollection<Usuario> lista = new ObservableCollection<Usuario>();
                int i = 0;
    
                if (App.dataList.Length > 0)
                {
                    try
                    {
                        foreach (string each in App.dataList)
                        {
                            string[] DataInfo = each.Split(',');
                            lista.Add(new Usuario()
                            {
                                Index = i,
                                DatabaseDeviceId = int.Parse(DataInfo[0]),
                                Nick = DataInfo[1],
                                Distancia = DataInfo[2]
                            });
                            i++;
                        }
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }
                return lista;
            }
        }
    
        private void ListViewLista_ItemTapped(object sender, ItemTappedEventArgs e)
        {
            Usuario item = (Usuario)e.Item;
            DisplayAlert("Dialog",item.Nick,"ok");
        }
    
    }
    

    }

    This is the MainActivity.cs:

    using System;
    using System.Threading;
    using System.Threading.Tasks;
    using Xamarin.Essentials;
    using Android;
    using Android.App;
    using Android.Runtime;
    using Android.Widget;
    using Android.OS;
    using Android.Content.PM;
    using Android.Support.V4.App;

    namespace BatePapo.Droid
    {
    [Activity(Label = "BatePapo", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity, ActivityCompat.IOnRequestPermissionsResultCallback
    {
    protected async override void OnCreate(Bundle savedInstanceState)
    {
    await TryToGetPermissions();

                TabLayoutResource = Resource.Layout.Tabbar;
                ToolbarResource = Resource.Layout.Toolbar;
                base.OnCreate(savedInstanceState);
                global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
                Xamarin.Essentials.Platform.Init(this, savedInstanceState);
    
                var request = new GeolocationRequest(GeolocationAccuracy.Medium, TimeSpan.FromSeconds(30));
                CancellationTokenSource source = new CancellationTokenSource();
                CancellationToken cancelToken = source.Token;
                var pontos = await Geolocation.GetLocationAsync(request, cancelToken);
    
            // THIS LINE IS NOT BEING WRITED TO CONSOLE 
            Console.WriteLine("************************** Coords: "+pontos.Latitude+", "+pontos.Longitude);
    
            LoadApplication(new App(pontos));
    
        }
    
        #region RuntimePermissions
        async Task TryToGetPermissions()
        {
            if ((int)Build.VERSION.SdkInt >= 23)
            {
                await GetPermissionsAsync();
                return;
            }
        }
        const int RequestLocationId = 0;
    
        readonly string[] PermissionsGroupLocation =
        {
            Manifest.Permission.AccessCoarseLocation,
            Manifest.Permission.AccessFineLocation,
            Manifest.Permission.Internet,
            Manifest.Permission.AccessNetworkState
        };
    
        async Task GetPermissionsAsync()
        {
            const string permission = Manifest.Permission.AccessFineLocation;
    
            if (CheckSelfPermission(permission) == (int)Android.Content.PM.Permission.Granted)
            {
                //TODO change the message to show the permissions name
                Toast.MakeText(this, "Permissões concedidas.", ToastLength.Short).Show();
                return;
            }
    
            if (ShouldShowRequestPermissionRationale(permission))
            {
                //set alert for executing the task
                AlertDialog.Builder alert = new AlertDialog.Builder(this);
                alert.SetTitle("Permissões necessárias");
                alert.SetMessage("Esta aplicação precisa de permissões para continuar.");
                alert.SetPositiveButton("Conceder permissões", (senderAlert, args) =>
                {
                    RequestPermissions(PermissionsGroupLocation, RequestLocationId);
                });
    
                alert.SetNegativeButton("Cancelar", (senderAlert, args) =>
                {
                    Toast.MakeText(this, "Cancelado!", ToastLength.Short).Show();
                });
    
                Dialog dialog = alert.Create();
                dialog.Show();
                return;
            }
            RequestPermissions(PermissionsGroupLocation, RequestLocationId);
        }
    
        public override async void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
            switch (requestCode)
            {
                case RequestLocationId:
                    {
                        if (grantResults[0] == (int)Android.Content.PM.Permission.Granted)
                        {
                            Toast.MakeText(this, "Permissões concedidas.", ToastLength.Short).Show();
                        }
                        else
                        {
                            //Permission Denied :(
                            Toast.MakeText(this, "Permissões negadas.", ToastLength.Short).Show();
                        }
                    }
                    break;
            }
        }
        #endregion
    }
    

    }

  • rootxrootx Member ✭✭

    @BillyLiu I was able to get an exception of what is causing the error.

    10-24 11:11:11.806 E/mono-rt ( 5146): [ERROR] FATAL UNHANDLED EXCEPTION: System.NullReferenceException: Object reference not set to an instance of an object.
    10-24 11:11:11.806 E/mono-rt ( 5146): at BatePapo.Listar+Usuarios+d__0.MoveNext () [0x00008] in <884331ffab654d389a65d99c011f1db7>:0
    10-24 11:11:11.806 E/mono-rt ( 5146): --- End of stack trace from previous location where exception was thrown ---
    10-24 11:11:11.806 E/mono-rt ( 5146): at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in :0
    10-24 11:11:11.806 E/mono-rt ( 5146): at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in :0
    10-24 11:11:11.806 E/mono-rt ( 5146): at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in :0
    10-24 11:11:11.806 E/mono-rt ( 5146): at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in :0
    10-24 11:11:11.806 E/mono-rt ( 5146): at BatePapo.Listar+d__2.MoveNext () [0x00066] in <884331ffab654d389a65d99c011f1db7>:0
    10-24 11:11:11.806 E/mono-rt ( 5146): --- End of stack trace from previous location where exception was thrown ---
    10-24 11:11:11.806 E/mono-rt ( 5146): at (wrapper dynamic-method) System.Object.53(intptr,intptr)

    Since I already lost all my hair with this problem, I will post here the real code and url, LOL. Since now, thank you for your time. At emulator it works smoothly but at real device not(tested on motog5 and galaxy s6). Please also add the https www to the url because this forum has a block for new users.

    this is the file App.Xaml.Cs where the url is loaded:

    using System;
    using System.Net;
    using System.Threading.Tasks;
    using Xamarin.Essentials;
    using Xamarin.Forms;
    using Xamarin.Forms.Xaml;

    [assembly: XamlCompilation(XamlCompilationOptions.Compile)]
    namespace BatePapo
    {
    public partial class App : Application
    {
    Location pontos;
    public static string[] dataList;
    public App(Location coords)
    {
    pontos = coords;
    InitializeComponent();
    MainPage = new MainPage();
    }

        protected async override void OnStart()
        {
            try
            {
                WebClient browser = new WebClient();
                string resultado = await browser.DownloadStringTaskAsync("comprarmusicas.com.br/chat/getOnlineUsersClose.php?lat=" + pontos.Latitude + "&lon=" + pontos.Longitude + "&raiokm=20000.0");
                string[] dataList = resultado.Split('/');
            }
            catch(Exception)
            {
                throw;
            }
        }
    
        protected override void OnSleep() {}
        protected override void OnResume() {}
    }
    

    }

    Listar.Xaml is the same I posted before, it contains the ListView and binds the values.

    Listar.Xaml.Cs is the file where I populate the list:

    using System.Collections.ObjectModel;
    using Xamarin.Forms;
    using Xamarin.Forms.Xaml;
    using System.Threading.Tasks;
    using System;

    namespace BatePapo
    {
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class Listar : ContentPage
    {
    public Listar ()
    {
    InitializeComponent();
    }

        public class Usuario
        {
            public int Index { get; set; }
            public int DatabaseDeviceId { get; set; }
            public string Nick { get; set; }
            public string Distancia { get; set; }
        }
    
        protected override async void OnAppearing()
        {
            Usuarios ListaUsers = new Usuarios();
            BindingContext = Task.Run(() => { return ListaUsers.GetDefaults(); });
        }
    
        public class Usuarios
        {
            public async Task<ObservableCollection<Usuario>> GetDefaults()
            {
                ObservableCollection<Usuario> lista = new ObservableCollection<Usuario>();
                int i = 0;
    
                if (App.dataList.Length > 0)
                {
                    try
                    {
                        foreach (string each in App.dataList)
                        {
                            string[] DataInfo = each.Split(',');
                            lista.Add(new Usuario()
                            {
                                Index = i,
                                DatabaseDeviceId = int.Parse(DataInfo[0]),
                                Nick = DataInfo[1],
                                Distancia = DataInfo[2]
                            });
                            i++;
                        }
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }
                return lista;
            }
        }
    
        private void ListViewLista_ItemTapped(object sender, ItemTappedEventArgs e)
        {
            Usuario item = (Usuario)e.Item;
            DisplayAlert("Dialog",item.Nick,"ok");
        }
    
    }
    

    }

    This is the MainActivity.cs:

    using System;
    using System.Threading;
    using System.Threading.Tasks;
    using Xamarin.Essentials;
    using Android;
    using Android.App;
    using Android.Runtime;
    using Android.Widget;
    using Android.OS;
    using Android.Content.PM;
    using Android.Support.V4.App;

    namespace BatePapo.Droid
    {
    [Activity(Label = "BatePapo", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity, ActivityCompat.IOnRequestPermissionsResultCallback
    {
    protected async override void OnCreate(Bundle savedInstanceState)
    {
    await TryToGetPermissions();

                TabLayoutResource = Resource.Layout.Tabbar;
                ToolbarResource = Resource.Layout.Toolbar;
                base.OnCreate(savedInstanceState);
                global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
                Xamarin.Essentials.Platform.Init(this, savedInstanceState);
    
                var request = new GeolocationRequest(GeolocationAccuracy.Medium, TimeSpan.FromSeconds(30));
                CancellationTokenSource source = new CancellationTokenSource();
                CancellationToken cancelToken = source.Token;
                var pontos = await Geolocation.GetLocationAsync(request, cancelToken);
    
            // THIS LINE IS NOT BEING WRITED TO CONSOLE 
            Console.WriteLine("************************** Coords: "+pontos.Latitude+", "+pontos.Longitude);
    
            LoadApplication(new App(pontos));
    
        }
    
        #region RuntimePermissions
        async Task TryToGetPermissions()
        {
            if ((int)Build.VERSION.SdkInt >= 23)
            {
                await GetPermissionsAsync();
                return;
            }
        }
        const int RequestLocationId = 0;
    
        readonly string[] PermissionsGroupLocation =
        {
            Manifest.Permission.AccessCoarseLocation,
            Manifest.Permission.AccessFineLocation,
            Manifest.Permission.Internet,
            Manifest.Permission.AccessNetworkState
        };
    
        async Task GetPermissionsAsync()
        {
            const string permission = Manifest.Permission.AccessFineLocation;
    
            if (CheckSelfPermission(permission) == (int)Android.Content.PM.Permission.Granted)
            {
                //TODO change the message to show the permissions name
                Toast.MakeText(this, "Permissões concedidas.", ToastLength.Short).Show();
                return;
            }
    
            if (ShouldShowRequestPermissionRationale(permission))
            {
                //set alert for executing the task
                AlertDialog.Builder alert = new AlertDialog.Builder(this);
                alert.SetTitle("Permissões necessárias");
                alert.SetMessage("Esta aplicação precisa de permissões para continuar.");
                alert.SetPositiveButton("Conceder permissões", (senderAlert, args) =>
                {
                    RequestPermissions(PermissionsGroupLocation, RequestLocationId);
                });
    
                alert.SetNegativeButton("Cancelar", (senderAlert, args) =>
                {
                    Toast.MakeText(this, "Cancelado!", ToastLength.Short).Show();
                });
    
                Dialog dialog = alert.Create();
                dialog.Show();
                return;
            }
            RequestPermissions(PermissionsGroupLocation, RequestLocationId);
        }
    
        public override async void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
            switch (requestCode)
            {
                case RequestLocationId:
                    {
                        if (grantResults[0] == (int)Android.Content.PM.Permission.Granted)
                        {
                            Toast.MakeText(this, "Permissões concedidas.", ToastLength.Short).Show();
                        }
                        else
                        {
                            //Permission Denied :(
                            Toast.MakeText(this, "Permissões negadas.", ToastLength.Short).Show();
                        }
                    }
                    break;
            }
        }
        #endregion
    }
    

    }

Sign In or Register to comment.