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

Asked

Viewed 245 times

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 groups separated into 4 radio groups I tried to use Try/catch and if/Else, but the screen does not show 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 exception 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 Goup radio), but I want to do it so that only one of any good enough group 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();

                }


            }




        }
    }
  • "(...)but I want to do it so that only one of any group good enough for the code to work" - Then it would not be better to have only one radio group?

  • The problem of having only 1 Radiogroup is that if someone wanted to assign more of a value to another person, they could not do so :(

  • @ramaral indicated me this possible solution: public int Radiogroupischecked(Radiogroup radioGroup) { //-1 Means Empty Selection Return radioGroup.Checkedradiobuttonid; } //User when user doesn’t check a radio button, show a Toast (Radiogroupischecked(group) == -1 || Radiogroupischecked(group2) == -1 || Radiogroupischecked(group3) == -1 || Radiogroupischecked(group4) == -1) { string exception = "At least one button of each field must be selected and the comment must be filled"; Toast.Maketext(this, exception, Toastlength.Long). Show(); }

  • As you accepted Matheus' answer I thought she had solved the problem. In fact you can use RadioGroup.CheckedRadioButtonId to check if any of the group’s Radiobutton has been selected. Its value will be -1 if no one is selected.

1 answer

-1


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

  • I switched to if (rdbgrupo1.Checked == false || rdbgrupo2.Checked == false || rdbgrupo3.Checked == false || rdbgrupo4.Checked == false) { string exception = "At least one button of each field must be selected and the comment must be filled"; Toast.Maketext(this, exception, Toastlength.Long). Show(); } But Unhandled Exception: System.Nullreferenceexception: Object Reference not set to an instance of an Object. occurred

  • My man, this code is all weird. If you want to see if a radioGroup is selected just check if rdgconquiste.Checkedradiobuttonid != -1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.