Forum Xamarin.Forms

System.NullReferenceException: 'Object reference not set to an instance of an object.'

ABloxityABloxity Member ✭✭✭

I am doing a navigation, but I always get the result that the navigation is null.

This is my code:

XAML:

            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <ViewCell.View>
                            <StackLayout Padding="10">

                                <ffimageloading:CachedImage
                                    HorizontalOptions="Start"
                                    Source="{Binding url_media_alimentacion}"
                                    LoadingPlaceholder="LoadImage"
                                    ErrorPlaceholder="ErrorImage"
                                    CacheDuration="50"
                                    RetryCount="3"
                                    RetryDelay="600"
                                    DownsampleToViewSize="True"
                                    WidthRequest="80" 
                                    HeightRequest="80">
                                    <ffimageloading:CachedImage.Transformations>
                                        <fftransformations:CircleTransformation/>
                                    </ffimageloading:CachedImage.Transformations>
                                </ffimageloading:CachedImage>

                                <Label
                                    Grid.Column="1"
                                    HorizontalOptions="FillAndExpand"
                                    Text="{Binding descripcion}" 
                                    FontSize="Medium"
                                    TextColor="Black"
                                    FontAttributes="Bold"/>

                                <StackLayout
                                    IsVisible="{Binding EsVisible}"
                                    Margin="0,0,80,0"
                                    Orientation="Horizontal">
                                    <Grid x:Name="Item">
                                        <Label
                                            HorizontalOptions="FillAndExpand"
                                            Text="{Binding descripcion_det}" 
                                            FontSize="Medium"
                                            TextColor="Black"
                                            FontAttributes="Bold"/>
                                        <Button
                                            BindingContext="{Binding Source={x:Reference ListaModuloAlimentacion}, Path=BindingContext}"   
                                            Command="{Binding NextPage}"   
                                            CommandParameter="{Binding Source={x:Reference Item}, Path=BindingContext}"
                                            Text="Iniciar"  
                                            WidthRequest="110"  
                                            FontSize="15"  
                                            BackgroundColor="Chocolate"  
                                            TextColor="White"/>
                                    </Grid>
                                </StackLayout>
                            </StackLayout>

                        </ViewCell.View>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

My viewModel:
public ICommand NextPage
{
get
{
try
{
return new Command(async (alimentacion) =>
{
await Application.Current.MainPage.Navigation.PushAsync(new AlimentacionVideosView(alimentacion.idalimentacion));
});
}
catch (Exception ex)
{
throw ex;
}
}
}

