1

I'm making a UWP app that allows the user to add songs to a playlist and then play a song in the playlist. But when I run the app and click on a song, the song plays but it throws a System.NullReferenceException. My XAML looks like this:

    <Grid>
    <MediaPlayerElement x:Name="mediaPlayerElement" AreTransportControlsEnabled="True" AutoPlay="True" HorizontalAlignment="Center" VerticalAlignment="Top" Width="830" Margin="0,36,0,0" Height="352">
        <MediaPlayerElement.TransportControls>
            <MediaTransportControls IsFastForwardButtonVisible="True"
                                    IsFastForwardEnabled="True"
                                    IsFastRewindButtonVisible="True"
                                    IsFastRewindEnabled="True"
                                    IsFullWindowButtonVisible="False"
                                    IsFullWindowEnabled="False">
            </MediaTransportControls>
        </MediaPlayerElement.TransportControls>
    </MediaPlayerElement>
    <AppBarButton Name="addSong" Icon="Add" Label="Add to Playlist" Click="AddToPlaylist" HorizontalAlignment="Center" Margin="0,417,0,0" VerticalAlignment="Top" Width="84"/>
    <ListView
        x:Name="playlist"
        Height="200"
        Width="850"
        Margin="216,510,214,10" HorizontalAlignment="Stretch"
        IsItemClickEnabled="True"
        Tapped="PlaySong_Tapped"/>
</Grid>

I define these class-level variables in the code-behind (C#):

    MediaSource _mediaSource; /*Windows.Media.Core*/
    private List<StorageFile> playlistFiles = new List<StorageFile>();
    MediaPlayer _mediaPlayer; /*Windows.Media.Playback*/

These are the methods and event handlers:

    async private void OpenFile(object sender, RoutedEventArgs e)
    {
        var filePicker = new FileOpenPicker();
        filePicker.FileTypeFilter.Add(".mp3");
        filePicker.SuggestedStartLocation = PickerLocationId.MusicLibrary;

        var file = await filePicker.PickSingleFileAsync();

        var properties = await file.Properties.GetMusicPropertiesAsync();

        if (file != null)
        {
            _mediaSource = MediaSource.CreateFromStorageFile(file);
            _mediaPlayer = new MediaPlayer();
            _mediaPlayer.Source = _mediaSource;
            mediaPlayerElement.SetMediaPlayer(_mediaPlayer);
        }
    }

    async private void AddToPlaylist(object sender, RoutedEventArgs e)
    {
        var filePicker = new FolderPicker();
        filePicker.FileTypeFilter.Add(".mp3");
        filePicker.SuggestedStartLocation = PickerLocationId.MusicLibrary;

        var folder = await filePicker.PickSingleFolderAsync();
        if (folder == null)
        {
            return;
        }

        var files = await folder.GetFilesAsync();
        if (files == null)
        {
            return;
        }

        foreach (var file in files)
        {
            playlistFiles.Add(file);
        }

        GetFiles();
    }

    private void GetFiles()
    {
        playlistFiles.ForEach(file =>
        {
            var listItem = new ListViewItem() { Name = file.DisplayName, Content = new { ID = file.DisplayName, Name = file.DisplayName, Content = file.DisplayName } };
            listItem.Tapped += new TappedEventHandler(PlaySong_Tapped);
            listItem.IsTapEnabled = true;
            listItem.Content = file.DisplayName;
            playlist.Items.Add(listItem);
        });
    }

    async private void PlaySong_Tapped(object sender, TappedRoutedEventArgs e)
    {
        var selectedSong = (sender as ListViewItem).Name; /*This line throws the System.NullReferenceException*/
        await PlaySong(selectedSong);
    }

    async private Task PlaySong(string fileID)
    {
        var file = playlistFiles.Where(x => x.DisplayName == fileID).FirstOrDefault();
        if (file != null)
        {
            mediaPlayerElement.Source = MediaSource.CreateFromStorageFile(file);
            mediaPlayerElement.MediaPlayer.Play();
        }
    }

I'm really stumped as to why it doesn't work.
Edit: I know what a NullReferenceException is but I can't figure out why the object is null.

  • 1
    Are you sure `sender` is a `ListViewItem`? The [`as` keyword will return `null`](https://stackoverflow.com/a/15232518/3181933) in this instance if `sender` isn't a `ListViewItem`. – ProgrammingLlama Sep 29 '18 at 09:39
  • It looks like you assign `PlaySong_Tapped` as an event to `ListView` as well: ``. So it's quite possible that `(sender as ListViewItem)` is `null`, specifically when the sender is a `ListView`. – dbc Sep 29 '18 at 10:09
  • For some reason I can't mark this as Answered, but thanks dcb! Turns out that was the problem. – Isaac Opperman Oct 01 '18 at 07:34

0 Answers0