Esempio n. 1
0
        public override bool OnOptionsItemSelected(IMenuItem item)
        {
            // Si selecciona icon exit
            if (item.ItemId == Resource.Id.exit)
            {
                AlertDialog.Builder dialog = new AlertDialog.Builder(this);
                AlertDialog         alert  = dialog.Create();
                alert.SetTitle("Salir");
                alert.SetMessage("¿Estás seguro?");
                alert.SetIcon(Resource.Drawable.logo);
                alert.SetButton("Si", (c, ev) =>
                {
                    this.FinishAffinity();
                    Finish();
                    Android.OS.Process.KillProcess(Android.OS.Process.MyPid());

                    GC.Collect();
                });

                alert.SetButton2("no", (c, ev) => { });
                alert.Show();
            }

            return(base.OnOptionsItemSelected(item));
        }
Esempio n. 2
0
 //Al dar click en la foto
 private void perfil_Click(object sender, EventArgs e)
 {
     Android.App.AlertDialog.Builder builder    = new Android.App.AlertDialog.Builder(this);
     Android.App.AlertDialog         alerDialog = builder.Create();
     //Titulo
     alerDialog.SetTitle("PERFIL");
     //Icono
     alerDialog.SetIcon(Resource.Drawable.Perfil);
     //Pregunta
     alerDialog.SetMessage("¿Desea cambiar la foto de Perfil?");
     alerDialog.SetButton("No", (s, ev) =>
     {
         StartActivity(typeof(VerPerfil));
     });
     alerDialog.SetButton3("Si", (s, ev) =>
     {
         try
         {
             Intent intent = new Intent(MediaStore.ActionImageCapture);
             StartActivityForResult(intent, 0);
         }
         catch (Exception ex)
         {
         }
     });
     alerDialog.Show();
 }
Esempio n. 3
0
        public void ReceiveDetections(Detections detections)
        {
            SparseArray qrcodes = detections.DetectedItems;

            if (qrcodes.Size() != 0)
            {
                _txtResult.Post(() => {
                    _txtResult.Text            = ((Barcode)qrcodes.ValueAt(0)).RawValue;
                    AlertDialog.Builder dialog = new AlertDialog.Builder(this);
                    AlertDialog alert          = dialog.Create();
                    alert.SetTitle("Código de Barras");
                    alert.SetMessage(((Barcode)qrcodes.ValueAt(0)).RawValue);
                    alert.SetIcon(Resource.Drawable.logo);
                    alert.SetButton("Volver", (c, ev) =>
                    {
                        // Para actualizar una actividad desde dentro de sí mismo
                        Finish(); StartActivity(Intent);

                        GC.Collect();
                    });

                    alert.Show();
                });
            }
        }
Esempio n. 4
0
 private void OnPushNotificationReceived(object sender, PushNotificationReceivedEventArgs e)
 {
     Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(this);
     Android.App.AlertDialog         alert   = builder.Create();
     alert.SetTitle(e.Title);
     alert.SetMessage(e.Message);
     alert.SetIcon(Resource.Drawable.mr_dialog_material_background_dark);
     alert.Show();
 }
Esempio n. 5
0
 /// <summary>
 /// Método para lançar um alerta caso
 /// o usuário não exista no banco de dados
 /// </summary>
 public void AlertaUsarioNegado()
 {
     Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(this);
     Android.App.AlertDialog         alerta  = builder.Create();
     alerta.SetTitle("ERROR");
     alerta.SetIcon(Android.Resource.Drawable.IcDialogAlert);
     alerta.SetMessage("Dados incorretos!");
     alerta.Show();
 }
Esempio n. 6
0
 private void CreateDialog(int iconId, string title = "", string message = "")
 {
     Android.App.AlertDialog.Builder builder = new AlertDialog.Builder(this);
     _alert = builder.Create();
     _alert.SetTitle(title);
     _alert.SetMessage(message);
     _alert.SetIcon(iconId);
     _alert.SetButton("Close", OnCloseDialog);
     _alert.Show();
 }
Esempio n. 7
0
        private async void Votar(int tipo)
        {
            try
            {
                Voto voto = new Voto()
                {
                    IdUsuario  = Usuario.UsuarioLogado.Id,
                    IdDenuncia = (int)denunciaSelecionada,
                    tipoVoto   = tipo
                };

                HttpClient client = new HttpClient();

                string json    = JsonConvert.SerializeObject(voto);
                var    content = new StringContent(json, Encoding.UTF8, "application/json");

                var uri    = "https://grugol.000webhostapp.com/API/votos/votar.php";
                var result = await client.PostAsync(uri, content);

                // Se ocorrer um erro lança uma exceção
                result.EnsureSuccessStatusCode();

                Toast.MakeText(this, "Voto realizado com sucesso!", ToastLength.Short).Show();
                TxtTitulo_Click(null, null);
                CarregarDados();
            }
            catch (HttpRequestException ex)
            {
                Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(this);
                Android.App.AlertDialog         alerta  = builder.Create();

                alerta.SetTitle("Erro!");
                alerta.SetIcon(Android.Resource.Drawable.StatNotifyError);
                alerta.SetMessage($"Ocorreu um erro de conexão ao carregar os dados\n{ex.Message}");
                alerta.SetButton("OK", (s, ev) =>
                {
                });
                alerta.Show();
                //Toast.MakeText(this, $"Ocorreu um erro de conexão ao carregar os dados\n{ex.Message}", ToastLength.Long).Show();
            }
            catch (Exception ex)
            {
                Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(this);
                Android.App.AlertDialog         alerta  = builder.Create();

                alerta.SetTitle("Erro!");
                alerta.SetIcon(Android.Resource.Drawable.StatNotifyError);
                alerta.SetMessage($"Ocorreu um erro inesperado ao carregar os dados\n{ex.Message}");
                alerta.SetButton("OK", (s, ev) =>
                {
                });
                alerta.Show();
                //Toast.MakeText(this, $"Ocorreu um erro inesperado ao carregar os dados\n{ex.Message}", ToastLength.Long).Show();
            }
        }
        async Task RegistrationAsync()
        {
            ShowProgressDialogue("Registering...please wait!");
            try
            {
                var HttpClient = SessionManager.GetHttpClient();
                var json       = JsonConvert.SerializeObject(CurMember);
                var content    = new StringContent(json, Encoding.UTF8, "application/json");
                var url        = SessionManager.GetAPIURL("farmerRegistrations");
                var req        = new HttpRequestMessage(HttpMethod.Post, url)
                {
                    Content = content,
                };
                var response = await HttpClient.PostAsync(url, content);

                var responseMsg = await response.Content.ReadAsStringAsync();

                if (!string.IsNullOrWhiteSpace(responseMsg))
                {
                    var json1 = JsonConvert.DeserializeObject <dynamic>(responseMsg);
                    if (response.IsSuccessStatusCode)
                    {
                        CurMember.IsSynced = true;
                        Farmer.DB.Update(CurMember);
                        Android.App.AlertDialog.Builder dialog = new Android.App.AlertDialog.Builder(this);
                        Android.App.AlertDialog         alert  = dialog.Create();
                        alert.SetTitle("Registration");
                        alert.SetCanceledOnTouchOutside(false);
                        alert.SetMessage("Registration was successful. You can now login. Your username is your mobile number. Use any PIN or password of choice.");
                        alert.SetIcon(Resource.Drawable.ic_account_key);
                        alert.SetButton("OK", (c, ev) =>
                        {
                            alert.Dismiss();
                            var intent = new Intent(this, typeof(LoginActivity));
                            intent.PutExtra("Username", CurMember.Mobile);
                            StartActivity(intent);
                            Finish();
                            OverridePendingTransition(Resource.Animation.side_in_right, Resource.Animation.side_out_left);
                        });
                        alert.Show();
                    }
                    else
                    {
                        CloseProgressDialogue();
                        MessageBox.Show(this, "Regidtration Error", (string)json1.error_description);
                    }
                }
            }
            catch (Exception e)
            {
                CloseProgressDialogue();
                this.Show("Error", e.Message);
            }
        }
