AutoSuggestBox ItemsSource from SQLite database

MikeBealeMikeBeale Member ✭✭

I've got stuck with this, and am very new to Xamatin Forms.

I'm wanting to use the dotMorten.Xamarin.Forms.AutoSuggestBox in my Xamarin Forms app.

I have the list of values in a SQLite table:
`public class Streets

{

    [PrimaryKey]

    [MaxLength(255)]

    public String StreetName { get; set; }

}`

I'm wanting to use this table as the ItemsSource for the AutoSuggestBox.

Using the ToDo example app I have the following code to get the records from the table:
`public Task<List> LookupStreetsAsync(String query)

    {

        return lookups.Table<Streets>().Where(s => s.StreetName.StartsWith(query)).OrderBy(s => s.StreetName).ToListAsync();

    }`

But I cannot get this to be the ItemsSource for my AutoSuggestBox:
`private void StreetAutoSuggestBox_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs e)

    {

        if (e.Reason == AutoSuggestionBoxTextChangeReason.UserInput)

        {

            String query = sender.Text.Trim();

            // only auto suggest if 3 or more characters

            if (query.Length > 2)

            {

                sender.ItemsSource = App.Lookups.LookupStreetsAsync(query);

            }

        }

    }`

The error is:
Cannot implicitly convert type 'System.Threading.Tasks.Task<System.Collections.Generic.List<XamarinFirst.Streets>>' to 'System.Collections.IList'. An explicit conversion exists (are you missing a cast?)

I have Googled trying to cast from List to IList but nothing works, just get more errors!

How can I use my SQLite table with the AutoSuggestBox?

Thanks,
Mike

Answers

  • yousufctecyousufctec USMember ✭✭✭

    @MikeBeale,
    It's just simple that you're using asynchronous programming and when you did use any Async method, you will get result as Task object in which you need to get your desired object using "Result" property.

    May be try as below:

    sender.ItemsSource = App.Lookups.LookupStreetsAsync(query).Result;

    Regards,
    Yousuf.

  • FaizalSaidaliFaizalSaidali USMember ✭✭✭

    Hi @MikeBeale ,
    I think you can resolve it as per @yousufctec suggestion. As a starter in Xamarin Forms you need to follow some standards in your coding as well. I would suggest to you for considering the MVVM pattern in your project. It will helps you to implement the async methods and bindings are proper approach and it makes your app become faster and less memory consuming as well.

    Refer this link for MVVM implementation and data binding: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/xaml/xaml-basics/data-bindings-to-mvvm

Sign In or Register to comment.