How to show an exception message if the user doesn't check a radio button in Xamarin Android?

Hi I need to display a error message on the screen if the user doesn't check a radio button. In this code there are 13 radio buttons separeted on 4 radio groups.
I tried to use try/catch and if/else but the screen stills not showing the Toast error message.
Another doubt: I know that radio groups doesn't allow a person to choose more than 1 option, but how can I do an excepeiton that allows the user just to pick 1 button of one single radio group? For example: now I have to choose at least 4 buttons (1 of each radio group) but I want to do it in a way that just one of any group will be good enough

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("alexandre_bonfim@whirlpool.com");
                enderecos.Add("alexandre_t_pires@whirlpool.com");
                enderecos.Add("ana_carolina_simoes @whirlpool.com");
                enderecos.Add("ana_claudia_s_belarmino@whirlpool.com");
                enderecos.Add("andre_costa@whirlpool.com");
                enderecos.Add("andre_l_teixeira@whirlpool.com");
                enderecos.Add("andreza_a_valle@whirlpool.com");
                enderecos.Add("anna_carolina_b_ferreira@whirlpool.com");
                enderecos.Add("bruno_b_souza@whirlpool.com");
                enderecos.Add("bruno_c_castanho@whirlpool.com");
                enderecos.Add("bruno_s_lombardero@whirlpool.com");
                enderecos.Add("caio_c_sacoman@whirlpool.com");
                enderecos.Add("carla_sedin@whirlpool.com");
                enderecos.Add("cassia_r_nascimento@whirlpool.com");
                enderecos.Add("celia_r_araujo@whirlpool.com");
                enderecos.Add("cesar_leandro_de_oliveira@whirlpool.com");
                enderecos.Add("daniel_b_szortyka@whirlpool.com");
                enderecos.Add("denis_caciatori@whirlpool.com");
                enderecos.Add("elisabete_c_ferreira@whirlpool.com");
                enderecos.Add("erick_c_senzaki@whirlpool.com");
                enderecos.Add("erika_g_souza@whirlpool.com");
                enderecos.Add("fabiana_monteiro@whirlpool.com");
                enderecos.Add("fernando_v_santos@whirlpool.com");
                enderecos.Add("gabriel_roveda@whirlpool.com");
                enderecos.Add("herivelto_alves_jr@whirlpool.com");
                enderecos.Add("jefferson_s_pecanha@whirlpool.com");
                enderecos.Add("josiane_a_teles@whirlpool.com");
                enderecos.Add("juliana_g_saito@whirlpool.com");
                enderecos.Add("juliano_ventola@whirlpool.com");
                enderecos.Add("leonardo_l_costa@whirlpool.com");
                enderecos.Add("leonardo_r_silva@whirlpool.com");
                enderecos.Add("lucas_m_santos@whirlpool.com");
                enderecos.Add("luiz_perea@whirlpool.com");
                enderecos.Add("norma_raphaeli@whirlpool.com");
                enderecos.Add("patricia_f_prates@whirlpool.com");
                enderecos.Add("priscila_l_dattilo@whirlpool.com");
                enderecos.Add("priscila_m_konte@whirlpool.com");
                enderecos.Add("reider_a_bernucio@whirlpool.com");
                enderecos.Add("renato_occhiuto@whirlpool.com");
                enderecos.Add("ricardo_a_fernandes@whirlpool.com");
                enderecos.Add("ricardo_matos_campaneruti @whirlpool.com");
                enderecos.Add("rogerio_pagotto@whirlpool.com");
                enderecos.Add("ruben_c_anacleto@whirlpool.com");
                enderecos.Add("taise_azevedo@whirlpool.com");
                enderecos.Add("vinicius_marques_assis@whirlpool.com");
                enderecos.Add("wanderly_t_limeira@whirlpool.com");
            }// 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[] { "comite_clima_ti@whirlpool.com" });
                    //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();

            }


        }




    }
}

Answers

  • kramskrams INMember ✭✭

    can u post a screen shot of your view (not axml but the view on device or emulator)

  • I can't Xamarin says that I have to be around for a little bit more time before posting links '-'

Sign In or Register to comment.