Esempio n. 9
0
        private async void CarregarDados()
        {
            try
            {
                HttpClient client = new HttpClient();
                // envia a requisição GET
                var uri    = "https://grugol.000webhostapp.com/API/denuncia/LerTodos.php";
                var result = await client.GetStringAsync(uri);

                CarregarVotos();

                // processa a resposta
                var posts = JsonConvert.DeserializeObject <List <Denuncia> >(result);
                denuncias = posts;
                var adapter = new DenunciaListAdapter(this, denuncias);
                lvDadosDenuncia.Adapter = adapter;
            }
            catch (JsonSerializationException)
            {
                Toast.MakeText(this, "Nenhuma denuncia foi encontrada!", ToastLength.Long).Show();
            }
            catch (HttpRequestException ex)
            {
                Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(this);
                Android.App.AlertDialog         alerta  = builder.Create();

                alerta.SetTitle("Erro!");
                alerta.SetIcon(Android.Resource.Drawable.StatNotifyError);
                alerta.SetMessage($"Ocorreu um erro de conexão ao carregar os dados\n{ex.Message}");
                alerta.SetButton("OK", (s, ev) =>
                {
                });
                alerta.Show();
                //Toast.MakeText(this, $"Ocorreu um erro de conexão ao carregar os dados\n{ex.Message}", ToastLength.Long).Show();
            }
            catch (Exception ex)
            {
                Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(this);
                Android.App.AlertDialog         alerta  = builder.Create();

                alerta.SetTitle("Erro!");
                alerta.SetIcon(Android.Resource.Drawable.StatNotifyError);
                alerta.SetMessage($"Ocorreu um erro inesperado ao carregar os dados\n{ex.Message}");
                alerta.SetButton("OK", (s, ev) =>
                {
                });
                alerta.Show();
                //Toast.MakeText(this, $"Ocorreu um erro inesperado ao carregar os dados\n{ex.Message}", ToastLength.Long).Show();
            }
        }
Esempio n. 10
0
 /// <summary>
 /// Método que apresenta um alerta
 /// </summary>
 /// <param name="mensagem">Mensagem a ser apresentada</param>
 public void ApresentaAlerta(string titulo, string mensagem, string texto_botao, Context context, MeuDelegate fun)
 {
     //define o alerta para executar a tarefa
     Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(context);
     Android.App.AlertDialog         alerta  = builder.Create();
     //Define o Titulo
     alerta.SetTitle(titulo);
     alerta.SetIcon(Android.Resource.Drawable.IcDialogAlert);
     alerta.SetMessage(mensagem);
     alerta.SetButton(texto_botao, (s, ev) =>
     {
         fun();
         //Toast.MakeText(context, "Legal, vamos continuar... !", ToastLength.Short).Show();
     });
     alerta.Show();
 }
Esempio n. 11
0
        private void ListItemClicked(int position)
        {
            Intent intent = null;

            switch (position)
            {
            case 0:
                intent = new Intent(this, typeof(Recordatorio));
                break;

            case 1:
                intent = new Intent(this, typeof(Calculadora));
                break;

            case 2:
                intent = new Intent(this, typeof(GuiaList));
                break;

            case 3:
                intent = new Intent(this, typeof(PacienteList));
                break;

            case 4:
                AlertDialog.Builder dialog = new AlertDialog.Builder(this);
                AlertDialog         alert  = dialog.Create();
                alert.SetTitle("Salir de la aplicación");
                alert.SetIcon(Resource.Drawable.logo);
                alert.SetButton("Aceptar", (c, ev) =>
                {
                    this.FinishAffinity();
                    Finish();
                    Android.OS.Process.KillProcess(Android.OS.Process.MyPid());

                    GC.Collect();
                });

                alert.SetButton2("Cancelar", (c, ev) => { });
                alert.Show();
                break;
            }

            if (intent != null)
            {
                StartActivity(intent);
            }
        }
Esempio n. 12
0
 public override bool OnOptionsItemSelected(IMenuItem item)
 {
     Android.App.AlertDialog.Builder builder    = new Android.App.AlertDialog.Builder(this);
     Android.App.AlertDialog         alerDialog = builder.Create();
     alerDialog.SetTitle("¡ Advertencia !");
     alerDialog.SetIcon(Resource.Drawable.Icon);
     alerDialog.SetMessage("¿Estás seguro que deseas salir?\nTodo tu progreso se perderá");
     alerDialog.SetButton("No", (s, ev) =>
     {
     });
     alerDialog.SetButton3("Si", (s, ev) =>
     {
         StartActivity(typeof(Lista_De_Examenes));
         Finish();
     });
     alerDialog.Show();
     return(base.OnOptionsItemSelected(item));
 }
Esempio n. 13
0
        private async void CarregarVotos()
        {
            try
            {
                HttpClient client = new HttpClient();

                var uri2    = "https://grugol.000webhostapp.com/API/votos/LerPorDenuncia.php";
                var result2 = await client.GetStringAsync(uri2);

                var resultVotos = JsonConvert.DeserializeObject <List <Voto> >(result2);
                votos = resultVotos;
            }
            catch (JsonSerializationException)
            {
            }
            catch (HttpRequestException ex)
            {
                Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(this);
                Android.App.AlertDialog         alerta  = builder.Create();

                alerta.SetTitle("Erro!");
                alerta.SetIcon(Android.Resource.Drawable.StatNotifyError);
                alerta.SetMessage($"Ocorreu um erro de conexão ao carregar os dados\n{ex.Message}");
                alerta.SetButton("OK", (s, ev) =>
                {
                });
                alerta.Show();
                //Toast.MakeText(this, $"Ocorreu um erro de conexão ao carregar os dados\n{ex.Message}", ToastLength.Long).Show();
            }
            catch (Exception ex)
            {
                Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(this);
                Android.App.AlertDialog         alerta  = builder.Create();

                alerta.SetTitle("Erro!");
                alerta.SetIcon(Android.Resource.Drawable.StatNotifyError);
                alerta.SetMessage($"Ocorreu um erro inesperado ao carregar os dados\n{ex.Message}");
                alerta.SetButton("OK", (s, ev) =>
                {
                });
                alerta.Show();
                //Toast.MakeText(this, $"Ocorreu um erro inesperado ao carregar os dados\n{ex.Message}", ToastLength.Long).Show();
            }
        }
