0

I know this question is asked like milion times but i just don't know how to solve this problem.

I have a page with a list view. I am trying to implement the searchbar but then i get an exception in xaml.cs file at this point

**ListViewData.ItemsSource = searchResult;**

Can anyone help and explain how to solve this? I have tried too many options to mention it here..

Below the code of the xaml file:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="pytaniaApp.ShowDataPage" >
   
    <StackLayout x:Name="stackLayout">
        <SearchBar Placeholder="Search" 
                   x:Name="DataSearch"
                   SearchButtonPressed="DataSearch_SearchButtonPressed"/>

        <Label Text="Kliknij zeby zmienic lub usunac wpis"
           VerticalOptions="Center"
           HorizontalOptions="Center"
           FontSize="Large"/>
        
        <ListView x:Name="ListViewData"             
              ItemSelected="OnSelectedItem"
                  HorizontalScrollBarVisibility="Always"
                  RowHeight="40">
           <ListView.ItemTemplate>                
                <DataTemplate>
                    <ViewCell>
                        <StackLayout>                            
                            <Label Text="{Binding DataLabel}"
                                   LineBreakMode="WordWrap"/>                            
                        </StackLayout>
                        </ViewCell> 
                        </DataTemplate>
            </ListView.ItemTemplate>            
        </ListView>
    </StackLayout>
   
</ContentPage>

Code of the xaml.cs file:

using SQLite;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace pytaniaApp
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class ShowDataPage : ContentPage
    {
        
        string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "database.db3");

        public ShowDataPage()
        {
            InitializeComponent();
                            
        }
        
        protected override void OnAppearing()
        {
            var db = new SQLiteConnection(dbPath);
            ListViewData.ItemsSource = db.Table<Data>().OrderBy(x => x.Date).ToList();

            BindingContext = new Data();
            

            base.OnAppearing();

        }

        public async void OnSelectedItem(object sender, SelectedItemChangedEventArgs e)
        {
            var myitem = e.SelectedItem as Data;

            await Navigation.PushAsync(new PageEditEntry(myitem.Id, myitem.Date, myitem.Hours));
        }
        
        private void DataSearch_SearchButtonPressed(object sender, EventArgs e)
        {
            var db = new SQLiteConnection(dbPath);
            string keyword = DataSearch.Text;
      
                
             var searchResult = db.Table<Data>().Where(x => x.DataLabel.Contains(keyword));
            
            ListViewData.ItemsSource = searchResult;
        }
    }
}

And the code of Data.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text;
using SQLite;

namespace pytaniaApp
{

    public class Data : INotifyPropertyChanged

    {
        public event PropertyChangedEventHandler PropertyChanged;

        void OnPropertyChanged([CallerMemberName] string name = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }

        [PrimaryKey, AutoIncrement]
        public int Id
        {
            get;
            set;
        }
        public double Hours
        {
            get;
            set;
        }
       
        public DateTime Date

        {
            get;
            set;
        }

        public override string ToString()
        {

            double hours_rounded = Math.Truncate(Hours);
            double minutes_left = (Hours - hours_rounded) * 60;
            return "W dniu " + this.Date.ToString("dd-MM-yyyy") + " przepracowalas " + hours_rounded + " godzin(y) i " + minutes_left + " minut.";
        }

        public string DataLabel
        {
            get { return ToString(); }

        }



    }
}

enter image description here

Dawid
  • 1
  • 1
  • 3
    Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it). Did you try debugging your code? – Klaus Gütter Nov 20 '20 at 16:20
  • 2
    Step 0: which thing is null? The debugger will show you. – canton7 Nov 20 '20 at 16:23
  • if you query does not return any data what will the value of `itemsSearch` be? – Jason Nov 20 '20 at 16:38
  • Klaus: i have read it but i just cant find the solution. The exception happens when using the app on the emulator so yes it is debugged. Canton: the debugger shows the line i mentioned, i think the "searchResult" may be null and it's not aceptable. Jason: when the query does not return anything i would like to show a message or just leave it empty but i dont know what are the possibilities. See printscreen for the exception – Dawid Nov 20 '20 at 20:13
  • Try to add a `.ToList()` to the `var searchResult = ..` line to force the query to materialize at this point. This might help you to find the actual problem. – Klaus Gütter Nov 20 '20 at 20:30
  • After adding .ToList() i get the same exception but on the line before:( : var searchResult = db.Table().Where(x => x.DataLabel.Contains(keyword)).ToList(); – Dawid Nov 21 '20 at 10:59

0 Answers0