Answers

  • ABloxityABloxity Member ✭✭✭
    edited January 2020

    I am using VS 2019

    Xamarin.Forms 4.2.0.815419

  • LandLuLandLu Member, Xamarin Team Xamurai

    Did you put your current page in a navigation page? We normally create the MainPage like:

    public App()
    {
        InitializeComponent();
    
        // Wrapped by a navigation page
        MainPage = new NavigationPage(new MainPage());
    }
    

    Moreover, your current page which contains this list view may be not located in the same navigation stack as the MainPage of the Application. We could pass the current page's navigation to your view model at the initial time like:

    public class MainPageViewModel
    {
        INavigation _navigation;
        public MainPageViewModel(INavigation navigation)
        {
            _navigation = navigation;
        }
        ...
    }
    // Initialize
    BindingContext = new MainPageViewModel(this.Navigation);
    

    We could also check the value of the navigation there.

  • JohnHardmanJohnHardman GBUniversity admin

    @ABloxity

    Have you checked that:

    alimentacion is not null
    alimentacion.idalimentacion is not null
    new AlimentacionVideosView(alimentacion.idalimentacion) completes without throwing an exception
    Application.Current.MainPage is not null
    Application.Current.MainPage.Navigation is not null

  • ABloxityABloxity Member ✭✭✭

    @JohnHardman
    @LandLu

    Yes, but I see that it is always the Main navigation page that always appears in null.

    I am using a tapped page

  • JohnHardmanJohnHardman GBUniversity admin
    edited January 2020

    @ABloxity said:
    @JohnHardman
    @LandLu

    Yes, but I see that it is always the Main navigation page that always appears in null.

    I am using a tapped page

    You mean that Application.Current.MainPage.Navigation is null?

    If so, post your code where you create your main page, wrap it in NavigationPage and set MainPage

  • ABloxityABloxity Member ✭✭✭

    This is my main page with a tabbed page menu.

    and the second option in the menu is when I click on the icon to go to the next page.
    of the navigation where it goes null

    This code:
    <ContentPage.BindingContext>


    </ContentPage.BindingContext>

    <ContentPage.Content>
        <StackLayout IsVisible="True"
                Padding="10" 
                Spacing="10">
    
            <ListView
                    x:Name="ListaModuloAlimentacion"
                    SelectionMode="None"
                    ItemsSource="{Binding ListaModuloAlimentacion}"
                    IsRefreshing="{Binding IsRefreshing}"
                    RefreshCommand="{Binding RefreshAlimentacionCommand}"
                    IsPullToRefreshEnabled="True"
                    HasUnevenRows="True"
                    SeparatorVisibility="Default"
                    BackgroundColor="#f6f8f9"
                    Header="">
    
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <ViewCell.View>
                                <Grid x:Name="Item_funciones">
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="Auto"/>
                                        <ColumnDefinition Width="*"/>
                                    </Grid.ColumnDefinitions>
                                    <ffimageloading:CachedImage
                                        Grid.Column="0"
                                        HorizontalOptions="Start"
                                        Source="{Binding url_media_alimentacion}"
                                        LoadingPlaceholder="LoadImage"
                                        ErrorPlaceholder="ErrorImage"
                                        CacheDuration="50"
                                        RetryCount="3"
                                        RetryDelay="600"
                                        DownsampleToViewSize="True"
                                        WidthRequest="80" 
                                        HeightRequest="80">
                                        <ffimageloading:CachedImage.Transformations>
                                            <fftransformations:CircleTransformation/>
                                        </ffimageloading:CachedImage.Transformations>
                                    </ffimageloading:CachedImage>
                                    <Label 
                                        Grid.Column="1"
                                        HorizontalOptions="FillAndExpand"
                                        Text="{x:Binding descripcion}" 
                                        FontSize="Medium"
                                        TextColor="Black"
                                        FontAttributes="Bold"/>
                                    <Image
                                        Grid.Column="2"
                                        HorizontalOptions="End"
                                        Source="icon_next.png">
                                        <Image.GestureRecognizers>
                                            <TapGestureRecognizer
                                                BindingContext="{Binding Source={x:Reference ListaModuloAlimentacion}, Path=BindingContext}" 
                                                                    Command="{Binding SelectedMultimedia}"
                                                                    CommandParameter="{Binding Source={x:Reference Item_funciones}, Path=BindingContext}"/>
                                        </Image.GestureRecognizers>
                                    </Image>
                                </Grid>
                            </ViewCell.View>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </StackLayout>
    </ContentPage.Content>
    

    and other code in mvvm Command
    public ICommand SelectedMultimedia
    {
    get
    {
    try
    {
    return new Command(async (video) =>
    {
    await Application.Current.MainPage.Navigation.PushAsync(new Page2(video.idalimentacion)); <---------
    });
    }
    catch (Exception ex)
    {
    string xError = "Ocurrió un error al poblar los comentarios de la publicacion";
    if (bool.Parse(App.Current.Properties["IsDev"].ToString()))
    xError = ex.Message;

                    Application.Current.MainPage.DisplayAlert(
                                              "Error",
                                              xError,
                                              "Aceptar");
                    throw ex;
                }
            }
        }
    

    In this line where it is coming out that the navigation is null:
    await Application.Current.MainPage.Navigation.PushAsync(new Page2(video.idalimentacion));

  • ABloxityABloxity Member ✭✭✭
  • JohnHardmanJohnHardman GBUniversity admin

    @JohnHardman said:
    You mean that Application.Current.MainPage.Navigation is null?

    If so, post your code where you create your main page, wrap it in NavigationPage and set MainPage

    @ABloxity - You haven't posted what was requested.

  • ABloxityABloxity Member ✭✭✭

    @JohnHardman

    This is my page..

    and APP.xaml.cs

  • JohnHardmanJohnHardman GBUniversity admin

    @ABloxity

    Of the options that I posted previously, which are true and which are false? Please answer all for all five options.

    (1) alimentacion is not null
    (2) alimentacion.idalimentacion is not null
    (3) new AlimentacionVideosView(alimentacion.idalimentacion) completes without throwing an exception
    (4) Application.Current.MainPage is not null
    (5) Application.Current.MainPage.Navigation is not null

    I have to ask, as your statement "In this line where it is coming out that the navigation is null" is ambiguous.

  • ABloxityABloxity Member ✭✭✭

    @JohnHardman
    1. TRUE
    2. TRUE
    3. FALSE
    4. FALSE
    5. FALSE

  • JohnHardmanJohnHardman GBUniversity admin
    edited February 2020

    @ABloxity said:
    1. TRUE
    2. TRUE
    3. FALSE
    4. FALSE
    5. FALSE

    TBH, I'm not sure that is correct. It seems to contradict information provided in earlier posts.

    However, one step at a time...

    @ABloxity said:
    3. FALSE

    Use the debugger to debug the AlimentacionVideosView constructor (the one that takes an argument - AlimentacionVideosView(alimentacion.idalimentacion)). You have said that is throwing an exception. Until that exception is resolved, you won't be able to push the page.

    You haven't posted the source code of that constructor. If you cannot resolve the exception, post the source code of the AlimentacionVideosView constructor

  • ABloxityABloxity Member ✭✭✭

    This is my Command code to push the page:

    public Command SelectedMultimedia
    {
    get
    {
    try
    {
    return new Command(async (eliminar) =>
    {
    await App.Current.MainPage.Navigation.PushAsync(new Page2(eliminar.idalimentacion));
    });
    }
    catch (Exception ex)
    {
    string xError = "Ocurrió un error al darle like a la publicacion";
    if (bool.Parse(App.Current.Properties["IsDev"].ToString()))
    xError = ex.Message;

                    Application.Current.MainPage.DisplayAlert(
                                              "Error",
                                              xError,
                                              "Aceptar");
    
                    throw ex;
                }
            }
        }
    

    And this is the builder who receives it:

    namespace Kumer.View
    {
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class Page2 : ContentPage
    {
    public Page2(int idalimentacion)
    {
    InitializeComponent();

            pidAlimentacion.Text = idalimentacion.ToString();
            int id_alimentacion = Convert.ToInt32(pidAlimentacion.Text);
            var coment = BindingContext as listaVideosAlimentacion;
            coment?.GetListaVideos(id_alimentacion);
        }
    }
    

    }

  • JohnHardmanJohnHardman GBUniversity admin

    @JohnHardman said:
    Use the debugger to debug the AlimentacionVideosView constructor (the one that takes an argument - AlimentacionVideosView(alimentacion.idalimentacion)). You have said that is throwing an exception. Until that exception is resolved, you won't be able to push the page.

    @ABloxity - Have you debugged the Page2/AlimentacionVideosView constructor? If so, what exception is thrown and at what line?

  • ABloxityABloxity Member ✭✭✭

    @JohnHardman

    Debugging functions, there is no exception,
    but when I remove the breakpoints in the lines that I comment, that's where I get the exception, without debugging it is when the message comes out:

    System.NullReferenceException: 'Object reference not set to an instance of an object.'

  • ABloxityABloxity Member ✭✭✭

    @JohnHardman

    debug until the constructor of the Page2 arrives and without problems, but when removing the breakpoints, it is when there is the exception.

  • JohnHardmanJohnHardman GBUniversity admin

    @ABloxity said:
    Debugging functions, there is no exception,

    Please double check your answers to the questions. Your posts are contradictory. Without accurate answers it is impossible to help.

    @ABloxity said:
    1. TRUE
    2. TRUE
    3. FALSE
    4. FALSE
    5. FALSE

  • ABloxityABloxity Member ✭✭✭

    @JohnHardman

    1. TRUE
    2. TRUE
    3. FALSE
    4. TRUE
    5. TRUE
  • JohnHardmanJohnHardman GBUniversity admin

    @ABloxity said:
    @JohnHardman

    1. TRUE
    2. TRUE
    3. FALSE
    4. TRUE
    5. TRUE

    You are saying that new AlimentacionVideosView(alimentacion.idalimentacion) throws an exception.

    But you also said "Debugging functions, there is no exception".

    Were I sitting next to you, I'd be able to confirm which of those is true. However, responding to forum posts, I have to rely on accurate, unambiguous information, which I am not getting, so I am going to bow out of this thread.

    Perhaps, if you share your entire source code, one of the paid support team (e.g. @LandLu ) will take a look and work out what is going on?

Sign In or Register to comment.