Esempio n. 14
0
        private void Aceptar_Click(object sender, EventArgs e)
        {
            Validar.Visibility = ViewStates.Visible;
            //timer.Stop();
            //StartActivity(typeof(Resultado));
            Android.App.AlertDialog.Builder builder    = new Android.App.AlertDialog.Builder(this);
            Android.App.AlertDialog         alerDialog = builder.Create();

            //Titulo
            alerDialog.SetTitle("FELICITACIONES");
            //Icono
            alerDialog.SetIcon(Resource.Drawable.CopaGanador1);
            //Pregunta
            alerDialog.SetMessage("Haz Obtenido: " + "100" + " Puntos");
            alerDialog.SetButton("ACEPTAR", (se, eve) =>
            {
                StartActivity(typeof(MenuPrincipal));
            });
            alerDialog.Show();
        }
Esempio n. 15
0
        void SignOut()
        {
            Android.App.AlertDialog.Builder dialog = new Android.App.AlertDialog.Builder(this);
            Android.App.AlertDialog         alert  = dialog.Create();
            alert.SetTitle("Sign out");
            alert.SetCanceledOnTouchOutside(false);
            alert.SetMessage("Are you sure you want to sign out");
            alert.SetIcon(Resource.Drawable.ic_account_key);
            alert.SetButton("Yes", (c, ev) =>
            {
                Action = 3;
                alert.Dismiss();
                // if (Xamarin.Essentials.Connectivity.NetworkAccess.HasInternetAccess()) SyncData();
                if (!IsSyncing)
                {
                    SessionManager.User.Logout();
                }
                FinishAffinity();
                //  StartActivity(typeof(LoginOptionsActivity));
                // OverridePendingTransition(Resource.Animation.side_in_right, Resource.Animation.side_out_left);
            });

            alert.SetButton2("Cancel", (c, ev) =>
            {
                alert.Dismiss();
            });
            alert.SetButton3("Lock", (c, ev) =>
            {
                if (!string.IsNullOrWhiteSpace(SessionManager.SecretLock))
                {
                    SessionManager.IsLocked = true;
                    FinishAffinity();
                }
                else
                {
                    StartActivityForResult(typeof(AuthTemp.AddTemporaryPinActivity), 0);
                    OverridePendingTransition(Resource.Animation.side_in_right, Resource.Animation.side_out_left);
                }
            });
            alert.Show();
        }
Esempio n. 16
0
        private void List_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
        {
            AlertDialog.Builder dialog = new AlertDialog.Builder(this);
            AlertDialog         alert  = dialog.Create();

            alert.SetTitle("Rotación");
            alert.SetIcon(Resource.Drawable.logo);
            alert.SetButton("Confirmar", (c, ev) =>
            {
                _rotacion           = _listRotacion[e.Position];
                _rotacion.confirmar = true;                 // Confirmar Rotación
                _rotacionService.updateRotacion(_rotacion); // Actualiza el registro en la base de datos

                // Para actualizar una actividad desde dentro de sí mismo
                Finish(); StartActivity(Intent);

                GC.Collect();
            });

            alert.SetButton2("Omitir", (c, ev) => { });
            alert.Show();
        }
Esempio n. 17
0
        async void CarregarDados()
        {
            try
            {
                HttpClient client = new HttpClient();

                string uri    = "https://grugol.000webhostapp.com/API/usuario/LerTodos.php";
                var    result = await client.GetStringAsync(uri);

                usuarios = JsonConvert.DeserializeObject <List <Usuario> >(result);
            }
            catch (HttpRequestException ex)
            {
                Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(this);
                Android.App.AlertDialog         alerta  = builder.Create();

                alerta.SetTitle("Erro!");
                alerta.SetIcon(Android.Resource.Drawable.StatNotifyError);
                alerta.SetMessage($"Ocorreu um erro de conexão ao carregar os dados\n{ex.Message}");
                alerta.SetButton("OK", (s, ev) =>
                {
                });
                alerta.Show();
            }
            catch (Exception ex)
            {
                Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(this);
                Android.App.AlertDialog         alerta  = builder.Create();

                alerta.SetTitle("Erro!");
                alerta.SetIcon(Android.Resource.Drawable.StatNotifyError);
                alerta.SetMessage($"Ocorreu um erro inesperado ao carregar os dados\n{ex.Message}");
                alerta.SetButton("OK", (s, ev) =>
                {
                });
                alerta.Show();
            }
        }
Esempio n. 18
0
 private void OnListItemClick(object sender, AdapterView.ItemClickEventArgs e)
 {
     try
     {
         var listView = sender as ListView;
         var l        = gridViewString[e.Position];
         if (l == "Quiz")
         {
             StartActivity(typeof(Lista_De_Examenes));
         }
         else
         if (l == "Examen")
         {
             //   StartActivity(typeof(ListaExamenesCompletos));
             Android.App.AlertDialog.Builder builder    = new Android.App.AlertDialog.Builder(this);
             Android.App.AlertDialog         alerDialog = builder.Create();
             alerDialog.SetTitle("Versión Pro");
             //poner imagen de respuesta incorrecta
             alerDialog.SetIcon(Resource.Drawable.Icon);
             alerDialog.SetMessage("Obtén la versión PRO.\nPara poder acceder a cientos de preguntas");
             alerDialog.Show();
         }
         else
         if (l == "LeaderBoard")
         {
             StartActivity(typeof(LeaderBoard2));
         }
         else
         if (l == "Configuración")
         {
             StartActivity(typeof(Configuracion));
         }
     }
     catch (Exception ex)
     {
     }
 }
Esempio n. 19
0
 private void CerrarSesion_Click(object sender, EventArgs e)
 {
     Android.App.AlertDialog.Builder builder    = new Android.App.AlertDialog.Builder(this);
     Android.App.AlertDialog         alerDialog = builder.Create();
     //Titulo
     alerDialog.SetTitle("SESIÓN");
     //Icono
     alerDialog.SetIcon(Resource.Drawable.Icon);
     //Pregunta
     alerDialog.SetMessage("¿Estás seguro que deseas cerrar la sesión?");
     alerDialog.SetButton("No", (s, ev) =>
     {
         StartActivity(typeof(Configuracion));
         Finish();
     });
     alerDialog.SetButton3("Si", (s, ev) =>
     {
         appCode.ChangeLoginStatus(this, 0);
         appCode.SaveUser(this, 0);
         StartActivity(typeof(MainActivity));
         Finish();
     });
     alerDialog.Show();
 }
Esempio n. 20
0
        protected override void OnPrepareDialogBuilder(AlertDialog.Builder builder)
        {
            base.OnPrepareDialogBuilder(builder);

            builder.SetIcon(Resource.Drawable.Icon);
            builder.SetPositiveButton("Google Wallet", pos_Click);
            builder.SetNegativeButton("Pay Pal", neg_Click);
        }
