1

No botão ACESSAR do Login do meu app ao ser clicado ele busca informações Json, no meu MacBook com Genymotion é acessado normalmente, mas quando vou utilizar o mesmo código no Windows (testei em dois deles) com Genymotion ele dá o seguinte erro:

inserir a descrição da imagem aqui

Se instalo no Smartphone pelo Windows ou pelo Macbook o acesso acontece normalmente quando clico em ACESSAR, gostaria de entender onde poderia estar o problema (dá a impressão de que seja de alguma maneira no Genymotion, até reinstalei e está a última versão dele e do VirtualBox.

Segue o 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>

Segue o Código:

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

Depois de colocar o erro Try/Catch (pedido abaixo nos comentários) o erro de retorno dele é o seguinte:

inserir a descrição da imagem aqui

6
  • 1
    Coloque um try/catch dentro da sua função do button. Talvez desta forma irá retornar o erro com mais detalhes
    – Tiago
    4/06/2018 às 12:48
  • Fiz a alteração do Try/Catch e editei no meu texto, se puderem dar uma olhada pra ver se estou errando em algo agora agradeço. @Diego, não posso desligar a internet, mas vamos ver se com o Try/Catch será possível. 4/06/2018 às 14:22
  • Enfim consegui utilizar o Try/Catch e já coloquei a mensagem que me retorna. 7/06/2018 às 13:04
  • Coloque também o método que você usa para fazer o Request 7/06/2018 às 19:29
  • Pronto, está lá como pedido. 7/06/2018 às 19:38

2 Respostas 2

1
+50

Acredito que o seu erro é falta de Internet na VM mesmo. Como você fez os testes em outros devices e deram certos, e como eu comentei na resposta acima, o seu código está certo. Então acredito que o problema é algo mais básico mesmo.

0

O seu código está correto, porém eu aconselho você a utilizar o GetStringAsync ao invés do 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;
}
8
  • Dá a mesma mensagem de erro quando chega na linha retorno = JsonConvert.DeserializeObject<Retorno>(result); 8/06/2018 às 16:41
  • O seu endpoint é get? Você que montou esta Web-API?
    – Tiago
    8/06/2018 às 16:51
  • Não entendi a pergunta do endpoint, se puder explanar melhor eu poderia conferir. Meu patrão quem montou a Web-API. 8/06/2018 às 17:02
  • Então você precisa ter certeza se este HTTP está como get, se você copia esta url no Browser ou no Postman: sibrati.com.br/foodsupply/valida_log_email_senha.php?ema={0}&sen={1} funciona?
    – Tiago
    8/06/2018 às 17:27
  • 1
    maravilhosa dica, abri o navegador do Genymotion e testei a net, não abriu nada, então modifiquei uma configuração pra ele pegar a net de minha placa de rede e funcionou. Coloque por favor esse último retorno seu como RESPOSTA pra eu poder definir como melhor resposta. 8/06/2018 às 20:15

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .