Skip to content Skip to sidebar Skip to footer

C# Xamarin Android Return Response Bool From Alertdialog

I am trying to return a bool true if the user selects yes from AlertDialog and visa versa. at the moment it always returns false. it seems like the bool 'result' is never being set

Solution 1:

You can create a Task-based dialog via a ManualResetEvent or a TaskCompletionSource so you can call it like this:

Usage via TaskCompletionSource Example:

try
{
    var result = await DialogAsync.Show(this, "StackOverflow", "Does it rock?");
    Log.Debug("SO", $"Dialog result: {result}");
}
catch (TaskCanceledException ex)
{
    Log.Debug("SO", $"Dialog cancelled; backbutton, click outside dialog, system-initiated, .... ");
}

DialogAsync via TaskCompletionSource Example:

public class DialogAsync : Java.Lang.Object, IDialogInterfaceOnClickListener, IDialogInterfaceOnCancelListener
{
    readonly TaskCompletionSource<bool?> taskCompletionSource = new TaskCompletionSource<bool?>();

    public DialogAsync(IntPtr handle, Android.Runtime.JniHandleOwnership transfer) : base(handle, transfer) { }
    public DialogAsync() { }

    public void OnClick(IDialogInterface dialog, int which)
    {
        switch (which)
        {
            case -1:
                SetResult(true);
                break;
            default:
                SetResult(false);
                break;
        }
    }

    public void OnCancel(IDialogInterface dialog)
    {
        taskCompletionSource.SetCanceled();
    }

    void SetResult(bool? selection)
    {
        taskCompletionSource.SetResult(selection);
    }

    public async static Task<bool?> Show(Activity context, string title, string message)
    {
        using (var listener = new DialogAsync())
        using (var dialog = new AlertDialog.Builder(context)
                                                            .SetPositiveButton("Yes", listener)
                                                            .SetNegativeButton("No", listener)
                                                            .SetOnCancelListener(listener)
                                                            .SetTitle(title)
                                                            .SetMessage(message))
        {
            dialog.Show();
            return await listener.taskCompletionSource.Task;
        }
    }
}

Usage Via ManualResetEvent Example:

using (var cancellationTokenSource = new CancellationTokenSource())
{
    var result = await DialogAsync.Show(this, "StackOverflow", "Does it rock?", cancellationTokenSource);
    if (!cancellationTokenSource.Token.IsCancellationRequested)
    {
        Log.Debug("SO", $"Dialog result: {result}");
    }
    else
    {
        Log.Debug("SO", $"Dialog cancelled; backbutton, click outside dialog, system-initiated, .... ");
    }
}

DialogAsync via ManualResetEvent Example:

public class DialogAsync : Java.Lang.Object, IDialogInterfaceOnClickListener, IDialogInterfaceOnCancelListener
{
    readonly ManualResetEvent resetEvent = new ManualResetEvent(false);
    CancellationTokenSource cancellationTokenSource;
    bool? result;

    public DialogAsync(IntPtr handle, Android.Runtime.JniHandleOwnership transfer) : base(handle, transfer) { }
    public DialogAsync() { }

    public void OnClick(IDialogInterface dialog, int which)
    {
        switch (which)
        {
            case -1:
                SetResult(true);
                break;
            default:
                SetResult(false);
                break;
        }
    }

    public void OnCancel(IDialogInterface dialog)
    {
        cancellationTokenSource.Cancel();
        SetResult(null);
    }

    void SetResult(bool? selection)
    {
        result = selection;
        resetEvent.Set();
    }

    public async static Task<bool?> Show(Activity context, string title, string message, CancellationTokenSource source)
    {
        using (var listener = new DialogAsync())
        using (var dialog = new AlertDialog.Builder(context)
                                                            .SetPositiveButton("Yes", listener)
                                                            .SetNegativeButton("No", listener)
                                                            .SetOnCancelListener(listener)
                                                            .SetTitle(title)
                                                            .SetMessage(message))
        {
            listener.cancellationTokenSource = source;
            context.RunOnUiThread(() => { dialog.Show(); });
            await Task.Run(() => { listener.resetEvent.WaitOne(); }, source.Token);
            return listener.result;
        }
    }
}

Post a Comment for "C# Xamarin Android Return Response Bool From Alertdialog"