Esempio n. 21
0
        protected async override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SupportActionBar.SetDisplayHomeAsUpEnabled(true);
            SupportActionBar.Elevation = 0;
            SetContentView(Resource.Layout.generic_list);
            Recycler = FindViewById <RecyclerView>(Resource.Id.gridView_items);
            Recycler.SetLayoutManager(new LinearLayoutManager(this));
            SelectMode = Intent.GetBooleanExtra(nameof(SelectMode), false);
            CourseID   = Intent.GetIntExtra(nameof(CourseID), 1);
            CurCourse  = await Course.DB.RowsAsync.FirstOrDefaultAsync(c => c.ID == CourseID);

            TitlesLayout       = FindViewById <LinearLayout>(Resource.Id.layout_title);
            TextOne            = FindViewById <TextView>(Resource.Id.text_title1);
            TextTwo            = FindViewById <TextView>(Resource.Id.text_title2);
            ExamBtn            = FindViewById <Button>(Resource.Id.btn_floating_action2);
            ExamBtn.Visibility = ViewStates.Visible;
            ExamBtn.Click     += async(o, e) =>
            {
                await CurCourse.LoadUserExaminations();

                await CurCourse.LoadAllExercises();

                var allexercises = CurCourse.AllExercises;
                var exercises    = CurCourse.UserExaminations;
                var passes       = new List <UserExamination>();
                foreach (var item in exercises)
                {
                    await item.LoadUserExaminationDetails();

                    var details = item.UserExaminationDetails;
                    foreach (var item2 in details)
                    {
                        await item2.LoadQuestion();

                        var q = item2.Question;
                        await q.LoadAnswers();

                        await item2.LoadAnswer();
                    }
                    var correctanswers = details.Where(c => c.AnswerID != null && c.Answer.IsCorrect);
                    var wronganswers   = details.Where(c => c.AnswerID != null && !c.Answer.IsCorrect);
                    var percentage     = 100 * correctanswers.Count() / details.Count;
                    if (percentage >= 70)
                    {
                        passes.Add(item);
                    }
                }
                var overalpercentage  = allexercises.Count > 0 ? 100 * passes.Count / allexercises.Count : 0;
                var requiredExercises = allexercises.Count * 70 / 100;
                if (overalpercentage >= 70)
                {
                    var intent = new Intent(this, typeof(InstructionActivity));
                    intent.PutExtra(nameof(CourseID), CourseID);
                    intent.PutExtra("ExamTypeID", (int)ExaminationType.EXAMINATION);
                    StartActivity(intent);
                    OverridePendingTransition(Resource.Animation.side_in_right, Resource.Animation.side_out_left);
                    Finish();
                }
                else
                {
                    Android.App.AlertDialog.Builder dialog = new Android.App.AlertDialog.Builder(this);
                    Android.App.AlertDialog         alert  = dialog.Create();
                    alert.SetTitle("Information");
                    alert.SetCanceledOnTouchOutside(false);
                    alert.SetMessage($"Number of attempted exercises: {exercises.Count}.\nPassed exercises: {passes.Count}\nOveral Pass rate: {overalpercentage}%\nYou need to pass at least {requiredExercises} short exercises to qualify for the final exam");
                    alert.SetIcon(Resource.Drawable.ic_account_key);
                    alert.SetButton("OK", (c, ev) =>
                    {
                        alert.Dismiss();
                    });
                    alert.Show();
                }
            };
            TitlesLayout.Visibility = ViewStates.Visible;
            TextOne.Visibility      = ViewStates.Visible;
            TextTwo.Visibility      = ViewStates.Visible;
            if (SelectMode)
            {
                Title = "Select module..";
            }
        }
Esempio n. 22
0
        public override bool OnOptionsItemSelected(IMenuItem item)
        {
            string   result = null;
            DBHelper dbh;
            Intent   intent;

            switch (item.ItemId)
            {
            case Android.Resource.Id.Home:
                if (SupportFragmentManager.BackStackEntryCount > 0)
                {
                    SupportFragmentManager.PopBackStack();
                    mCurrentFragment = mStackFrag.Pop();
                }
                else
                {
                    Finish();
                }
                return(true);

            case Resource.Id.menu_projectedit:
                intent = new Intent(this, typeof(EditProjectActivity));
                intent.PutExtra("ProjectId", selProjectId.ToString());
                StartActivity(intent);
                return(true);

            case Resource.Id.menu_projectdel:
                dbh = new DBHelper();
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                AlertDialog         alert   = builder.Create();
                alert.SetTitle("Delete project");
                alert.SetIcon(Android.Resource.Drawable.IcDialogAlert);
                alert.SetMessage("Are you sure?");

                alert.SetButton2("Yes", (s, ev) =>
                {       //yes
                    string dresult = dbh.DeleteProject(selProjectId);
                    if (dresult.Equals("ok"))
                    {
                        Toast.MakeText(this, "Project deleted!", ToastLength.Short).Show();
                        Finish();
                    }
                    else
                    {
                        Toast.MakeText(this, "Deletion failed!", ToastLength.Short).Show();
                    }
                });
                alert.SetButton("No", (s, ev) =>
                {       //no
                });
                alert.Show();
                return(true);

            case Resource.Id.menu_project_tasks:
                if (SupportFragmentManager.BackStackEntryCount > 0)
                {
                    SupportFragmentManager.PopBackStack();
                    mCurrentFragment = mStackFrag.Pop();
                }
                else
                {
                    ShowFragment(mProjectTasksFrag);
                }
                return(true);

            case Resource.Id.menu_prj_task_add:
                intent = new Intent(this, typeof(NewProjectTaskActivity));
                intent.PutExtra("ProjectId", selProjectId.ToString());
                StartActivity(intent);
                return(true);

            default:
                return(base.OnOptionsItemSelected(item));
            }
        }
Esempio n. 23
0
        async Task RegistrationAsync()
        {
            ProgressBar.Visibility = ViewStates.Visible;
            BtnLogin.Enabled       = false;
            try
            {
                var HttpClient = SessionManager.GetHttpClient();
                var json       = JsonConvert.SerializeObject(CurMember);
                var content    = new StringContent(json, Encoding.UTF8, "application/json");
                var url        = SessionManager.GetAPIURL("extensionOfficerRegistrations");
                var req        = new HttpRequestMessage(HttpMethod.Post, url)
                {
                    Content = content,
                };
                var response = await HttpClient.PostAsync(url, content);

                var responseMsg = await response.Content.ReadAsStringAsync();

                if (!string.IsNullOrWhiteSpace(responseMsg))
                {
                    var json1 = JsonConvert.DeserializeObject <ExtensionOfficer>(responseMsg);
                    if (response.IsSuccessStatusCode)
                    {
                        if (json1.ErrorCode.HasValue)
                        {
                            if (json1.ErrorCode == -1)
                            {
                                MessageBox.Show(this, "Record not found", json1.Firstname);
                            }
                            if (json1.ErrorCode == 1)
                            {
                                Android.App.AlertDialog.Builder dialog = new Android.App.AlertDialog.Builder(this);
                                Android.App.AlertDialog         alert  = dialog.Create();
                                alert.SetTitle("Record found");
                                alert.SetCanceledOnTouchOutside(false);
                                alert.SetMessage(json1.Firstname);
                                alert.SetIcon(Resource.Drawable.ic_account_key);
                                alert.SetButton("OK", (c, ev) =>
                                {
                                    alert.Dismiss();
                                    var intent = new Intent(this, typeof(LoginActivity));
                                    intent.PutExtra("Username", CurMember.ECNumber);
                                    StartActivity(intent);
                                    Finish();
                                    OverridePendingTransition(Resource.Animation.side_in_right, Resource.Animation.side_out_left);
                                });
                                alert.Show();
                            }
                        }

                        else
                        {
                            CurMember.IsSynced = true;
                            ExtensionOfficer.DB.Update(CurMember);
                            Android.App.AlertDialog.Builder dialog = new Android.App.AlertDialog.Builder(this);
                            Android.App.AlertDialog         alert  = dialog.Create();
                            alert.SetTitle("Registration");
                            alert.SetCanceledOnTouchOutside(false);
                            alert.SetMessage("Registration was successful. You can now login. Your username is your EC number. Use any PIN or password of choice.");
                            alert.SetIcon(Resource.Drawable.ic_account_key);
                            alert.SetButton("OK", (c, ev) =>
                            {
                                alert.Dismiss();
                                var intent = new Intent(this, typeof(LoginActivity));
                                intent.PutExtra("Username", CurMember.ECNumber);
                                StartActivity(intent);
                                Finish();
                                OverridePendingTransition(Resource.Animation.side_in_right, Resource.Animation.side_out_left);
                            });
                            alert.Show();
                        }
                    }
                    else
                    {
                        MessageBox.Show(this, "Regidtration Error", "Unknown error");
                    }
                }
            }
            catch (Exception e)
            {
                this.Show("Error", e.Message);
                BtnLogin.Enabled       = true;
                ProgressBar.Visibility = ViewStates.Gone;
            }
        }
