PuineaGip
PuineaGip

Reputation: 5

Why does this refresh command crash the app?

Heres all the lines associated with the refresh command

This is the main binding in the XAML code

RefreshCommand="{Binding RefreshCommand}"

This is the ViewModel

async Task Refresh()
    {
        IsBusy = true;

        await Task.Delay(2000);

        Note.Clear();

        var notes = await NoteService.GetNote();

        Note.AddRange(notes);

        IsBusy = false;

    }

And the method GetNote looks like this

public static async Task<IEnumerable<Note>> GetNote()
    {
        await Init();

        var note = await db.Table<Note>().ToListAsync();
        return note;
    }

There are other methods include Refresh command, and they do not crash whenever the Refresh part is excluded, hence I believe the issue is related with this refresh method. Any help is appreciated!

Upvotes: 0

Views: 189

Answers (1)

Andrew Au
Andrew Au

Reputation: 101

Is Note binded to a UI element, such as a ListView?

If so, you may have to ensure that UI-related actions such as Note.AddRange(notes); are executed in the Main UI thread:

Device.BeginInvokeOnMainThread (() => {
    var notes = await NoteService.GetNote();
    Note.AddRange(notes);
});

More details here: Why use Device.BeginInvokeOnMainThread() in a Xamarin application?

Upvotes: 1

Related Questions