Dbl
Dbl

Reputation: 5914

Can't create handler inside thread which has not called Looper.prepare() [xamarin]

So i don't actually have a question because i've already solved it, but in case someone else runs into this issue it's always nice to have a neat solution.

And while there is a plentitude of "Can't create handler inside thread which has not called Looper.prepare()" - questions there is none tagged with xamarin. (so theirs is all java and i had 0 matches for "Can't create handler inside thread which has not called Looper.prepare() [xamarin]")

Upvotes: 9

Views: 7690

Answers (3)

koviroli
koviroli

Reputation: 1453

Very similar actually happend to me. Previous evening I was developing and testing my app. Next morning, from other computer I got the exception you described. I was remembered from a official Xamarin.Forms documentation that sometimes a bin and obj folder removal solves lot of issues.

I did exactly the same, removed my bin and obj folder from my shared Xamarin.Forms library and also from Xamarin.Android library.

The strange exception disappeared.

Upvotes: 0

Maulik Parmar
Maulik Parmar

Reputation: 892

The issue is generated because You tried to do work on UI from other thread. If you want to change UI, Must call UI changes from UI thread.

Xamarin Android:

activity.RunOnUiThread(() =>
{
      // Write your code here         
});

Xamarin IOS:

nsObject.BeginInvokeOnMainThread(() =>
{
     // Write your code here                
});

Xamarin Forms:

Device.BeginInvokeOnMainThread(() =>
{
     // Write your code here
});

Upvotes: 20

Dbl
Dbl

Reputation: 5914

public static class PageExtensions
{
    public static Task<bool> DisplayAlertOnUi(this Page source, string title, string message, string accept, string cancel)
    {
        TaskCompletionSource<bool> doneSource = new TaskCompletionSource<bool>();
        Device.BeginInvokeOnMainThread(async () =>
        {
            try
            {
                var result = await source.DisplayAlert(title, message, accept, cancel);
                doneSource.SetResult(result);
            }
            catch (Exception ex)
            {
                doneSource.SetException(ex);
            }
        });

        return doneSource.Task;
    }
}

Finally i had a case for using TaskCompletionSource to solve an issue.

Upvotes: 13

Related Questions