Esempio n. 24
0
        private void Aceptar_Click(object sender, EventArgs e)
        {
            try
            {
                //validar si se contest[o la pregunta
                int i;

                for (i = 0; i < (r.Length - 1); i++)
                {
                    if (r[i].Selected || r[i].Checked)
                    {
                        break;
                    }
                }
                //si content[o la pregunta
                if (i < (r.Length - 1) || pre.tipo == 2)
                {
                    Android.App.AlertDialog.Builder builder    = new Android.App.AlertDialog.Builder(this);
                    Android.App.AlertDialog         alerDialog = builder.Create();
                    //valida si est[a bien la pregunta
                    int validadorpregunta = 0;
                    if (pre.tipo == 2)
                    {
                        validadorpregunta = validarRespuesta(pre, Respuesta.Text);
                    }
                    else
                    {
                        validadorpregunta = validarRespuesta(pre, i);
                    }

                    if (validadorpregunta == 1)
                    {
                        calificacion++;

                        alerDialog.SetTitle("FELICITACIONES");
                        alerDialog.SetIcon(Resource.Drawable.Bien);
                        alerDialog.SetMessage("Felicidades, respuesta correcta");
                        alerDialog.SetButton("OK", (s, ev) =>
                        {
                            correcta = true;
                            respusu  = i;
                        });
                    }
                    else
                    {
                        alerDialog.SetTitle("Respuesta incorrecta");
                        alerDialog.SetIcon(Resource.Drawable.Mal);
                        alerDialog.SetMessage(pre.ayuda);
                        alerDialog.SetButton("OK", (s, ev) =>
                        {
                            correcta = false;
                            respusu  = i;
                        });
                    }

                    //guarda respuesta usuario
                    //---------------RespuestaUsuario
                    ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(this);
                    // ID de usuario
                    int      userid   = prefs.GetInt("user", 0);
                    User     Datos    = new User(userid);
                    String   NOM      = Datos.Nombre;
                    int      preid    = pre.idPregunta;
                    DateTime thisDay  = DateTime.Today;
                    int      respcorr = pre.opcCorrecta;

                    Classes.Parameter[] p = new Classes.Parameter[] {
                        new Classes.Parameter("@ID_Usuario", userid),
                        new Classes.Parameter("@ID_Pregunta", preid),
                        new Classes.Parameter("@Fecha", thisDay),
                        new Classes.Parameter("@Respuesta_Usuario", respusu),
                        new Classes.Parameter("@Respuesta_Correcta", respcorr),
                        new Classes.Parameter("@Tiempo", null),
                        new Classes.Parameter("@Coorecta", correcta)
                    };
                    int ID = Convert.ToInt32(MSSql.FirstDataFromTable(con, "InsertRespuestasAlumnos", p));
                    MSSql.FirstDataFromTable(con, "InsertRespuestasAlumnos", p);
                    respusu = 0;
                    //---------------RespuestaUsuario
                    //aumenta contador de pregunta
                    contPregunta++;
                    //valida si tiene que mostrar la soguiente
                    if (contPregunta < 10)
                    {
                        ContadorPreg.Text = (contPregunta + 1) + " de 10";
                        pre = Pregunta.obtenerAleatoria(examen);
                        mostrarPregunta(pre);
                        r[10].Visibility = ViewStates.Gone;
                        r[10].Checked    = true;
                        r[10].Selected   = true;
                    }
                    else
                    {
                        Validar.Visibility = ViewStates.Visible;


                        alerDialog.CancelEvent += OnDialogCancel;
                        if (calificacion <= 3)
                        {
                            alerDialog.SetTitle("Necesitas estudiar más.");
                            alerDialog.SetIcon(Resource.Drawable.CopaTercero3);
                        }
                        else if (calificacion <= 7)
                        {
                            alerDialog.SetTitle("Buen intento, pero aún hay camino por recorrer.");
                            alerDialog.SetIcon(Resource.Drawable.CopaSegundo2);
                        }
                        else
                        {
                            alerDialog.SetTitle("¡FELICITACIONES!");
                            alerDialog.SetIcon(Resource.Drawable.CopaGanador1);
                        }


                        alerDialog.SetMessage("Haz Obtenido: " + (calificacion) + " Puntos");
                        alerDialog.SetButton("ACEPTAR", (se, eve) =>
                        {
                            StartActivity(typeof(MenuPrincipal));
                            Finish();
                        });
                    }
                    alerDialog.Show();
                }//no contest[o la pregunta
                else
                {
                    Android.App.AlertDialog.Builder builder    = new Android.App.AlertDialog.Builder(this);
                    Android.App.AlertDialog         alerDialog = builder.Create();
                    alerDialog.SetTitle("Error");
                    alerDialog.SetMessage("Debes seleccionar una opción");
                    alerDialog.Show();
                }
            }catch (Exception ex)
            {
            }
        }
Esempio n. 25
0
        public override bool OnOptionsItemSelected(IMenuItem item)
        {
            DBHelper dbh;
            string   status = "Pending";

            switch (item.ItemId)
            {
            case Android.Resource.Id.Home:
                Finish();
                return(true);

            case Resource.Id.menu_task_done:
                dbh    = new DBHelper();
                status = "Completed";

                string sresult = dbh.UpdateGoalTaskStatus(taskId, status);
                if (sresult.Equals("ok"))
                {
                    Toast.MakeText(this, "Task status: " + status, ToastLength.Short).Show();
                    mTaskStatus.Text = status;
                }
                else
                {
                    Toast.MakeText(this, "Failed updating task status!", ToastLength.Short).Show();
                }
                return(true);

            case Resource.Id.menu_task_undo:
                dbh    = new DBHelper();
                status = "Pending";

                string uresult = dbh.UpdateGoalTaskStatus(taskId, status);
                if (uresult.Equals("ok"))
                {
                    Toast.MakeText(this, "Task status: " + status, ToastLength.Short).Show();
                    mTaskStatus.Text = status;
                }
                else
                {
                    Toast.MakeText(this, "Failed updating task status!", ToastLength.Short).Show();
                }
                return(true);

            case Resource.Id.menu_task_del:
                dbh = new DBHelper();
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                AlertDialog         alert   = builder.Create();
                alert.SetTitle("Delete task");
                alert.SetIcon(Android.Resource.Drawable.IcDialogAlert);
                alert.SetMessage("Are you sure?");

                alert.SetButton2("Yes", (s, ev) =>
                {       //yes
                    string dresult = dbh.DeleteGoalTask(taskId);
                    if (dresult.Equals("ok"))
                    {
                        Toast.MakeText(this, "Task deleted!", ToastLength.Short).Show();
                        Finish();
                    }
                    else
                    {
                        Toast.MakeText(this, "Task deletion failed!", ToastLength.Short).Show();
                    }
                });
                alert.SetButton("No", (s, ev) =>
                {       //no
                });
                alert.Show();
                return(true);

            default:
                return(base.OnOptionsItemSelected(item));
            }
        }
