Error accessing JSON - Xamarin Forms

Asked

Viewed 122 times

1

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

inserir a descrição da imagem aqui

If I install on Smartphone by Windows or Macbook the access usually happens when I click ACCESS, I would like to understand where the problem might be (it gives the impression that it is somehow in Genymotion, until reinstalled and is the latest version of it and Virtualbox.

Follows the XAML:

<AbsoluteLayout>
    <Grid AbsoluteLayout.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>

Follows 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 placing the Try/Catch error (requested below in the comments) its return error is as follows:

inserir a descrição da imagem aqui

  • 1

    Place a Try/catch inside your button function. Maybe this way will return the error with more details

  • I made the change to Try/Catch and edited in my text, if you can take a look to see if I’m missing something now thank you. @Diego, I can’t turn off the internet, but let’s see if Try/Catch is possible.

  • Finally I managed to use Try/Catch and I’ve put the message that returns.

  • Also put the method you use to do Request

  • All right, it’s there as request.

  • I edited my answer with a code that compiles

Show 1 more comment

2 answers

1


I believe your mistake is lack of Internet in the VM itself. As you did the tests on other Vices and they were right, and as I commented in the answer above, your code is right. So I think the problem is something more basic.

0

Your code is correct, but 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;
}
  • Gives the same error message when it reaches the line retorno = JsonConvert.DeserializeObject<Retorno>(result);

  • Is your endpoint get? You set up this Web-API?

  • I didn’t understand the endpoint question, if I can explain it better I could check. My boss who set up the Web-API.

  • Then you need to make sure that this HTTP is as get, if you copy this url in Browser or Postman: http://sibrati.com.br/foodsupply/valida_log_email_senha.php?ema={0}&sen={1} works?

  • Yes, normally, only {0} is replaced by a valid email and {1} is replaced by a valid password, placed by the client in Entry’s from the Login screen. On my Mac everything accesses normally for example, from Smartphone too.

  • I suspect that your VM is without Internet or something like that. If it works on your mobile it is very likely that this is it

  • I suspect that your VM is without Internet or something like that. If it works on your mobile it is very likely that this is it

  • 1

    wonderful tip, I opened the Genymotion browser and tested the net, opened nothing, so I modified a configuration to get the net from my network card and it worked. Please put this last return of yours as ANSWER so I can define as the best answer.

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.