Home > OS >  Xamarin System.NullReferenceException: 'Object reference not set to an instance of an object.&#
Xamarin System.NullReferenceException: 'Object reference not set to an instance of an object.&#

Time:05-20

I do not understand why when I try to log in, the program returns a System.NullReferenceException, when I perform a check to prevent the values entered from being null

Here's the model:

using Newtonsoft.Json;

namespace StockingApp.Models
{
public class LoginModel
{
    [JsonProperty("email")]
    public string Email { get; set; }

    [JsonProperty("password")]
    public string Password { get; set; }
  }
}

Here's the code I use to sign in:

private async void loginButton_Clicked(object sender, EventArgs e)
    {
        LoginModel log = new LoginModel
        {
            Email = txtEmail.Text,
            Password = txtPassword.Text
        };

        if (txtEmail.Text != null | txtPassword.Text != null)
        {
            Uri RequestUri = new Uri("The url of the Api");

            var client = new HttpClient();
            var json = JsonConvert.SerializeObject(log);
            var contentJson = new StringContent(json, Encoding.UTF8, "application/json");
            //this is the line that causes the exception
            var response = await client.PostAsync(RequestUri, contentJson);

            if (response.IsSuccessStatusCode)
            {
                await DisplayAlert("Iniciar Sesión", "El inicio de sesión se realizó correctamente", "Ok");
            }
            else
            {
                await DisplayAlert("Error", "Los datos introducidos son incorrectos", "Ok");
            }
        }
        else
        {
            await DisplayAlert("Error", "Faltan datos por introducir", "Ok");
        }
    }

This is the line that cause the exception, i don't understand why response is null

var response = await client.PostAsync(RequestUri, contentJson);

Here's the Xaml & How the Xaml looks: How it looks

<ContentPage.Content>
    <StackLayout Spacing="5" Padding="10" VerticalOptions="Center">
    <Entry x:Name="txtEmail" Placeholder="{translator:Translate prompt_email}" Style="{StaticResource entryStyles}"/>
    <Entry x:Name="txtPassword" Placeholder="{translator:Translate prompt_password}" Style="{StaticResource entryStyles}" IsPassword="True"/>
    <Button x:Name="loginButton" Text="{translator:Translate title_activity_login}" Style="{StaticResource buttonStyles}" Clicked="loginButton_Clicked"/>
    <Label  Text="{translator:Translate tit_contacto}" HorizontalTextAlignment="Center"/>
    <Label x:Name="link" Margin="20" HorizontalOptions="Center">
        <Label.FormattedText>
            <FormattedString>
                <Span Text="www.atecresa.com"  TextColor="GreenYellow" TextDecorations="Underline">
                    <Span.GestureRecognizers>
                        <TapGestureRecognizer Command="{Binding TapCommand}"
                                      CommandParameter="https://atecresa.com" NumberOfTapsRequired="1"/>
                    </Span.GestureRecognizers>
                </Span>
            </FormattedString>
        </Label.FormattedText>
    </Label>
</StackLayout>
</ContentPage.Content>

This is the swagger to log in: Swagger of the api

I did a check on Postman and the api works properly: Postman check

CodePudding user response:

I have a similar error, i just change the http of the url to https. I think thats the problem here.

CodePudding user response:

Maybe try this

if (txtEmail.Text != null && txtPassword.Text != null)
  • Related