Esempio n. 26
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.TakeTestLayout);
            Toolbar        toolbar    = FindViewById <Toolbar>(Resource.Id.toolbar1);
            Context        mContext   = Android.App.Application.Context;
            AppPreferences ap         = new AppPreferences(mContext);
            string         dbPath     = Intent.GetStringExtra("dbPath");
            int            primaryKey = Convert.ToInt32(ap.getValue("primaryKey"));
            var            db         = new SQLiteConnection(dbPath);
            var            session    = db.Table <Session>().Where(x => x.Id == primaryKey).FirstOrDefault();

            toolbar.Title = session.Session_Name;
            TextView displayQuestion = FindViewById <TextView>(Resource.Id.displayQuestion);
            CheckBox optionA         = FindViewById <CheckBox>(Resource.Id.checkBoxOptionA);
            CheckBox optionB         = FindViewById <CheckBox>(Resource.Id.checkBoxOptionB);
            CheckBox optionC         = FindViewById <CheckBox>(Resource.Id.checkBoxOptionC);
            CheckBox optionD         = FindViewById <CheckBox>(Resource.Id.checkBoxOptionD);

            string sessionName   = Intent.GetStringExtra("sessionName");
            string correctAnswer = "";


            var sessionList = db.Table <Session>();


            displayQuestion.Text = session.Question;
            optionA.Text         = session.OptionA;
            optionB.Text         = session.OptionB;
            optionC.Text         = session.OptionC;
            optionD.Text         = session.OptionD;
            Button submit = FindViewById <Button>(Resource.Id.buttonSubmit);


            optionA.Click += delegate
            {
                optionA.Checked = true;
                optionB.Checked = false;
                optionC.Checked = false;
                optionD.Checked = false;
                correctAnswer   = "Option A";
            };

            optionB.Click += delegate
            {
                optionB.Checked = true;
                optionA.Checked = false;
                optionC.Checked = false;
                optionD.Checked = false;
                correctAnswer   = "Option B";
            };

            optionC.Click += delegate
            {
                optionC.Checked = true;
                optionA.Checked = false;
                optionB.Checked = false;
                optionD.Checked = false;
                correctAnswer   = "Option C";
            };

            optionD.Click += delegate
            {
                optionD.Checked = true;
                optionA.Checked = false;
                optionB.Checked = false;
                optionC.Checked = false;
                correctAnswer   = "Option D";
            };

            submit.Click += async delegate
            {
                Android.App.AlertDialog.Builder dialog = new Android.App.AlertDialog.Builder(this);
                Android.App.AlertDialog         alert  = dialog.Create();
                alert.SetTitle("Answer Submitted");
                alert.SetMessage("Thank You!");
                alert.SetIcon(Resource.Drawable.icon);

                Android.App.AlertDialog.Builder dialogError = new Android.App.AlertDialog.Builder(this);
                Android.App.AlertDialog         alertError  = dialog.Create();
                alertError.SetTitle("Connection Error");
                alertError.SetMessage("Please check your Internet Connection and Try Again.");
                alertError.SetIcon(Resource.Drawable.icon);

                if (correctAnswer == "")
                {
                    Toast.MakeText(this, "You have to select one of the option", ToastLength.Short).Show();
                }
                else
                {
                    alert.Show();
                    FirebaseHelper firebaseHelper = new FirebaseHelper();

                    if (correctAnswer == session.CorrectAnswer)
                    {
                        //submit response
                        try
                        {
                            SessionResponse response = new SessionResponse();
                            response.name         = ap.getValue("name");
                            response.mobilenumber = Convert.ToDouble(ap.getValue("mobilenumber"));
                            var result = await firebaseHelper.postResponse(session.Session_Name, response);

                            primaryKey++;
                            ap.saveValue("primaryKey", "" + primaryKey);
                            var mainActivity = new Intent(this, typeof(MainActivity));
                            StartActivity(mainActivity);
                            //FinishAfterTransition();
                            this.Finish();
                        }
                        catch (Exception ex)
                        {
                            alert.Dismiss();
                            alertError.Show();
                        }
                    }
                    else
                    {
                        try
                        {
                            var items = await firebaseHelper.getAllSession();//only waste the time and match of the correct response submission time

                            primaryKey++;
                            ap.saveValue("primaryKey", "" + primaryKey);
                            var mainActivity = new Intent(this, typeof(MainActivity));
                            StartActivity(mainActivity);
                            //FinishAfterTransition();
                            this.Finish();
                        }
                        catch (Exception)
                        {
                            alert.Dismiss();
                            alertError.Show();
                        }
                    }
                }


                //LayoutInflater layoutInflater = LayoutInflater.From(this);
                //View mView = layoutInflater.Inflate(Resource.Layout.RatingLayout, null);
                //RatingBar ratingBar = mView.FindViewById<RatingBar>(Resource.Id.ratingBar1);
                //Button buttonRating = mView.FindViewById<Button>(Resource.Id.buttonRating);
                //Android.Support.V7.App.AlertDialog.Builder alertDialogBuilder = new Android.Support.V7.App.AlertDialog.Builder(this);
                //alertDialogBuilder.SetView(mView);
                //var alert = alertDialogBuilder.Show();
                //alertDialogBuilder.SetCancelable(false);
                //buttonRating.Click += async delegate
                //{
                //    try
                //    {
                //        var firebase = new FirebaseClient("https://leapproject-b603d.firebaseio.com/");
                //        int rating = Convert.ToInt32(ratingBar.Rating);
                //        var items = await firebase.Child(session.Session_Name).PostAsync<int>(rating);
                //        //Toast.MakeText(this, "your Score is " + ap.getValue("score"), ToastLength.Short).Show();

                //        if (ap.getValue("testAttempted") == "" + sessionList.Count())
                //        {

                //            Toast.MakeText(this, "WOWEQAW", ToastLength.Short).Show();


                //            //for (int i = 0; i < 10; i++)
                //            //{
                //            //    Random rand = new Random();
                //            //    SessionResponse sessionResponse = new SessionResponse();
                //            //    sessionResponse.name = ap.getValue("name");
                //            //    sessionResponse.mobilenumber = Convert.ToDouble(ap.getValue("mobilenumber"));
                //            //    //sessionResponse.score = Convert.ToInt32(ap.getValue("score"));
                //            //    sessionResponse.score = rand.Next(1, 9);
                //            //    var scoreItem = await firebase.Child("Score").Child("" + sessionResponse.score).PostAsync<SessionResponse>(sessionResponse);

                //            //}

                //        }

                //        alert.Dismiss();
                //        var mainActivity = new Intent(this, typeof(MainActivity));
                //        StartActivity(mainActivity);
                //    }
                //    catch
                //    {
                //        Console.WriteLine("Failed to update the database");
                //    }
                //};
            };
        }
