Error accessing JSON - Xamarin Forms

1

On the login button of my app when it is clicked it searches Json information, on my MacBook with Genymotion is accessed normally, but when I use the same code in Windows (I tested on two of them) with Genymotion it gives the following error :

IfIinstallontheSmartphonefromWindowsorMacbooktheaccesshappensnormallywhenIclickonACCESS,Iwouldliketounderstandwheretheproblemmightbe(itseemstobesomehowinGenymotion,Ievenreinstalledandit'sthelastversionofitandVirtualBox.

FollowXAML:

<AbsoluteLayout><GridAbsoluteLayout.LayoutBounds="0, 0, 1, 1"
          AbsoluteLayout.LayoutFlags="All" >

        <Grid.RowDefinitions>
            <!-- Define as linhas -->
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <BoxView Grid.Row="0"
                     BackgroundColor="Bisque"/>
        <BoxView Grid.Row="1"
                     BackgroundColor="Accent"/>
        <BoxView Grid.Row="2"
                     BackgroundColor="Aqua"/>
        <BoxView Grid.Row="3"
                     BackgroundColor="Beige"/>
        <BoxView Grid.Row="4"
                     BackgroundColor="Blue"/>

        <!-- Entry's -->
        <Entry Grid.Row="2"
                   x:Name="entryEmail" 
                   Text="[email protected]"
                   FontSize="Small"
                   VerticalOptions="StartAndExpand"/>
        <Entry Grid.Row="2"
                   x:Name="entrySenha" 
                   IsPassword="True"
                   Text="123456"
                   FontSize="Small"
                   VerticalOptions="CenterAndExpand"/>

        <!-- Botões -->
        <Button Grid.Row="3"
                Text="Cadastro"
                Clicked="btnCadastrarUserAsync"
                TextColor="White"
                HorizontalOptions="Start"
                VerticalOptions="StartAndExpand"
                FontSize="Small"
                BackgroundColor="DodgerBlue"
                Margin="0"/>
        <Button Grid.Row="3"
                x:Name="btnAcessar" 
                Clicked="btnAcessar_Clicked"
                HorizontalOptions="Center"
                VerticalOptions="StartAndExpand"
                Text="Acessar"
                TextColor="White"
                FontSize="Small"
                BackgroundColor="DodgerBlue"
                Margin="0"/>
        <Button Grid.Row="3"
                Text="Sair"
                Clicked="Sair_Clicked"
                HorizontalOptions="End"
                VerticalOptions="StartAndExpand"
                TextColor="White"
                FontSize="Small"
                BackgroundColor="DodgerBlue"
                Margin="0"/>
    </Grid>

    <!-- Loading -->
    <StackLayout IsVisible="{Binding IsLoading}" 
                 AbsoluteLayout.LayoutBounds="0, 0, 1, 1"
                 AbsoluteLayout.LayoutFlags="All"  
                 BackgroundColor="DodgerBlue" 
                 Opacity="0.5">

        <!-- Loading -->
        <ActivityIndicator x:Name="actInd"
                           IsRunning="{Binding IsLoading}"
                           IsVisible="{Binding IsLoading}"
                           Color="DarkBlue"
                           HeightRequest="60"
                           WidthRequest="60"
                           BackgroundColor="Transparent"
                           HorizontalOptions="CenterAndExpand"
                           VerticalOptions="CenterAndExpand">
        </ActivityIndicator>
    </StackLayout>

</AbsoluteLayout>

Follow the Code:

using Plugin.LocalNotifications;
using FoodSuppy.Classe;
using FoodSuppy.Classe_Interface;
using SQLite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using System.ComponentModel;

namespace FoodSuppy
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class Login : ContentPage, INotifyPropertyChanged
    {
        private int _vezesTimer;
        bool isLoading = false;     //Loading

        public Login()
        {
            InitializeComponent();

            //Para se utilizar o Binding
            BindingContext = this;

            //A cada 3 segundo envia uma notificação ao smartphone
            Device.StartTimer(TimeSpan.FromSeconds(3), () =>
            {
                CrossLocalNotifications.Current.Show("Título", "Bla bla blá");
                return true;
            });

            //A cada 1 segundo passa pela instrução IF

        }

        //Botão Logado/Não Logado
        private void OnToggledSwitch(object sender, ToggledEventArgs e)
        {
            bool swtLogado = e.Value;
        }

        //Botão Acessar
        async void btnAcessar_Clicked(object sender, EventArgs e)
        {
            var retorno = new Retorno();

            bool EmailVazio = string.IsNullOrEmpty(entryEmail.Text);
            bool SenhaVazia = string.IsNullOrEmpty(entrySenha.Text);

            //Campos Entry Vazios ou Não
            if ((EmailVazio == false) && (SenhaVazia == false))
            {
                //Loading
                IsLoading = true;

                retorno = await BuscarDados.BuscaInformacao(entryEmail.Text, entrySenha.Text);

                if (retorno.COD == "1")
                {
                    var login = new Login1();

                    login.EMAIL = entryEmail.Text;
                    login.SENHA = entrySenha.Text;
                    login.LOGADO = true;
                    login.ID_USUARIO = retorno.ID_RET;

                    new LoginDataAccess().InserirLogin(login);

                    IsLoading = false; //Loading

                    await Navigation.PushAsync(new Principal_Master(login.ID_USUARIO));
                }
                if (retorno.COD == "2")
                {
                    IsLoading = false; //Loading
                    await DisplayAlert("Confira", "Senha incorreta!", "Ok");
                }
                if (retorno.COD == "3")
                {
                    IsLoading = false; //Loading
                    await DisplayAlert("Confira", "E-mail não cadastrado!", "Ok");
                }
            }
            else if ((EmailVazio) && (SenhaVazia == false))
            {
                await DisplayAlert("Verificação", "Campo e-mail vazio, preencha!", "OK");
            }
            else if ((EmailVazio == false) && (SenhaVazia))
            {
                await DisplayAlert("Verificação", "Campo de senha vazio, preencha!", "OK");
            }
            else
            {
                await DisplayAlert("Verificação", "Campos de e-mail e senha vazios, preencha!", "OK");
            }
        }

        //Botão Cadastrar Usuário
       async Task btnCadastrarUserAsync(object sender, EventArgs e)
        {
            await Navigation.PushAsync(new CadastroUsuario("1", "0"));
        }

        //Botão Sair
        private async void Sair_Clicked(object sender, EventArgs e)
        {
            var result = await DisplayAlert("Alerta", "Deseja realmente sair?", "Sim", "Não");

            if (result) System.Diagnostics.Process.GetCurrentProcess().Kill();
        }

        //Loading
        public bool IsLoading
        {
            get
            {
                return isLoading;
            }
            set
            {
                isLoading = value;
                RaisePropertyChanged("IsLoading");
            }
        }

        //Continuando sobre Loading
        #pragma warning restore CS0108 // O membro oculta o membro herdado; nova palavra-chave ausente
        public void RaisePropertyChanged(string name)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(name));
        }

        #pragma warning disable CS0108 // O membro oculta o membro herdado; nova palavra-chave ausente
        public event PropertyChangedEventHandler PropertyChanged;
    }
}

JSON

' class BuscarDados
    {
        private static string UrlBase = "http://sibrati.com.br/foodsupply/valida_log_email_senha.php?ema={0}&sen={1}";

        public async static Task<Retorno> BuscaInformacao(string email, string senha)
        {
            string URL = string.Format(UrlBase, email, senha);

            HttpClient http = new HttpClient();

            var response = await http.GetAsync(URL);
            var content = await response.Content.ReadAsStringAsync();
            var retorno = JsonConvert.DeserializeObject<Retorno>(content);

            return retorno;
        }
    }'

After putting the Try / Catch error (request below in comments) the return error is as follows:

    
asked by anonymous 04.06.2018 / 14:34

2 answers

1

I believe your mistake is Internet shortage in the same VM. As you did the tests on other devices and gave them right, and as I commented in the answer above, your code is right. So I think the problem is something even more basic.

    
08.06.2018 / 22:39
0

Your code is correct, however I advise you to use GetStringAsync instead of GetAsync.

public async static Task<Retorno> BuscaInformacao(string email, string senha)
{
    HttpClient httpClient = new HttpClient();
    var retorno = new Retorno();

    try
    {
        var result = await httpClient.GetStringAsync(string.Format(UrlBase, email, senha));
        retorno = JsonConvert.DeserializeObject<Retorno>(result);
    }
    catch (Exception)
    {
        //Aqui você pode tratar a sua exception. Lembrando que o erro poderá ocorrer caso o usuário fique sem acesso à internet!
        return null;
    }
    finally
    {
        if (httpClient != null)
        {
            httpClient.Dispose();
            httpClient = null;
        }
    }

    return retorno;
}
    
08.06.2018 / 14:16