0
votes

I have a couple of text fields in my app and I want an error message to show up when the length of text is less than 1, so basically when there is no text placed in the text fields. But when I test this out, the app crashes.

Here's the code in both Xaml and C# (code behind)

XAML:

    <?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns:sys="clr-namespace:System;assembly=mscorlib"
    xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="RoseySports.Create_Activity" Title="Create Activity">

        <AbsoluteLayout VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">

        <Image AbsoluteLayout.LayoutFlags="All" AbsoluteLayout.LayoutBounds="0, 0, 1, 1"
               Source="background.jpg" Aspect="AspectFill"/>

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

                <ContentView Padding="0, 40, 0, 0">

                    <Label Text="Create Activity" FontSize="25" TextColor="White" VerticalOptions="StartAndExpand" HorizontalOptions="CenterAndExpand"/>

                </ContentView>

                <StackLayout VerticalOptions="Center" HorizontalOptions="Center" Padding="10, 0, 10, 0">

                    <Grid RowSpacing="50" ColumnSpacing="20" HorizontalOptions="Center" VerticalOptions="Center" Padding="10, 0, 10, 0">

                        <Label Grid.Row="0" Grid.Column="0" Text="Activity Title" TextColor="White" FontSize="20" HorizontalOptions="Center" VerticalOptions="Center"/>
                        <Entry Grid.Row="0" Grid.Column="1" WidthRequest="200" HorizontalOptions="Center" VerticalOptions="Center" x:Name="title"/>
                        <Label Grid.Row="1" Grid.Column="0" Text="Date" TextColor="White" FontSize="20" HorizontalOptions="Center" VerticalOptions="Center"/>
                        <DatePicker Grid.Row="1" Grid.Column="1" Format="d MMM yyyy" x:Name="minDate"/>
                        <Label Grid.Row="2" Grid.Column="0" Text="Place" TextColor="White" FontSize="20" HorizontalOptions="Center" VerticalOptions="Center"/>
                        <Picker x:Name="fieldPicker" Grid.Row="2" Grid.Column="1" HorizontalOptions="Center" VerticalOptions="Center"/>
                        <Label Grid.Row="3" Grid.Column="0" Text="Time" TextColor="White" FontSize="20" HorizontalOptions="Center" VerticalOptions="Center"/>
                        <TimePicker Grid.Row="3" Grid.Column="1" HorizontalOptions="Center" VerticalOptions="Center"/>
                    </Grid>

                    <Label Text="Activity Description" TextColor="White" FontSize="20" Margin="20" HorizontalOptions="Center"/>
                    <Editor HeightRequest="100" WidthRequest="300" x:Name="description"/>

                <Grid VerticalOptions="End" Padding="10, 10, 10, 10">
                    <Button Grid.Row="0" Grid.Column="0" Text="Return To Home" Clicked="Handle_Clicked" FontSize="20" TextColor="White" HorizontalOptions="Start"/>
                    <Button Grid.Row="0" Grid.Column="1" Text="Invite" Clicked="Handle_Clicked_1" FontSize="20" HorizontalOptions="End" TextColor="White"/>
                </Grid>
                </StackLayout>

            </ScrollView>
        </AbsoluteLayout>
</ContentPage>

C#:

using System;
using System.Collections.Generic;

using Xamarin.Forms;

namespace RoseySports
{
    public partial class Create_Activity : ContentPage
    {

        public Create_Activity()
        {
            InitializeComponent();

            String[] place = {

                "Agostinelli Football Field",
                "Tennis Court 1 (Rosey)",
                "Tennis Court 2 (Rosey)",
                "Tennis Court 3 (Rosey)",
                "Tennis Court 4 (Rosey)",
                "Tennis Court 5 (Rosey)",
                "Tennis Court 6 (Rosey)",
                "Gymnasium (Rosey)",
                "Gymasium (La Combe)",
                "Fitness Room (Rosey)",
                "Fitness Room (La Combe)",
                "Judo Room (La Combe)",
                "Swimming Pool (Rosey)",
                "Swimming Pool (La Combe)",
                "Basketball Court (Rosey)",
                "Basketball Court (La Combe)",
                "Rugby Field (Rosey)"

            };

            minDate.SetValue(DatePicker.MinimumDateProperty, DateTime.Now);

            for (int i = 0; i < place.Length; i++)
            {

                fieldPicker.Items.Add(place[i]);
            }
        }

        private async void Handle_Clicked_1(object sender, System.EventArgs e)
        {
            if (title.Text.Length < 1
                && description.Text.Length < 1)
            {
                await DisplayAlert("Error", "Make sure all fields are completed", "OK");

            } else {

                await Navigation.PushModalAsync(new Invite_Page());

            }

        }

        private async void Handle_Clicked(object sender, System.EventArgs e)
        {
            await Navigation.PushModalAsync(new Home());
        }
    }
}

The most important bit is this:

private async void Handle_Clicked_1(object sender, System.EventArgs e)
            {
                if (title.Text.Length < 1
                    && description.Text.Length < 1)
                {
                    await DisplayAlert("Error", "Make sure all fields are completed", "OK");

                } else {

                    await Navigation.PushModalAsync(new Invite_Page());

                }

I get this error when I try leaving the text boxes empty:

System.NullReferenceException has been thrown

Object reference not set to an instance of an object

This is the stacktrace:

" at RoseySports.Create_Activity+d__1.MoveNext () [0x0001d] in /Users/als-moh/Desktop/School/Le Rosey/Class 1 & T/SL/CS/IA/RoseySports/RoseySports/Create_Activity.xaml.cs:48 \n--- End of stack trace from previous location where exception was thrown ---\n at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.b__6_0 (System.Object state) [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.0.0.15/src/Xamarin.iOS/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/AsyncMethodBuilder.cs:1018 \n at Foundation.NSAsyncSynchronizationContextDispatcher.Apply () [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.0.0.15/src/Xamarin.iOS/Foundation/NSAction.cs:178 \n--- End of stack trace from previous location where exception was thrown ---\n at (wrapper managed-to-native) UIKit.UIApplication.UIApplicationMain(int,string[],intptr,intptr)\n at UIKit.UIApplication.Main (System.String[] args, System.IntPtr principal, System.IntPtr delegate) [0x00005] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.0.0.15/src/Xamarin.iOS/UIKit/UIApplication.cs:79 \n at UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x0002c] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.0.0.15/src/Xamarin.iOS/UIKit/UIApplication.cs:63 \n at RoseySports.iOS.Application.Main (System.String[] args) [0x00001] in /Users/als-moh/Desktop/School/Le Rosey/Class 1 & T/SL/CS/IA/RoseySports/iOS/Main.cs:17 "

2
Any exceptions? Could you please post the full stacktrace?Rui Jarimba
@SeM I don't think this applies to my issueMohamed Al Sabbagh
title.Text is null ? or just empty ?Greggz
@Greggz just emptyMohamed Al Sabbagh

2 Answers

1
votes

You should do null check for title.Text and description.Text. Because the value will be null if the text is empty for the entry control. Hence the app gets crash when you try to access the length property since it is null.

if(string.IsNullOrEmpty(title.Text) || string.IsNullOrEmpty(description.Text))
{
   await DisplayAlert("Error", "Make sure all fields are completed", "OK");
}

I coded OR (||) comparison in if loop because, if any of the field is empty, the error alert should be thrown as you want all the fields need to be completed

0
votes
if (title.Text == null && description.Text == null)
        {
            await DisplayAlert("Error", "Make sure all fields are completed", "OK");

        }

Because the Entry and Editor text property is a String, they are null when empty and length cannot check whether it's a null or not.