Esempio n. 27
0
        private void BValidar_Click(object sender, EventArgs e)
        {
            try
            {



                string cadena = Convert.ToString(txtFechaNac.Text);
                string[] separadas;
                separadas = cadena.Split(',');
                string dia = separadas[0];
                string mes = separadas[1];
                string año = separadas[2];
                Android.App.AlertDialog.Builder builder10 = new AlertDialog.Builder(this);
                AlertDialog alertDialog10 = builder10.Create();
                alertDialog10.SetTitle("REGISTRO");

                if (Convert.ToInt32(año) > 2017)
                {
                    alertDialog10.SetIcon(Resource.Drawable.Icon);
                    alertDialog10.SetMessage("¿Acaso vienes del Futuro?");
                    alertDialog10.SetButton("OK", (s, ev) =>
                    {

                    });
                    alertDialog10.Show();
                }
                else if (Convert.ToInt32(año) >= 2014 && Convert.ToInt32(año) <= 2017)
                {
                    alertDialog10.SetIcon(Resource.Drawable.Icon);
                    alertDialog10.SetMessage("Eres un bebe muy inteligente, pero no te puedes registrar");
                    alertDialog10.SetButton("OK", (s, ev) =>
                    {

                    });
                    alertDialog10.Show();
                }

                else if (Convert.ToInt32(año) > 1917 && Convert.ToInt32(año) < 2013)
                {
                    obtener_datos();
                    int genero;

                    if (validar_contra() && validar_EditText(txtNombre) && validar_EditText(txtApellidos) && validar_EditText(txtEmail) && txtFechaNac.Text != "" && validarMail(txtEmail))
                    {
                        if (GeneroMasculino.Checked)
                        {
                            genero = 1;
                        }
                        else
                        {
                            genero = 0;
                        }

                        Android.App.AlertDialog.Builder builder5 = new Android.App.AlertDialog.Builder(this);
                        Android.App.AlertDialog alerDialog5 = builder5.Create();
                        //Titulo
                        alerDialog5.SetTitle("Compra");
                        //Icono
                        alerDialog5.SetIcon(Resource.Drawable.Icon);
                        //Pregunta
                        alerDialog5.SetMessage("Al dar Click en continuar aceptas nuestro Aviso de Privacidad.\n el cual lo puedes consultar en: www.preparate.com/AvisoDePrivacidad");
                        alerDialog5.SetButton("Continuar", (si, eve) =>
                        {

                            try
                            {

                                string res = API0.User.InsertUser(txtNombre.Text, txtApellidos.Text, "", Convert.ToDateTime(txtFechaNac.Text), tContra1.Text, txtEmail.Text, genero, 1, 1, "a");
                                Android.App.AlertDialog.Builder builder = new AlertDialog.Builder(this);
                                AlertDialog alertDialog = builder.Create();
                                alertDialog.SetTitle("REGISTRO");
                                switch (res)
                                {
                                    case "-2":
                                        txtEmail.SetBackgroundColor(Android.Graphics.Color.Red);
                                        alertDialog.SetMessage("La dirección de correo ya existe, por favor ingresa otra dirección ó inicia sesión.");
                                        alertDialog.SetButton("OK", (s, ev) =>
                                        {
                                        });
                                        alertDialog.Show();
                                        break;
                                    default:

                                        alertDialog.SetIcon(Resource.Drawable.Icon);
                                        alertDialog.SetMessage("Registro Exitoso");
                                        alertDialog.SetButton("OK", (s, ev) =>
                                        {
                                            StartActivity(typeof(Select_Registro));
                                            Finish();
                                        });
                                        alertDialog.Show();
                                        break;
                                }



                            }

                            catch (Exception ex)
                            {

                            }

                        });

                        alerDialog5.SetButton3("Cancelar", (se, eve) =>
                        {
                            StartActivity(typeof(Crear_Perfil));

                        });
                        alerDialog5.Show();

                    }
                }
                else
                {
                    alertDialog10.SetIcon(Resource.Drawable.Icon);
                    alertDialog10.SetMessage("Eres muy Anciano para usar esta aplicación.");
                    alertDialog10.SetButton("OK", (s, ev) =>
                    {

                    });
                    alertDialog10.Show();
                }
            }
            catch (Exception ex)
            {
                Toast.MakeText(this, "Por favor ingresa los datos correctos", ToastLength.Long).Show();
            }

        }
Esempio n. 28
0
        protected override async void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            //Set your main view here
            SetContentView(Resource.Layout.main);
            dbPath   = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "SessionDB.db");
            mContext = Android.App.Application.Context;
            ap       = new AppPreferences(mContext);
            if (session_count < 1)
            {
                LayoutInflater layoutInflater = LayoutInflater.From(this);
                View           mView          = layoutInflater.Inflate(Resource.Layout.ProgressLayout, null);
                Android.Support.V7.App.AlertDialog.Builder alertProgress = new Android.Support.V7.App.AlertDialog.Builder(this);
                alertProgress.SetView(mView).SetCancelable(false);
                var       alert     = alertProgress.Show();
                Stopwatch stopWatch = new Stopwatch();
                stopWatch.Start();
                while (session_count < 1)
                {
                    stopWatch.Stop();
                    if (stopWatch.ElapsedMilliseconds >= 10000)
                    {
                        mView.FindViewById <TextView>(Resource.Id.displayLoading).Text = "Please Check the Internet Connection";
                    }
                    else
                    {
                        stopWatch.Start();
                    }

                    await fetchData();
                }
                alert.Dismiss();
            }


            if (ap.getValue("name") == "" && ap.getValue("mobilenumber") == "")
            {
                LayoutInflater layoutInflater = LayoutInflater.From(this);
                View           mView          = layoutInflater.Inflate(Resource.Layout.user_pref, null);
                Button         buttonRegitser = mView.FindViewById <Button>(Resource.Id.buttonRegister);
                Android.Support.V7.App.AlertDialog.Builder alertDialogBuilder = new Android.Support.V7.App.AlertDialog.Builder(this);
                alertDialogBuilder.SetView(mView);
                alertDialogBuilder.SetCancelable(false);
                var alert = alertDialogBuilder.Show();
                buttonRegitser.Click += async delegate
                {
                    var username     = mView.FindViewById <TextView>(Resource.Id.editUsername).Text;
                    var mobilenumber = mView.FindViewById <TextView>(Resource.Id.editMobileNumber).Text;
                    try
                    {
                        if (username.Length >= 3 && mobilenumber.Length == 10 && Convert.ToDouble(mobilenumber) < 10000000000)
                        {
                            ap.saveValue("name", username);
                            ap.saveValue("mobilenumber", mobilenumber);
                            ap.saveValue("primaryKey", "1");
                            int index = Convert.ToInt32(ap.getValue("primaryKey"));
                            alert.Dismiss();
                            displayOTP(index);
                        }
                        else
                        {
                            Toast.MakeText(this, "Please enter a valid Name and MobileNumber.", ToastLength.Short).Show();
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Exception from MainActitvity in the Inputs " + ex);
                        Toast.MakeText(this, "Please enter a valid Name and MobileNumber", ToastLength.Short).Show();
                    }
                };
            }
            else
            {
                int index = Convert.ToInt32(ap.getValue("primaryKey"));
                Console.WriteLine("TEST ATTEMPTED :" + index);
                if (index <= session_count)
                {
                    displayOTP(index);
                }
                else
                {
                    Android.App.AlertDialog.Builder dialog = new Android.App.AlertDialog.Builder(this);
                    Android.App.AlertDialog         alert1 = dialog.Create();
                    alert1.SetTitle("Sessions Complete");
                    alert1.SetMessage("Thank You!");
                    alert1.SetIcon(Resource.Drawable.icon);
                    alert1.SetCancelable(false);
                    alert1.SetButton("EXIT", (c, ev) =>
                    {
                        MoveTaskToBack(true);
                        this.Finish();
                        this.FinishAffinity();
                    });
                    alert1.Show();
                }
            }
        }
