How to show an exception message if the user does not check a radio button on Xamarin Android?

0

I need to display an error message on the screen if the user does not check a radio button. In this code, there are 13 radio buttons separated into 4 radio groups I tried to use try / catch and if / else, but the screen does not show the Toast error.

Another question: I know that radio groups do not allow a person to choose more than 1 option, but how can I make an exceppeiton that allows the user to choose only 1 button from a single radio group?

For example: now I have to choose at least 4 buttons (1 of each radio goup), but I want to do it so that only one of any group good enough for the code to work >

Here is the code

    using Android.App;
    using Android.Content.PM;
    using Android.Content.Res;
    using Android.OS;
    using Android.Support.V4.Widget;
    using Android.Views;
    using Android.Widget;
    using System.Collections;
    using Android.Support.V7.App;
    using Android.Support.V4.View;
    using Android.Support.Design.Widget;
    using Auth0.OidcClient;
    using Android.Content;
    using IdentityModel.OidcClient;
    using Android.Graphics;
    using System.Net;
    using System;
    using Android.Runtime;
    using Android.Text.Method;
    using System.Text;
    namespace whirlpoolapp
    {
        [Activity(Label = "whirlpoolapp", MainLauncher = true)]
        [IntentFilter(
        new[] { Intent.ActionView },
        Categories = new[] { Intent.CategoryDefault, Intent.CategoryBrowsable },
        DataScheme = "whirlpoolapp.whirlpoolapp",
        DataHost = "lucasmoreira.auth0.com",
        DataPathPrefix = "/android/whirlpoolapp.whirlpoolapp/callback")]
        public class MainActivity : Activity
        {
            private ArrayList enderecos;
            TextView queroreconhecer;
            TextView crie;
            TextView conquiste;
            TextView entregue;
            TextView viva;
            TextView comentar;
            EditText comentário;
            Spinner spinner;
            ArrayAdapter adapter;
            RadioGroup rdgcrie;
            RadioGroup rdgconquiste;
            RadioGroup rdgentregue;
            RadioGroup rdgviva;
            Button enviar;
            private Auth0Client client;
            private AuthorizeState authorizeState;
            ProgressDialog progress;

            protected override void OnResume()
            {
                base.OnResume();

                if (progress != null)
                {
                    progress.Dismiss();

                    progress.Dispose();
                    progress = null;
                }
            }

            protected override async void OnNewIntent(Intent intent)
            {
                base.OnNewIntent(intent);

                var loginResult = await client.ProcessResponseAsync(intent.DataString, authorizeState);

                var sb = new StringBuilder();
                if (loginResult.IsError)
                {
                    sb.AppendLine($"An error occurred during login: {loginResult.Error}");
                }
                else
                {
                    sb.AppendLine($"ID Token: {loginResult.IdentityToken}");
                    sb.AppendLine($"Access Token: {loginResult.AccessToken}");
                    sb.AppendLine($"Refresh Token: {loginResult.RefreshToken}");

                    sb.AppendLine();

                    sb.AppendLine("-- Claims --");
                    foreach (var claim in loginResult.User.Claims)
                    {
                        sb.AppendLine($"{claim.Type} = {claim.Value}");
                    }
                }


            }

            private async void LoginButtonOnClick(object sender, EventArgs eventArgs)
            {


                progress = new ProgressDialog(this);
                progress.SetTitle("Log In");
                progress.SetMessage("Please wait while redirecting to login screen...");
                progress.SetCancelable(false); // disable dismiss by tapping outside of the dialog
                progress.Show();

                // Prepare for the login
                authorizeState = await client.PrepareLoginAsync();

                // Send the user off to the authorization endpoint
                var uri = Android.Net.Uri.Parse(authorizeState.StartUrl);
                var intent = new Intent(Intent.ActionView, uri);
                intent.AddFlags(ActivityFlags.NoHistory);
                StartActivity(intent);
            }

            protected override void OnCreate(Bundle bundle)
            {
                base.OnCreate(bundle);

                SetContentView(Resource.Layout.Main);
                client = new Auth0Client(new Auth0ClientOptions
                {
                    Domain = Resources.GetString(Resource.String.auth0_domain),
                    ClientId = Resources.GetString(Resource.String.auth0_client_id),
                    Activity = this
                });
                //preenche o arraylist com os dados
                GetEmails();
                //cria a instância do spinner declarado no arquivo Main
                spinner = FindViewById<Spinner>(Resource.Id.spnDados);
                //cria textview
                queroreconhecer = FindViewById<TextView>(Resource.Id.txtReconhecer);
                crie = FindViewById<TextView>(Resource.Id.txtCrie);
                conquiste = FindViewById<TextView>(Resource.Id.txtConquiste);
                entregue = FindViewById<TextView>(Resource.Id.txtEntregue);
                viva = FindViewById<TextView>(Resource.Id.txtViva);
                comentar = FindViewById<TextView>(Resource.Id.txtComentário);
                comentário = FindViewById<EditText>(Resource.Id.edtComentario);
                rdgcrie = FindViewById<RadioGroup>(Resource.Id.rdgCrie);
                rdgconquiste = FindViewById<RadioGroup>(Resource.Id.rdgConquiste);
                rdgentregue = FindViewById<RadioGroup>(Resource.Id.rdgEntregue);
                rdgviva = FindViewById<RadioGroup>(Resource.Id.rdgViva);
                adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleListItem1, enderecos);
                spinner.Adapter = adapter;
                spinner.ItemSelected += Spinner_ItemSelected;
                enviar = FindViewById<Button>(Resource.Id.button1);
                enviar.Click += enviar_Click;
                void GetEmails()
                {
                    enderecos = new ArrayList();
                    enderecos.Add("Escolha um colaborador abaixo");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("ana_carolina_simoes @whirlpool.com");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("ricardo_matos_campaneruti @whirlpool.com");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                    enderecos.Add("[email protected]");
                }// fim getEmails

                void Spinner_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
                {
                    Spinner spinner = (Spinner)sender;
                    string toast = string.Format("Colaborador selecionado: {0}", spinner.GetItemAtPosition(e.Position));
                    Toast.MakeText(this, toast, ToastLength.Long).Show();
                    string texto = toast;


                }


            }
            void enviar_Click(object sender, EventArgs e)
            {   try { 
                RadioButton rdbgrupo1 = FindViewById<RadioButton>(rdgconquiste.CheckedRadioButtonId);
                RadioButton rdbgrupo2 = FindViewById<RadioButton>(rdgcrie.CheckedRadioButtonId);
                RadioButton rdbgrupo3 = FindViewById<RadioButton>(rdgviva.CheckedRadioButtonId);
                RadioButton rdbgrupo4 = FindViewById<RadioButton>(rdgentregue.CheckedRadioButtonId);
                if (rdbgrupo1.Selected == false || rdbgrupo2.Selected == false || rdbgrupo3.Selected == false || rdbgrupo4.Selected == false)
                    {
                     string excecao = "Ao menos um botão de cada campo deve ser selecionado e o comentário deve ser preenchido";
                     Toast.MakeText(this, excecao, ToastLength.Long).Show();
                    }
                else
                    {
                        String emailescolhido = spinner.SelectedItem.ToString();
                        String campocomentario = comentário.Text;
                        string message = "Ao menos um botão de cada campo deve ser selecionado";
                        Toast.MakeText(ApplicationContext, message, ToastLength.Long).Show();
                        var email = new Intent(Android.Content.Intent.ActionSend);
                        //send to
                        email.PutExtra(Android.Content.Intent.ExtraEmail,
                        new string[] { "" + emailescolhido });
                        //cc to
                        email.PutExtra(Android.Content.Intent.ExtraCc,
                        new string[] { "[email protected]" });
                        //subject
                        email.PutExtra(Android.Content.Intent.ExtraSubject, "SABIA QUE VOCÊ FOI RECONHECIDO?");
                        //content
                        email.PutExtra(Android.Content.Intent.ExtraText,
                        "Você foi reconhecido pelo(s) valor(es) de: " + rdbgrupo1.Text + " , " + rdbgrupo2.Text + " , " + rdbgrupo3.Text + " e " + rdbgrupo4.Text);
                        email.PutExtra(Android.Content.Intent.ExtraText, "" + campocomentario);
                        email.SetType("message/rfc822");
                        StartActivity(email);
                    }

                }
                catch (Java.Lang.Exception ex)
                {
                    string excecao = "Ao menos um botão de cada campo deve ser selecionado e o comentário deve ser preenchido";
                    Toast.MakeText(this, excecao, ToastLength.Long).Show();

                }


            }




        }
    }
    
asked by anonymous 17.10.2017 / 15:03

1 answer

-1

You have to use rdbgrupo1.Checked and not rdbgrupo1.Selected .

    
17.10.2017 / 19:49