Esempio n. 29
0
        public override bool OnOptionsItemSelected(IMenuItem item)
        {
            AlertDialog.Builder builder      = new AlertDialog.Builder(this);
            AlertDialog         mAlertDialog = builder.Create();

            switch (item.ItemId)
            {
            case Android.Resource.Id.Home:
                mDrawerLayout.OpenDrawer((int)GravityFlags.Left);
                return(true);


            //delete goals
            case Resource.Id.menu_delete_goals:
                mAlertDialog.SetTitle("Delete all goals");
                mAlertDialog.SetIcon(Resource.Drawable.ic_bin);
                mAlertDialog.SetMessage("Are you sure?");

                //buttons
                mAlertDialog.SetButton2("Yes", (s, ev) =>
                {
                    DBHelper dbh = new DBHelper();

                    string result = dbh.DeleteAllGoals();

                    if (result.Equals("ok"))
                    {
                        Snackbar.Make(mDrawerLayout, "All goals deleted!", Snackbar.LengthShort).Show();
                    }
                    else
                    {
                        Snackbar.Make(mDrawerLayout, result != null ? result : "Failed deleting goals!", Snackbar.LengthShort).SetAction("Ok", (v) => { }).Show();
                    }
                });

                mAlertDialog.SetButton("No", (s, ev) =>
                {
                    Snackbar.Make(mDrawerLayout, "Action cancelled", Snackbar.LengthLong).SetAction("Ok", (v) => { }).Show();
                });

                mAlertDialog.Show();

                return(true);

            //delete projects
            case Resource.Id.menu_delete_projects:
                mAlertDialog.SetTitle("Delete all projects");
                mAlertDialog.SetIcon(Resource.Drawable.ic_bin);
                mAlertDialog.SetMessage("Are you sure?");

                //buttons
                mAlertDialog.SetButton2("Yes", (s, ev) =>
                {
                    Snackbar.Make(mDrawerLayout, "All projects deleted!", Snackbar.LengthLong).SetAction("Ok", (v) => { }).Show();
                });

                mAlertDialog.SetButton("No", (s, ev) =>
                {
                    Snackbar.Make(mDrawerLayout, "Action cancelled", Snackbar.LengthLong).SetAction("Ok", (v) => { }).Show();
                });

                mAlertDialog.Show();

                return(true);

            //delete budgets
            case Resource.Id.menu_delete_budgets:
                mAlertDialog.SetTitle("Delete all budgets");
                mAlertDialog.SetIcon(Resource.Drawable.ic_bin);
                mAlertDialog.SetMessage("Are you sure?");

                //buttons
                mAlertDialog.SetButton2("Yes", (s, ev) =>
                {
                    Snackbar.Make(mDrawerLayout, "All budgets deleted!", Snackbar.LengthLong).SetAction("Ok", (v) => { }).Show();
                });

                mAlertDialog.SetButton("No", (s, ev) =>
                {
                    Snackbar.Make(mDrawerLayout, "Action cancelled", Snackbar.LengthLong).SetAction("Ok", (v) => { }).Show();
                });

                mAlertDialog.Show();

                return(true);

            //delete shopping lists
            case Resource.Id.menu_delete_shop_lists:
                mAlertDialog.SetTitle("Delete all shopping lists");
                mAlertDialog.SetIcon(Resource.Drawable.ic_bin);
                mAlertDialog.SetMessage("Are you sure?");

                //buttons
                mAlertDialog.SetButton2("Yes", (s, ev) =>
                {
                    Snackbar.Make(mDrawerLayout, "All shopping lists deleted!", Snackbar.LengthLong).SetAction("Ok", (v) => { }).Show();
                });

                mAlertDialog.SetButton("No", (s, ev) =>
                {
                    Snackbar.Make(mDrawerLayout, "Action cancelled", Snackbar.LengthLong).SetAction("Ok", (v) => { }).Show();
                });

                mAlertDialog.Show();

                return(true);

            default:
                return(base.OnOptionsItemSelected(item));
            }
        }
Esempio n. 30
0
        private async void btnDenunciar_click(object sender, EventArgs e)
        {
            try
            {
                btnDenunciar.Enabled = false;
                var coods = await Geolocation.GetLocationAsync();

                double lat = coods.Latitude;
                double lon = coods.Longitude;

                Denuncia denuncia = new Denuncia
                {
                    Latitude  = lat,
                    Longitude = lon
                };

                denuncia.Titulo    = txtTitulo.Text;
                denuncia.Descricao = txtDescricao.Text;

                LimparCampos();


                HttpClient client = new HttpClient();

                string json    = JsonConvert.SerializeObject(denuncia);
                var    content = new StringContent(json, Encoding.UTF8, "application/json");

                var uri    = "https://grugol.000webhostapp.com/API/denuncia/criarNova.php";
                var result = await client.PostAsync(uri, content);

                // Se ocorrer um erro lança uma exceção
                result.EnsureSuccessStatusCode();

                Toast.MakeText(this, "Denúncia feita com sucesso!", ToastLength.Short).Show();
                CarregarDados();
                btnDenunciar.Enabled = true;
            }
            catch (HttpRequestException ex)
            {
                btnDenunciar.Enabled = true;
                Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(this);
                Android.App.AlertDialog         alerta  = builder.Create();

                alerta.SetTitle("Erro!");
                alerta.SetIcon(Android.Resource.Drawable.StatNotifyError);
                alerta.SetMessage($"Ocorreu um erro de conexão ao carregar os dados\n{ex.Message}");
                alerta.SetButton("OK", (s, ev) =>
                {
                });
                alerta.Show();
                //Toast.MakeText(this, $"Ocorreu um erro de conexão ao carregar os dados\n{ex.Message}", ToastLength.Long).Show();
            }
            catch (Exception ex)
            {
                btnDenunciar.Enabled = true;
                Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(this);
                Android.App.AlertDialog         alerta  = builder.Create();

                alerta.SetTitle("Erro!");
                alerta.SetIcon(Android.Resource.Drawable.StatNotifyError);
                alerta.SetMessage($"Ocorreu um erro inesperado ao carregar os dados\n{ex.Message}");
                alerta.SetButton("OK", (s, ev) =>
                {
                });
                alerta.Show();
                //Toast.MakeText(this, $"Ocorreu um erro inesperado ao carregar os dados\n{ex.Message}", ToastLength.Long).Show();
            }
        }