private void ShowInfoAufTestversion() { string message = string.Empty; if (MainActivity.IsGooglePlayPreLaunchTestMode) { message = "Die App befindet sich im Testmodus. Folgende Einschränkung bestehen bis zum {0}:\n\n"; message += "- Nur Testdatenbank\n"; message += "- Kein EAN Scan\n"; message = string.Format(message, MainActivity.preLaunchTestEndDay.AddDays(-1).ToShortDateString()); var messageDialog = new AlertDialog.Builder(this); messageDialog.SetMessage(message); messageDialog.SetTitle(Resource.String.App_Name); messageDialog.SetIcon(Resource.Drawable.ic_launcher); messageDialog.SetPositiveButton(Resource.String.App_Ok, (s, e) => {}); messageDialog.Create().Show(); return; } string lastRunDay = Settings.GetString("LastRunDay", string.Empty); int startInfoNr = Settings.GetInt("StartInfoNumber", 0); DateTime lastRun = new DateTime(); DateTime today = DateTime.Today; if (!string.IsNullOrEmpty(lastRunDay)) { lastRun = DateTime.ParseExact(lastRunDay, "yyyy.MM.dd", CultureInfo.InvariantCulture); } // Zum Debuggen // lastRun = new DateTime(1900,01,01); // startInfoNr = 0; if (today != lastRun) { startInfoNr++; if (startInfoNr > 3) { startInfoNr = 1; } switch (startInfoNr) { case 1: message = Resources.GetString(Resource.String.Start_TestVersionInfo1); break; case 2: message = Resources.GetString(Resource.String.Start_TestVersionInfo2); break; case 3: message = Resources.GetString(Resource.String.Start_TestVersionInfo3); break; case 4: message = Resources.GetString(Resource.String.Start_TestVersionInfo4); break; } } if (!string.IsNullOrEmpty(message)) { this.SetInfoText(message, false); } Settings.PutString("LastRunDay", today.ToString("yyyy.MM.dd")); Settings.PutInt("StartInfoNumber", startInfoNr); }
public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.PlaylistExerciseRow2, parent, false); View deleteView = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.DeleteItem, null); PlaylistViewHolder viewHolder = new PlaylistViewHolder(itemView, OnClick); //click event for the favorite button viewHolder.imageButton.Click += (sender, e) => { var pos = viewHolder.AdapterPosition; var name = playlists[pos].name; if (playlists[pos].favorite == true) { //set favorite to false and update list Toast.MakeText(parent.Context, "Removed from favorites", ToastLength.Short).Show(); viewHolder.imageButton.SetImageResource(Resource.Drawable.ic_star_border_green_A700_18dp); dataBase.updateFavorite(name, false); playlists[pos].favorite = false; } else { //set favorite to true and update list Toast.MakeText(parent.Context, "Added to favorites", ToastLength.Short).Show(); viewHolder.imageButton.SetImageResource(Resource.Drawable.ic_star_green_A700_18dp); dataBase.updateFavorite(name, true); playlists[pos].favorite = true; } }; //click event for the delete button viewHolder.deleteButton.Click += (sender, e) => { var pos = viewHolder.AdapterPosition; var name = playlists[pos].name; //make popup menu for confirmation of deleting from database AlertDialog.Builder builder = new AlertDialog.Builder(parent.Context); builder.SetView(deleteView); AlertDialog alertDialog = builder.Create(); Button deleteButton = deleteView.FindViewById <Button>(Resource.Id.btnDelete); Button cancelButton = deleteView.FindViewById <Button>(Resource.Id.btnCancel); TextView txtTitle = deleteView.FindViewById <TextView>(Resource.Id.titleDelete); txtTitle.Text = "Delete Playlist?"; deleteButton.Click += delegate { dataBase.deletePlaylist(name); Toast.MakeText(parent.Context, name + " deleted", ToastLength.Short).Show(); playlists.RemoveAt(pos); NotifyDataSetChanged(); alertDialog.Dismiss(); }; cancelButton.Click += delegate { //close window alertDialog.Dismiss(); }; alertDialog.Show(); }; return(viewHolder); }
public override Dialog OnCreateDialog(Bundle savedInstanceState) { _dialogId = GetColorPreference().GetArgs().GetInt(ARG_ID); _showAlphaSlider = GetColorPreference().GetArgs().GetBoolean(ARG_ALPHA); _showColorShades = GetColorPreference().GetArgs().GetBoolean(ARG_SHOW_COLOR_SHADES); _colorShape = (ColorShape)GetColorPreference().GetArgs().GetInt(ARG_COLOR_SHAPE); if (savedInstanceState == null) { _color = new Color(GetColorPreference().GetColor()); _dialogType = (ColorPickerDialog.DialogType)GetColorPreference().GetArgs().GetInt(ARG_TYPE); } else { _color = new Color(savedInstanceState.GetInt(ARG_COLOR)); _dialogType = (ColorPickerDialog.DialogType)savedInstanceState.GetInt(ARG_TYPE); } _rootView = new FrameLayout(Activity); if (_dialogType == ColorPickerDialog.DialogType.Custom) { _rootView.AddView(CreatePickerView()); } else if (_dialogType == ColorPickerDialog.DialogType.Preset) { _rootView.AddView(CreatePresetsView()); } var selectedButtonStringRes = GetColorPreference().GetArgs().GetInt(ARG_SELECTED_BUTTON_TEXT); if (selectedButtonStringRes == 0) { selectedButtonStringRes = Resource.String.cpv_select; } var builder = new AlertDialog.Builder(Activity).SetView(_rootView).SetPositiveButton( selectedButtonStringRes, new DialogInterfaceOnClickListener( (d, w) => { OnColorSelected(); })); var dialogTitleStringRes = GetColorPreference().GetArgs().GetInt(ARG_DIALOG_TITLE); if (dialogTitleStringRes != 0) { builder.SetTitle(dialogTitleStringRes); } _presetsButtonStringRes = GetColorPreference().GetArgs().GetInt(ARG_PRESETS_BUTTON_TEXT); _customButtonStringRes = GetColorPreference().GetArgs().GetInt(ARG_CUSTOM_BUTTON_TEXT); int neutralButtonStringRes; if (_dialogType == ColorPickerDialog.DialogType.Custom && GetColorPreference().GetArgs().GetBoolean(ARG_ALLOW_PRESETS)) { neutralButtonStringRes = (_presetsButtonStringRes != 0 ? _presetsButtonStringRes : Resource.String.cpv_presets); } else if (_dialogType == ColorPickerDialog.DialogType.Preset && GetColorPreference().GetArgs().GetBoolean(ARG_ALLOW_CUSTOM)) { neutralButtonStringRes = (_customButtonStringRes != 0 ? _customButtonStringRes : Resource.String.cpv_custom); } else { neutralButtonStringRes = 0; } if (neutralButtonStringRes != 0) { builder.SetNeutralButton(neutralButtonStringRes, (IDialogInterfaceOnClickListener)null); } return(builder.Create()); }
private async void Next_FoundVehicle2_Click(object sender, EventArgs e) { if (FoundVehicle2_radiobtn3.Checked) { var p = JsonConvert.DeserializeObject <Model.Missingvehicle>(Intent.GetStringExtra("objtopass")); p.issueType = "Found Vehicle"; Control.DataOper.PutData <Issuelocationpickup_MissingVehicle>(this, p); } else { if (location_lati != "" && location_longi != "") { await Task.Run(async() => { var p = JsonConvert.DeserializeObject <Model.Missingvehicle>(Intent.GetStringExtra("objtopass")); p.locationLatitude = location_lati; p.locationLongitude = location_longi; p.Status = "unverified"; p.isresolved = 0; // Issue is not resolved yet. p.issueFlag = "green"; p.issueType = "Found Vehicle"; p.isWorkingStarted = 0; p.amount_collected = 0; p.estimated_cost = 0; try { mapFuncHelper = new MapFunctions.MapFunctionHelper(APIKEY, null); var placemark = await mapFuncHelper.FindCordinateAddress(new Android.Gms.Maps.Model.LatLng(Convert.ToDouble(location_lati), Convert.ToDouble(location_longi))); if (placemark != null) { LocationName = placemark.Replace(", Karachi, Karachi City, Sindh, Pakistan", string.Empty); p.location_name = LocationName; p.issueStatement = "Unidentified vehicle found since " + p.foundDate.Date.ToShortDateString() + " with Plate No. " + p.plateNumber + " near " + LocationName; Android.App.AlertDialog.Builder dialog = new AlertDialog.Builder(this); AlertDialog alert = dialog.Create(); alert.SetMessage("Please wait while your issue is being posted ..."); alert.Show(); await Control.IssueController.PostIssue <Model.Missingvehicle>(p, this); } } catch (FeatureNotSupportedException fnsEx) { // Feature not supported on device } catch (Exception ex) { // Handle exception that may have occurred in geocoding } }); } else { MainThread.BeginInvokeOnMainThread(() => { Toast.MakeText(this, "Please select Vehicle Location", ToastLength.Long).Show(); }); } } }
protected override void OnCreate(Bundle savedInstanceState) { try { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.ProcesoPrincipalActivity); string contenido = Intent.GetStringExtra("contenido") ?? string.Empty; if (!string.IsNullOrEmpty(contenido)) { AutenticarUsuarioResult resultado = Newtonsoft.Json.JsonConvert.DeserializeObject <AutenticarUsuarioResult>(contenido); citas = resultado.lista; if (citas != null && citas.Any()) { UsuarioBO usuario = new UsuarioBO { Usuario = citas[0].Usuario, Password = citas[0].Password }; usuarioinformacion = Newtonsoft.Json.JsonConvert.SerializeObject(usuario); } } Spinner spinner = FindViewById <Spinner>(Resource.Id.spinner1); spinner.Adapter = new CitasAdapter(this, citas); spinner.ItemSelected += new EventHandler <AdapterView.ItemSelectedEventArgs>(spinner_ItemSelected); Button btnCheckin = FindViewById <Button>(Resource.Id.button1); Button btnCheckout = FindViewById <Button>(Resource.Id.button2); Button btnCrm = FindViewById <Button>(Resource.Id.button3); #region btnCheckIn btnCheckin.Click += async delegate { btnCheckin.Enabled = false; if (isInCall) { Toast.MakeText(this, "Su Solicitud se esta procesando...", ToastLength.Short).Show(); btnCheckin.Enabled = true; return; } isInCall = true; try { if (!GetIsInternetAccessAvailable()) { Toast.MakeText(context, "Sin Acceso a Internet. Verifique", ToastLength.Short).Show(); btnCheckin.Enabled = true; isInCall = false; return; } if (!IsHostReachable()) { Toast.MakeText(context, "Sin comunicación con el Servicio. Verifique", ToastLength.Short).Show(); btnCheckin.Enabled = true; isInCall = false; return; } if (citaSeleccionada != null) { progress = new ProgressDialog(this); progress.Indeterminate = false; progress.SetProgressStyle(ProgressDialogStyle.Spinner); progress.SetMessage("Realizando Check-In..."); progress.SetCancelable(false); progress.Show(); var locator = CrossGeolocator.Current; locator.DesiredAccuracy = 1; var position = await locator.GetPositionAsync(timeoutMilliseconds : 10000); if (position != null) { DateTime momento = DateTime.Now; citaSeleccionada.LatitudInicio = position.Latitude; citaSeleccionada.LongitudInicio = position.Longitude; citaSeleccionada.HoraLlegada = momento.ToString("dd/MM/yyyy HH:mm"); citaSeleccionada.year = momento.Year; citaSeleccionada.month = momento.Month; citaSeleccionada.day = momento.Day; citaSeleccionada.hour = momento.Hour; citaSeleccionada.minute = momento.Minute; string resultado = await DoCheckInAsync(); if (string.IsNullOrEmpty(resultado)) { RunOnUiThread(() => { btnCheckin.Enabled = true; isInCall = false; progress.Hide(); progress.Dispose(); CargaInformacionConResultado("CI"); }); } else { RunOnUiThread(() => { btnCheckin.Enabled = true; isInCall = false; citaSeleccionada.LatitudInicio = 0; citaSeleccionada.LongitudInicio = 0; citaSeleccionada.HoraLlegada = string.Empty; citaSeleccionada.year = 0; citaSeleccionada.month = 0; citaSeleccionada.day = 0; citaSeleccionada.hour = 0; citaSeleccionada.minute = 0; progress.Hide(); progress.Dispose(); AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.SetTitle("Información"); alert.SetMessage(resultado); alert.SetPositiveButton("Aceptar", (senderAlert, args) => { }); Dialog dialog = alert.Create(); dialog.Show(); }); } } else { btnCheckin.Enabled = true; isInCall = false; Toast.MakeText(context, "No se logro optener su posición actual", ToastLength.Long).Show(); return; } } else { btnCheckin.Enabled = true; isInCall = false; Toast.MakeText(context, "Debe seleccionar una cita", ToastLength.Long).Show(); return; } } catch (Exception ex) { progress.Hide(); btnCheckin.Enabled = true; isInCall = false; Toast.MakeText(this, "No se logro realizar el Check In. Intente más tarde. Error: " + ex.Message, ToastLength.Long).Show(); } }; #endregion btnCheckIn #region btnCheckout btnCheckout.Click += async delegate { btnCheckout.Enabled = false; if (isInCall) { Toast.MakeText(this, "Su Solicitud se esta procesando...", ToastLength.Short).Show(); btnCheckout.Enabled = true; return; } isInCall = true; try { if (!GetIsInternetAccessAvailable()) { btnCheckout.Enabled = true; isInCall = false; Toast.MakeText(context, "Sin Acceso a Internet. Verifique", ToastLength.Long).Show(); return; } if (!IsHostReachable()) { btnCheckout.Enabled = true; isInCall = false; Toast.MakeText(context, "Sin comunicación con el Servicio. Verifique", ToastLength.Long).Show(); return; } if (citaSeleccionada != null) { progress = new ProgressDialog(this); progress.Indeterminate = false; progress.SetProgressStyle(ProgressDialogStyle.Spinner); progress.SetMessage("Realizando Check-Out..."); progress.SetCancelable(false); progress.Show(); var locator = CrossGeolocator.Current; locator.DesiredAccuracy = 1; var position = await locator.GetPositionAsync(timeoutMilliseconds : 10000); if (position != null) { DateTime momento = DateTime.Now; citaSeleccionada.LatitudFin = position.Latitude; citaSeleccionada.LongitudFin = position.Longitude; citaSeleccionada.HoraSalida = momento.ToString("dd/MM/yyyy HH:mm"); citaSeleccionada.year = momento.Year; citaSeleccionada.month = momento.Month; citaSeleccionada.day = momento.Day; citaSeleccionada.hour = momento.Hour; citaSeleccionada.minute = momento.Minute; string resultado = await DoCheckOutAsync(); if (string.IsNullOrEmpty(resultado)) { RunOnUiThread(() => { btnCheckout.Enabled = true; isInCall = false; progress.Hide(); progress.Dispose(); CargaInformacionConResultado("CO"); }); } else { RunOnUiThread(() => { btnCheckout.Enabled = true; isInCall = false; citaSeleccionada.LatitudFin = 0; citaSeleccionada.LongitudFin = 0; citaSeleccionada.HoraSalida = string.Empty; citaSeleccionada.year = 0; citaSeleccionada.month = 0; citaSeleccionada.day = 0; citaSeleccionada.hour = 0; citaSeleccionada.minute = 0; progress.Hide(); progress.Dispose(); AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.SetTitle("Información"); alert.SetMessage(resultado); alert.SetPositiveButton("Aceptar", (senderAlert, args) => { }); Dialog dialog = alert.Create(); dialog.Show(); }); } } else { btnCheckout.Enabled = true; isInCall = false; Toast.MakeText(context, "No se logro optener su posición actual", ToastLength.Long).Show(); return; } } else { btnCheckout.Enabled = true; isInCall = false; Toast.MakeText(context, "Debe seleccionar una cita", ToastLength.Long).Show(); return; } } catch (Exception ex) { progress.Hide(); btnCheckout.Enabled = true; isInCall = false; Toast.MakeText(this, "No se logro realizar el Check Out. Intente más tarde. Error: " + ex.Message, ToastLength.Long).Show(); } }; #endregion btnCheckout #region btnCRM btnCrm.Click += delegate { try { var existIntent = ApplicationContext.PackageManager.GetLaunchIntentForPackage("com.microsoft.crm.crmhost"); //var existIntent = ApplicationContext.PackageManager.GetLaunchIntentForPackage("com.whatsapp"); if (existIntent != null) { StartActivity(existIntent); } else { existIntent = ApplicationContext.PackageManager.GetLaunchIntentForPackage("com.microsoft.crm.crmphone"); if (existIntent != null) { StartActivity(existIntent); } else { var uri = Android.Net.Uri.Parse("market://details?id=com.microsoft.crm.crmhost"); var intent = new Intent(Intent.ActionView, uri); StartActivity(intent); } } } catch (Exception ex) { Toast.MakeText(this, "No se pudo abrir Dynamics CRM. Intente más tarde. Error: " + ex.Message, ToastLength.Long).Show(); return; } }; #endregion btnCRM AndroidEnvironment.UnhandledExceptionRaiser += new EventHandler <RaiseThrowableEventArgs>(AndroidEnvironment_UnhandledExceptionRaiser); } catch (Exception ex) { Toast.MakeText(context, "La aplicación tuvo un incoveniente. Intente más tarde. Error: " + ex.Message, ToastLength.Long).Show(); } }
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Use this to return your custom view for this Fragment // return inflater.Inflate(Resource.Layout.YourFragment, container, false); //return base.OnCreateView(inflater, container, savedInstanceState); View view = inflater.Inflate(Resource.Layout.fragmentLogin, container, false); ((MainActivity)Activity).habilitarMenuLateral(false); ((MainActivity)Activity).cambiarTituloAplicacion("Autenticación de usuario"); Button btnLogin = view.FindViewById <Button>(Resource.Id.btnLogin); EditText txtUsuario = view.FindViewById <EditText>(Resource.Id.txtUsuario); EditText txtContrasena = view.FindViewById <EditText>(Resource.Id.txtPassword); TextInputLayout passwordWrapper = view.FindViewById <TextInputLayout>(Resource.Id.txtInputLayoutPassword); string txtPassword = passwordWrapper.EditText.Text; Context context; context = view.Context; txtUsuario.Text = ""; txtContrasena.Text = ""; txtUsuario.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) => { usuario = e.Text.ToString(); }; txtContrasena.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) => { contrasena = e.Text.ToString(); }; if (!coneccionInternet.verificaConeccion(this.Context)) { AlertDialog.Builder alerta = new AlertDialog.Builder(this.Context); alerta.SetTitle("Mensaje de alerta"); alerta.SetIcon(Resource.Drawable.alertaNuevo); alerta.SetMessage("El servicio de Internet no se encuentra disponible, por favor revise su conexión e intente ingresar nuevamente"); alerta.SetNegativeButton("Salir", HandleButtonClick); alerta.SetCancelable(false); alerta.Create(); alerta.Show(); } //se limpia la tabla de Oficial Notificador ManejoBaseDatos.CrearDB(); ManejoBaseDatos.Abrir(); List <string> tablas = new List <string>(); tablas.Add("OficialNotificador"); ManejoBaseDatos.BorrarTablas(tablas); ManejoBaseDatos.Cerrar(); btnLogin.Click += (o, e) => { try { if (!string.IsNullOrEmpty(usuario) && (contrasena.Equals("12345", StringComparison.Ordinal)) && (usuario.Equals("supervisor", StringComparison.Ordinal) || usuario.Equals("demo", StringComparison.Ordinal))) { string query = @"https://pjgestionnotificacionmovilservicios.azurewebsites.net/api/OficialNotificador/ConsultarOficialNotificador?PCodNotificador=" + usuario + ""; if (coneccionInternet.verificaConeccion(this.Context)) { try { WebRequest request = HttpWebRequest.Create(query); request.ContentType = "application/json"; request.Method = "GET"; string content = ""; using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { if (response.StatusCode != HttpStatusCode.OK) { Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode); } using (StreamReader reader = new StreamReader(response.GetResponseStream())) { content = reader.ReadToEnd(); if (string.IsNullOrWhiteSpace(content)) { Console.Out.WriteLine("fzeledon -- Response contained empty body..."); } else { try { var jsonParsed = JObject.Parse(content); codOficina = jsonParsed["Oficinas"][0]["Codigo"].ToString(); supervisor = jsonParsed["Supervisor"].ToString(); rolNocturno = jsonParsed["RolNocturno"].ToString(); codNotificador = jsonParsed["CodNotificador"].ToString(); cuotaMinima = jsonParsed["Oficinas"][0]["CuotaMinima"].ToString(); ManejoBaseDatos.Abrir(); ManejoBaseDatos.Insertar("OficialNotificador", "Activo,CodigoNotificador,DespachoCodigo,Supervisor,RolNocturno", "'" + jsonParsed["Activo"].ToString() + "','" + jsonParsed["CodNotificador"].ToString() + "','" + jsonParsed["Oficinas"][0]["Codigo"].ToString() + "','" + jsonParsed["Supervisor"].ToString() + "','" + jsonParsed["RolNocturno"].ToString() + "'"); ManejoBaseDatos.Cerrar(); //se realiza la comprobacion si se tiene una sesion abierta servicioCheckDB coneccion = new servicioCheckDB(); var sesionAbierta = coneccion.ObtenerString("https://pjgestionnotificacionmovilservicios.azurewebsites.net/api/OficialNotificador/OficialConCierrePendiente?PCodNotificador=" + codNotificador + "", Activity); // "\"\"" if (!sesionAbierta.Equals("\"\"", StringComparison.Ordinal)) { Console.WriteLine("Sesion abierta"); AlertDialog.Builder alerta = new AlertDialog.Builder(this.Context); alerta.SetTitle("Mensaje de alerta"); alerta.SetIcon(Resource.Drawable.alertaNuevo); alerta.SetMessage("El usuario tiene una jornada abierta."); alerta.SetPositiveButton("Cerrar jornada", HandlePositiveButtonClick); alerta.SetNegativeButton("Continuar", HandleButonContinuar); alerta.SetCancelable(false); alerta.Create(); alerta.Show(); } else { // se inicia la carga de datos para la actividad de buzones(mailboxes) a traves de la actividad splash Toast.MakeText(this.Activity, "Cargando Datos ", ToastLength.Long).Show(); Intent intent = new Intent(this.Activity, typeof(SplashActivity)); StartActivity(intent); } } catch (Exception ex) { Console.WriteLine("Error descargando datos de usuario: " + ex.ToString()); } } } } } catch (WebException webEx) { Console.WriteLine("Error en solicitud Web: " + webEx.ToString()); } } else { AlertDialog.Builder alerta = new AlertDialog.Builder(this.Context); alerta.SetTitle("Mensaje de alerta"); alerta.SetIcon(Resource.Drawable.alertaNuevo); alerta.SetMessage("El servicio de Internet no se encuentra disponible, por favor revise su conexión e intente ingresar nuevamente"); alerta.SetNegativeButton("Salir", HandleButtonClick); alerta.SetCancelable(false); alerta.Create(); alerta.Show(); } } else { Toast.MakeText(this.Activity, "Usted ha digitado un usuario y contraseña incorrecta.", ToastLength.Short).Show(); } } catch (Exception ex) { Console.WriteLine("Error en autenticación " + ex.ToString()); } }; return(view); }
public void CallApi() { progressBar.Visibility = ViewStates.Visible; contentLinearLayout.Visibility = ViewStates.Gone; Task.Factory.StartNew(() => { //UpdateClient var clientInfo = new Models.Request.UpdateClient.Datum { address = address.Text, cellPhone = cellphone.Text, email = email.Text, firstName = name.Text, lastName = lastname.Text, phone = cellphone.Text, ocupation = work.Text, }; var arrayListDataFotUpdate = new Models.Request.UpdateClient.UpdateClientRequest { data = new List <Models.Request.UpdateClient.Datum>(), _id = HomeActivity.GetInstance().clientInfo._id, _rev = HomeActivity.GetInstance().clientInfo._rev, }; arrayListDataFotUpdate.data.Add(clientInfo); var response = ApiService.UpdateInfo( Constants.Url.UpdateClientInfoServicePrefix, arrayListDataFotUpdate).Result; if (!response.IsSuccess) { RunOnUiThread(() => { progressBar.Visibility = ViewStates.Gone; contentLinearLayout.Visibility = ViewStates.Visible; Android.App.AlertDialog.Builder dialo = new AlertDialog.Builder(this); AlertDialog aler = dialo.Create(); aler.SetTitle("ALERTA"); aler.SetMessage("Hubo un error inesperado"); aler.SetButton("ACEPTAR", (c, ev) => { }); aler.SetButton2("CANCEL", (c, ev) => { }); aler.Show(); }); return; } var Client = (Models.Responses.UpdateClient.UpdateClientResponse)response.Result; if (Client.data[0].header.status.Equals("200")) { RunOnUiThread(() => { progressBar.Visibility = Android.Views.ViewStates.Gone; contentLinearLayout.Visibility = Android.Views.ViewStates.Visible; Android.App.AlertDialog.Builder dialogs = new AlertDialog.Builder(this); AlertDialog alerts = dialogs.Create(); alerts.SetTitle("Operación Exitosa"); alerts.SetMessage("Su información ha sido actualizada"); alerts.SetButton("ACEPTAR", (c, ev) => { var intent = new Intent(this, typeof(AccountsActivity)); StartActivity(intent); Finish(); }); alerts.Show(); }); return; } RunOnUiThread(() => { progressBar.Visibility = Android.Views.ViewStates.Gone; contentLinearLayout.Visibility = Android.Views.ViewStates.Visible; Android.App.AlertDialog.Builder dialog = new AlertDialog.Builder(this); AlertDialog alert = dialog.Create(); alert.SetTitle("ALERTA"); alert.SetMessage("Hubo un error inesperado"); alert.SetButton("ACEPTAR", (c, ev) => { }); alert.SetButton2("CANCEL", (c, ev) => { }); alert.Show(); }); return; }); }
/// <summary> /// Saves the details on screen to a new or existing profile to file after validating it. /// Default profiles cannot be edited. /// </summary> private void SaveProfile() { var newSettings = new Settings(); try { newSettings.ProfileName = spinProfiles.SelectedItem.ToString().Trim(); newSettings.Url = edtBackendUrl.Text.Trim(); newSettings.Timeout = Convert.ToInt32(edtBackendTimeout.Text); newSettings.Domain = edtDomain.Text; newSettings.Username = edtUsername.Text; newSettings.Password = EncryptionControl.EncryptWithDeviceID(edtPassword.Text); newSettings.FragmentSize = Convert.ToInt32(edtFragmentSize.Text); newSettings.IsTestInstance = chkIsTestInstance.Checked; } catch (Exception e) { Log.Info("MobuAndroid", "Error while saving invalid settings.", e.Message); } if (!String.IsNullOrEmpty(edtProfileName.Text) && edtProfileName.Text != spinProfiles.SelectedItem.ToString()) { newSettings.ProfileName = edtProfileName.Text; } if (profiles.Any((x => x.IsDefault && x.ProfileName == newSettings.ProfileName))) { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.SetTitle("Cannot Change Default Settings"); alert.SetMessage("You cannot change a default settings profile. Please enter a different name for this new settings profile."); alert.SetNeutralButton("OK", (senderAlert, args) => { }); Dialog dialog = alert.Create(); dialog.Show(); return; } if (!newSettings.IsValid()) { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.SetTitle("Invalid Settings"); alert.SetMessage("Please complete all fields before saving settings."); alert.SetNeutralButton("OK", (senderAlert, args) => { }); Dialog dialog = alert.Create(); dialog.Show(); } else { if (settingsControl.SaveSettingsProfile(newSettings)) { currentProfile = newSettings; profiles = settingsControl.GetSettingsProfiles(); spinProfiles.Adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerDropDownItem, profiles.Select(x => x.ProfileName).ToList()); spinProfiles.SetSelection(profiles.FindIndex(x => x.ProfileName == currentProfile.ProfileName)); AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.SetTitle("Profile saved"); alert.SetMessage("Settings profile " + currentProfile.ProfileName + " saved."); alert.SetNeutralButton("OK", (senderAlert, args) => { }); Dialog dialog = alert.Create(); dialog.Show(); } else { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.SetTitle("Save Failed"); alert.SetMessage("Settings profile " + currentProfile.ProfileName + " could not be saved."); alert.SetNeutralButton("OK", (senderAlert, args) => { }); Dialog dialog = alert.Create(); dialog.Show(); } } }
//need to make this call async to make responsive screen private async void BindVehicleImages() { if (CommonFunctions.IsNetworkConnected()) { Java.IO.File _dir; //Environment.DirectoryPictures = "Images"; _dir = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory + "/RentACar" + "/" + rentRunningTrans.RegNo); //km12akk // Get the latitude and longitude entered by the user and create a query.km12akk";// //string url = "https://uk1.ukvehicledata.co.uk/api/datapackage/VehicleImageData?v=2&api_nullitems=1&auth_apikey=a418b0ad-33ab-4953-9a00-9d3ea8a12319&key_VRM=" + rentRunningTrans.RegNo; // Fetch the vehicle information asynchronously, // parse the results, then update the screen: // objVehicleImageList = await GetVehicleImagesfromAPIAsync(url); // _markdamage.SetBackgroundResource(Resource.Drawable.UK1); // ParseAndDisplay (json); //this.progressLayout.Visibility = ViewStates.Visible; _layoutVehicleImages = FindViewById <LinearLayout>(Resource.Id.layoutVehicleImages); //if (objVehicleImageList != null) { if (_dir.Exists() && _dir.ListFiles().Count() > 0) { Java.IO.File[] _objVehicleImageList = _dir.ListFiles(); //Needed to uncommment for (int i = 0; i < _objVehicleImageList.Count(); i++) //for (int i = 0; i < 6; i++) { ImageView imgVehicle = new ImageView(this); imgVehicle.SetMaxWidth(60); imgVehicle.SetMaxHeight(60); imgVehicle.LayoutParameters = new LinearLayout.LayoutParams(150, 150); imgVehicle.Visibility = ViewStates.Visible; imgVehicle.Id = i + 1; //var imageBitmap =CommonFunctions.GetBitmapFromUrl(objVehicleImageList.Response.DataItems.VehicleImages.ImageDetailsList[i].ImageUrl); // imgVehicle.SetImageBitmap(imageBitmap); imgVehicle.SetImageURI(Android.Net.Uri.Parse(_objVehicleImageList[i].AbsolutePath)); //imgVehicle.SetBackgroundResource(Resource.Drawable.CarExterior); imgVehicle.SetOnClickListener(this); // add into my parent view _layoutVehicleImages.AddView(imgVehicle); } //objVehicleImageList["DataItems"]["VehicleImages"]["ImageDetailsList"] } else { try { ImageView imgVehicle = new ImageView(this); imgVehicle.SetMaxWidth(60); imgVehicle.SetMaxHeight(60); LinearLayout.LayoutParams obj = new LinearLayout.LayoutParams(150, 150); obj.SetMargins(5, 5, 5, 5); //imgVehicle.LayoutParameters = new LinearLayout.LayoutParams(150, 150); imgVehicle.Visibility = ViewStates.Visible; // LinearLayout.LayoutParams obj = new LinearLayout.LayoutParams(100, 100); //obj.SetMargins(5,5,5,5); imgVehicle.LayoutParameters = obj; if (rentRunningTrans.VehicleType == "Car") { imgVehicle.Id = 101; imgVehicle.SetBackgroundResource(Resource.Drawable.CarExterior); imgVehicle.SetOnClickListener(this); //imgVehicle.SetPadding(10, 10, 10, 10); // add into my parent view _layoutVehicleImages.AddView(imgVehicle); ImageView imgVehicleInterior = new ImageView(this); imgVehicleInterior.SetMaxWidth(60); imgVehicleInterior.SetMaxHeight(60); //LinearLayout.LayoutParams objj = new LinearLayout.LayoutParams(150, 150); //obj.SetMargins(5, 5, 5, 5); imgVehicleInterior.LayoutParameters = obj; // imgVehicleInterior.LayoutParameters = new LinearLayout.LayoutParams(150, 150); imgVehicleInterior.Visibility = ViewStates.Visible; imgVehicleInterior.Id = 102; imgVehicleInterior.SetBackgroundResource(Resource.Drawable.VehicleInteriorImg); imgVehicleInterior.SetOnClickListener(this); //imgVehicleInterior.SetPadding(10, 10, 10, 10); _layoutVehicleImages.AddView(imgVehicleInterior); _markdamage.SetBackgroundResource(Resource.Drawable.CarExterior); iCurrentDamageImageId = 101; } else if (rentRunningTrans.VehicleType == "Luton Van") { imgVehicle.Id = 201; imgVehicle.SetBackgroundResource(Resource.Drawable.LutonVan); imgVehicle.SetOnClickListener(this); // add into my parent view _layoutVehicleImages.AddView(imgVehicle); _markdamage.SetBackgroundResource(Resource.Drawable.LutonVan); iCurrentDamageImageId = 201; } else if (rentRunningTrans.VehicleType == "Standard Van") { imgVehicle.Id = 301; imgVehicle.SetBackgroundResource(Resource.Drawable.StandardVan); imgVehicle.SetOnClickListener(this); // add into my parent view _layoutVehicleImages.AddView(imgVehicle); _markdamage.SetBackgroundResource(Resource.Drawable.StandardVan); iCurrentDamageImageId = 301; } _markdamage.RemoveAllViews(); _markdamage.SetOnTouchListener(this); _markdamage.SetOnDragListener(this); if (rentRunningTrans.RentVehicleDamage != null) { foreach (var objVehicleMarkDamage in rentRunningTrans.RentVehicleDamage.Where(x => x.DamageImageId == iCurrentDamageImageId).OrderBy(x => x.DamageNumber)) { this.DrawDamageCircle(objVehicleMarkDamage); iLastDamageNumber = objVehicleMarkDamage.DamageNumber; } } } catch (Exception ex) { //Do nothing } } } } else { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.SetMessage("Please enable internet to get vehicle images from API."); alert.SetNeutralButton("OK", delegate { }); alert.Create().Show(); } //this.progressLayout.Visibility = ViewStates.Gone; }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); // メイン画面からそれぞれのボタンを取得します。 _SpinnerUserLists = FindViewById <Spinner>(Resource.Id.spinnerUserLists); _TimeStamp = FindViewById <Button>(Resource.Id.buttonStamp); _ToggleAttendance = FindViewById <ToggleButton>(Resource.Id.toggleAttendance); _ToConfig = FindViewById <Button>(Resource.Id.buttonToConfig); // コンフィグファイルを読み取ります。 _EntityConfig = _ConfigLocalStorage.Read(); // ユーザーリスト取得インスタンスです。 try { _UserList = new DAO.CsvToUserList(_EntityConfig); // 取得したユーザーリストをユーザーセレクトボックスに設定します。 ArrayAdapter <string> adapter = new ArrayAdapter <string>(this, Android.Resource.Layout.SimpleSpinnerItem, _UserList.GetUserLists()); adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); _SpinnerUserLists.Adapter = adapter; } catch (SmbException e) { _TimeStamp.Enabled = false; Utility.LocalIPAddress LocalIPAddress = new Utility.LocalIPAddress(); System.Collections.Generic.List <System.Net.IPAddress> localadr = LocalIPAddress.GetLocalIPAddress(); string localIP = localadr[0].ToString(); Toast.MakeText(this, localIP, ToastLength.Long).Show(); //Toast.MakeText(this, "サーバー接続エラーが発生しました。\n エラー内容:" + e, ToastLength.Long).Show(); var dlg = new AlertDialog.Builder(this); dlg.SetTitle("エラー"); dlg.SetMessage("サーバー接続エラーが発生しました。\n エラー内容:" + e.StackTrace.ToString()); dlg.SetPositiveButton( //OKボタンの処理 "OK", (s, a) => Toast.MakeText(this, "OK", ToastLength.Short).Show()); dlg.SetNegativeButton( //Cancelボタンの処理 "Cancel", (s, a) => Toast.MakeText(this, "Cancel", ToastLength.Short).Show()); dlg.Create().Show(); } // 打刻ボタンクリック時の挙動です。 _TimeStamp.Click += delegate { TimeStamp_onClick(); }; _ToConfig.Click += delegate { ToConfig_onClick(); }; }
public Task <string> DisplayAlertAsync(string title, string message, string cancel, params string[] buttons) { var activity = (MainActivity)CrossCurrentActivity.Current.Activity; if (activity == null) { return(Task.FromResult <string>(null)); } var result = new TaskCompletionSource <string>(); var alertBuilder = new AlertDialog.Builder(activity); alertBuilder.SetTitle(title); if (!string.IsNullOrWhiteSpace(message)) { if (buttons != null && buttons.Length > 2) { if (!string.IsNullOrWhiteSpace(title)) { alertBuilder.SetTitle($"{title}: {message}"); } else { alertBuilder.SetTitle(message); } } else { alertBuilder.SetMessage(message); } } if (buttons != null) { if (buttons.Length > 2) { alertBuilder.SetItems(buttons, (sender, args) => { result.TrySetResult(buttons[args.Which]); }); } else { if (buttons.Length > 0) { alertBuilder.SetPositiveButton(buttons[0], (sender, args) => { result.TrySetResult(buttons[0]); }); } if (buttons.Length > 1) { alertBuilder.SetNeutralButton(buttons[1], (sender, args) => { result.TrySetResult(buttons[1]); }); } } } if (!string.IsNullOrWhiteSpace(cancel)) { alertBuilder.SetNegativeButton(cancel, (sender, args) => { result.TrySetResult(cancel); }); } var alert = alertBuilder.Create(); alert.CancelEvent += (o, args) => { result.TrySetResult(null); }; alert.Show(); return(result.Task); }
public override Dialog OnCreateDialog(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); var builder = new AlertDialog.Builder(Activity); var inflater = Activity.LayoutInflater; var dialogView = inflater.Inflate(Resource.Layout.ReportDialogView, null); if (dialogView != null) { monthTV = dialogView.FindViewById <TextView>(Resource.Id.textMonth); yearTV = dialogView.FindViewById <TextView>(Resource.Id.textYear); catTV = dialogView.FindViewById <TextView>(Resource.Id.textRepCategory); expensesTV = dialogView.FindViewById <TextView>(Resource.Id.textRepExpenses); realExpensesTV = dialogView.FindViewById <TextView>(Resource.Id.textRealExpenses); spinner = dialogView.FindViewById <Spinner>(Resource.Id.spinnerRep); GetTVText(); startDate = new DateTime(selectedYear, selectedMonth, 1); endDate = startDate.AddMonths(1).AddDays(-1); LoadSpinnerData(); spinner.ItemSelected += Spinner_ItemSelected; spinner.SetSelection(1); using (var db = new ExpenseManager()) { expensesSum = db.GetItemsByDates(startDate, endDate).Sum(a => a.Amount); } expensesTV.Text = expensesSum.ToString(); SetAmounts(); if (startAmount == -1 || endAmount == -1) { realExpensesTV.Text = "Brak wystarczających danych"; } else { using (var db = new IncomeManager()) { incomesSum = db.GetItemsByDates(startDate, endDate).Sum(a => a.Amount); } realSum = startAmount + (float)incomesSum - endAmount; realExpensesTV.Text = realSum.ToString(); } builder.SetView(dialogView); builder.SetNeutralButton("Wróć", HandleNeutralButtonClick); } var dialog = builder.Create(); return(dialog); }
private void SamplePageContents(Android.Content.Context con) { //Title list Title.Add("Software"); Title.Add("Banking"); Title.Add("Media"); Title.Add("Medical"); //jobSearchLabel jobSearchLabel = new TextView(con); jobSearchLabel.Text = "Job Search"; jobSearchLabel.TextSize = 30; jobSearchLabel.Typeface = Typeface.DefaultBold; //jobSearchLabelSpacing jobSearchLabelSpacing = new TextView(con); jobSearchLabelSpacing.SetHeight(40); //countryLabel countryLabel = new TextView(con); countryLabel.Text = "Country"; countryLabel.TextSize = 16; //countryLabelSpacing countryLabelSpacing = new TextView(con); countryLabelSpacing.SetHeight(10); //countryAutoCompleteSpacing countryAutoCompleteSpacing = new TextView(con); countryAutoCompleteSpacing.SetHeight(30); //jobFieldLabel jobFieldLabel = new TextView(con); jobFieldLabel.Text = "Job Field"; jobFieldLabel.TextSize = 16; //jobFieldLabelSpacing jobFieldLabelSpacing = new TextView(con); jobFieldLabelSpacing.SetHeight(10); //jobFieldAutoCompleteSpacing jobFieldAutoCompleteSpacing = new TextView(con); jobFieldAutoCompleteSpacing.SetHeight(30); //experienceLabel experienceLabel = new TextView(con); experienceLabel.Text = "Experience"; experienceLabel.TextSize = 16; //experienceLabelSpacing experienceLabelSpacing = new TextView(con); experienceLabelSpacing.SetHeight(10); //Experience list Experience.Add("1"); Experience.Add("2"); //searchButton searchButton = new Button(con); searchButton.SetWidth(ActionBar.LayoutParams.MatchParent); searchButton.SetHeight(40); searchButton.Text = "Search"; searchButton.SetTextColor(Color.White); searchButton.SetBackgroundColor(Color.Gray); searchButton.Click += (object sender, EventArgs e) => { GetResult(); resultsDialog.SetMessage(jobNumber + " Jobs Found"); resultsDialog.Create().Show(); }; //searchButtonSpacing searchButtonSpacing = new TextView(con); searchButtonSpacing.SetHeight(30); //experience Spinner experienceSpinner = new Spinner(con, SpinnerMode.Dialog); experienceSpinner.DropDownWidth = 500; experienceSpinner.SetBackgroundColor(Color.Gray); ArrayAdapter <String> experienceDataAdapter = new ArrayAdapter <String> (con, Android.Resource.Layout.SimpleSpinnerItem, Experience); experienceDataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); experienceSpinner.Adapter = experienceDataAdapter; //experienceSpinnerSpacing experienceSpinnerSpacing = new TextView(con); experienceSpinnerSpacing.SetHeight(30); //results dialog resultsDialog = new AlertDialog.Builder(con); resultsDialog.SetTitle("Results"); resultsDialog.SetPositiveButton("OK", (object sender, DialogClickEventArgs e) => { }); resultsDialog.SetCancelable(true); }
private static AlertDialogInfo CreateDialog(string content, string title, string okText = null, string cancelText = null, Action<bool> afterHideCallbackWithResponse = null) { var tcs = new TaskCompletionSource<bool>(); var builder = new AlertDialog.Builder(AppCompatActivityBase.CurrentActivity); builder.SetMessage(content); builder.SetTitle(title); var dialog = (AlertDialog)null; builder.SetPositiveButton(okText ?? "OK", (d, index) => { tcs.TrySetResult(true); if (dialog != null) { dialog.Dismiss(); dialog.Dispose(); } if (afterHideCallbackWithResponse == null) return; afterHideCallbackWithResponse(true); }); if (cancelText != null) { builder.SetNegativeButton(cancelText, (d, index) => { tcs.TrySetResult(false); if (dialog != null) { dialog.Dismiss(); dialog.Dispose(); } if (afterHideCallbackWithResponse == null) return; afterHideCallbackWithResponse(false); }); } builder.SetOnDismissListener(new OnDismissListener(() => { tcs.TrySetResult(false); if (afterHideCallbackWithResponse == null) return; afterHideCallbackWithResponse(false); })); dialog = builder.Create(); return new AlertDialogInfo { Dialog = dialog, Tcs = tcs }; }
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup listContainer = (ViewGroup)base.OnCreateView(inflater, container, savedInstanceState); TextView proj = new TextView(inflater.Context); proj.Gravity = GravityFlags.Center; ComplexUnitType ct = ComplexUnitType.Dip; proj.SetTextSize(ct, 20); proj.Text = _projectName; SwipeRefreshLayout srl = new SwipeRefreshLayout(inflater.Context); //srl.AddView(listContainer, ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); srl.LayoutParameters = ( new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent)); LinearLayout ll = new LinearLayout(inflater.Context); ll.Orientation = Orientation.Vertical; LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); lp2.Gravity = GravityFlags.Center; proj.LayoutParameters = lp2; View ruler = new View(inflater.Context); ruler.SetBackgroundColor(Color.Gray); ll.AddView(proj); ll.AddView(ruler, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 2)); ll.AddView(listContainer); //ll.AddView(srl); empty = new TextView(this.Activity) { Text = "No Content Found", Visibility = ViewStates.Gone, LayoutParameters = ( new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent)) }; empty.SetTextSize(ct, 25); ll.AddView(empty); _si = new ListOfProjects.Scrollinput(srl); srl.Refresh += async delegate { try { await AddData(((MainActivity)Activity).Ctrl, _projectId); srl.Refreshing = false; } catch (CannotReachServerException) { AlertDialog.Builder builder = new AlertDialog.Builder(Activity); builder.SetTitle("Unable to Connect") .SetMessage("Please check your network connection and try again") .SetNeutralButton("Okay", (sender, args) => { builder.Dispose(); }) .SetCancelable(false); AlertDialog alert = builder.Create(); alert.Show(); } catch (StatusNotOkayException se) { AlertDialog.Builder builder = new AlertDialog.Builder(Activity); builder.SetTitle("An Error has occured") .SetMessage("Error :" + se.GetMessage()) .SetNeutralButton("Okay", (sender, args) => { builder.Dispose(); }) .SetCancelable(false); AlertDialog alert = builder.Create(); alert.Show(); } catch (Exception e) { // For any other weird exceptions AlertDialog.Builder builder = new AlertDialog.Builder(Activity); builder.SetTitle("An Error has occured") .SetNeutralButton("Okay", (sender, args) => { builder.Dispose(); }) .SetMessage("Error :" + e.Message) .SetCancelable(false); AlertDialog alert = builder.Create(); alert.Show(); } }; return(ll); }
async void getLastKnownLocation() { try { var location = await Geolocation.GetLastKnownLocationAsync(); if (location != null) { lat = location.Latitude.ToString(); lon = location.Longitude.ToString(); } else { test.Text = "Can't find location"; } } catch (FeatureNotSupportedException fnsEx) { // Handle not supported on device exception AlertDialog.Builder alert = new AlertDialog.Builder(Context as Activity); alert.SetTitle("Failed"); alert.SetMessage(fnsEx.ToString()); alert.SetPositiveButton("Okay", (senderAlert, args) => { Toast.MakeText(Context as Activity, "Okay", ToastLength.Short).Show(); }); Dialog dialog = alert.Create(); dialog.Show(); } catch (FeatureNotEnabledException fneEx) { AlertDialog.Builder alert = new AlertDialog.Builder(Context as Activity); alert.SetTitle("Failed"); alert.SetMessage(fneEx.ToString()); alert.SetPositiveButton("Okay", (senderAlert, args) => { Toast.MakeText(Context as Activity, "Okay", ToastLength.Short).Show(); }); Dialog dialog = alert.Create(); dialog.Show(); } catch (PermissionException pEx) { AlertDialog.Builder alert = new AlertDialog.Builder(Context as Activity); alert.SetTitle("Failed"); alert.SetMessage(pEx.ToString()); alert.SetPositiveButton("Okay", (senderAlert, args) => { Toast.MakeText(Context as Activity, "Okay", ToastLength.Short).Show(); }); Dialog dialog = alert.Create(); dialog.Show(); } catch (Exception ex) { AlertDialog.Builder alert = new AlertDialog.Builder(Context as Activity); alert.SetTitle("Failed"); alert.SetMessage(ex.ToString()); alert.SetPositiveButton("Okay", (senderAlert, args) => { Toast.MakeText(Context as Activity, "Okay", ToastLength.Short).Show(); }); Dialog dialog = alert.Create(); dialog.Show(); } }
private async Task AddData(Controller ctrl, string projectId) { try { var output = await ctrl.GetTasks(AccountStorage.DataSet, projectId); System.Diagnostics.Debug.WriteLine(output.Count); var listAdapter = new TaskAdapter(Activity, Android.Resource.Layout.SimpleListItem1, output.ToArray()); ListView.Adapter = listAdapter; SetListShown(true); if (listAdapter.Count == 0) { empty.Visibility = ViewStates.Visible; } else { ListView.SetSelection(listAdapter.Count - 1); } //ListView.SmoothScrollByOffset(listAdapter.Count -1); // ListView.SmoothScrollToPosition(listAdapter.Count - 1); } catch (CannotReachServerException) { AlertDialog.Builder builder = new AlertDialog.Builder(Activity); builder.SetTitle("Unable to Connect") .SetMessage("Please check your network connection and try again") .SetNeutralButton("Okay", (sender, args) => { builder.Dispose(); ((MainActivity)Activity).FragmentManager.PopBackStack(); }) .SetCancelable(false); AlertDialog alert = builder.Create(); alert.Show(); } catch (WebException we) { if (we.Status == WebExceptionStatus.ProtocolError) { var response = we.Response as HttpWebResponse; if (response != null) { Console.WriteLine("HTTP Status Code: " + (int)response.StatusCode); if (response.StatusCode == HttpStatusCode.Forbidden) { try { Toast.MakeText(this.Activity, "Username and password error.", ToastLength.Long).Show(); System.Diagnostics.Debug.WriteLine("We are about to logout"); AccountStorage.ClearStorage(); System.Diagnostics.Debug.WriteLine("Main Activity is :" + Activity == null); System.Diagnostics.Debug.WriteLine("Items in the backstack :" + Activity.FragmentManager.BackStackEntryCount); System.Diagnostics.Debug.WriteLine("Main Activity is :" + Activity == null); Activity.FragmentManager.PopBackStack(null, PopBackStackFlags.Inclusive); System.Diagnostics.Debug.WriteLine("Items in the backstack 2 :" + Activity.FragmentManager.BackStackEntryCount); ((MainActivity)(Activity)).SetDrawerState(false); ((MainActivity)(Activity)).SwitchToFragment(MainActivity.FragmentTypes.Login); } catch (System.Exception e) { System.Diagnostics.Debug.WriteLine("We encountered an error :" + e.Message); } } } else { // no http status code available Toast.MakeText(Activity, "Unable to load the data. Please restart the application.", ToastLength.Short).Show(); } } else { // no http status code availableToast.MakeText(Activity, "Unable to load the data. Please restart the application.", ToastLength.Short).Show(); } } catch (StatusNotOkayException se) { AlertDialog.Builder builder = new AlertDialog.Builder(Activity); builder.SetTitle("An Error has occured") .SetMessage("Error :" + se.GetMessage()) .SetNeutralButton("Okay", (sender, args) => { builder.Dispose(); }) .SetCancelable(false); AlertDialog alert = builder.Create(); alert.Show(); } catch (Exception e) { // For any other weird exceptions AlertDialog.Builder builder = new AlertDialog.Builder(Activity); builder.SetTitle("An Error has occured") .SetNeutralButton("Okay", (sender, args) => { builder.Dispose(); }) .SetMessage("Error :" + e.Message) .SetCancelable(false); AlertDialog alert = builder.Create(); alert.Show(); } }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.UserMenu); EditText accountEditText = FindViewById <EditText>(Resource.Id.accountNaamEditText); EditText passwordEditText = FindViewById <EditText>(Resource.Id.wachtwoordEditText); Button logInButton = FindViewById <Button>(Resource.Id.loginButton); Button createAccountButton = FindViewById <Button>(Resource.Id.createAccountBtn); passwordEditText.InputType = Android.Text.InputTypes.TextVariationPassword | Android.Text.InputTypes.ClassText; logInButton.Click += delegate { if (string.IsNullOrEmpty(accountEditText.Text)) { messageHandler(4); } else if (string.IsNullOrEmpty(passwordEditText.Text)) { messageHandler(5); } else { gebruiker = model.credentialCheck(accountEditText.Text, passwordEditText.Text); if (gebruiker == null) { messageHandler(6); } else { messageHandler(7); } } }; createAccountButton.Click += delegate { if (string.IsNullOrEmpty(passwordEditText.Text)) { messageHandler(1); } else { if (model.checkIfAccountExists(accountEditText.Text, passwordEditText.Text)) { messageHandler(2); } else if (!model.checkIfAccountExists(accountEditText.Text, passwordEditText.Text)) { if (model.createAccount(accountEditText.Text, passwordEditText.Text)) { messageHandler(3); } } } }; void messageHandler(int switchId) { switch (switchId) { case 1: Android.App.AlertDialog.Builder popupMessage1 = new AlertDialog.Builder(this); AlertDialog alert1 = popupMessage1.Create(); alert1.SetTitle("Account maken mislukt!"); alert1.SetMessage("Het wachtwoord mag niet leeg zijn."); alert1.SetButton("OK", (c, ev) => { accountEditText.Text = ""; passwordEditText.Text = ""; }); alert1.Show(); break; case 2: Android.App.AlertDialog.Builder popupMessage2 = new AlertDialog.Builder(this); AlertDialog alert2 = popupMessage2.Create(); alert2.SetTitle("Account maken mislukt!"); alert2.SetMessage("Het aanmaken van het account is mislukt, deze accountnaam bestaat al."); alert2.SetButton("OK", (c, ev) => { accountEditText.Text = ""; passwordEditText.Text = ""; }); alert2.Show(); break; case 3: Android.App.AlertDialog.Builder popupMessage3 = new AlertDialog.Builder(this); AlertDialog alert3 = popupMessage3.Create(); alert3.SetTitle("Account maken gelukt!"); alert3.SetMessage("U kunt nu inloggen."); alert3.SetButton("OK", (c, ev) => { accountEditText.Text = ""; passwordEditText.Text = ""; }); alert3.Show(); break; case 4: Android.App.AlertDialog.Builder popupMessage4 = new AlertDialog.Builder(this); AlertDialog alert4 = popupMessage4.Create(); alert4.SetTitle("Inloggen mislukt!"); alert4.SetMessage("Account naam mag niet leeg zijn bij het inloggen."); alert4.SetButton("OK", (c, ev) => { accountEditText.Text = ""; passwordEditText.Text = ""; }); alert4.Show(); break; case 5: Android.App.AlertDialog.Builder popupMessage5 = new AlertDialog.Builder(this); AlertDialog alert5 = popupMessage5.Create(); alert5.SetTitle("Inloggen mislukt!"); alert5.SetMessage("Wachtwoord mag niet leeg zijn."); alert5.SetButton("OK", (c, ev) => { accountEditText.Text = ""; passwordEditText.Text = ""; }); alert5.Show(); break; case 6: Android.App.AlertDialog.Builder popupMessage6 = new AlertDialog.Builder(this); AlertDialog alert6 = popupMessage6.Create(); alert6.SetTitle("Inloggen mislukt!"); alert6.SetMessage("Het wachtwoord en/of gebruikersnaam is onjuist."); alert6.SetButton("OK", (c, ev) => { accountEditText.Text = ""; passwordEditText.Text = ""; }); alert6.Show(); break; case 7: Android.App.AlertDialog.Builder popupMessage7 = new AlertDialog.Builder(this); AlertDialog alert7 = popupMessage7.Create(); alert7.SetTitle("Inloggen gelukt!"); alert7.SetMessage("Door op ok te klikken zal u teruggaan naar het hoofdmenu."); alert7.SetButton("OK", (c, ev) => { accountEditText.Text = ""; passwordEditText.Text = ""; Intent myIntent = new Intent(this, typeof(MainActivity)); myIntent.PutExtra("userId", gebruiker.id.ToString()); SetResult(Result.Ok, myIntent); Finish(); }); alert7.Show(); break; } } }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.LA_Editar_Nota); // Create your application here //Pega o título e a descrição e exibem para edição EditText titulo = (EditText)FindViewById(Resource.Id.ET_Ed_Nota_Titulo); EditText descricao = (EditText)FindViewById(Resource.Id.ET_Ed_Nota_Descricao); titulo.Text = Intent.GetStringExtra("titulo"); descricao.Text = Intent.GetStringExtra("descricao"); Button voltar_Para_Ver_Notas = FindViewById <Button>(Resource.Id.BT_Ed_Nota_Voltar); voltar_Para_Ver_Notas.Click += delegate { var verNota = new Intent(this, typeof(AC_VerNotas)); verNota.PutExtra("codigoUsuario", Intent.GetStringExtra("codigoUsuario")); StartActivity(verNota); }; //Método para exibir um alerta e confirmar se a edição //é para ser concluída. Button confirmar_Edicao_Notas = FindViewById <Button>(Resource.Id.BT_Ed_Nota_Confirmar); confirmar_Edicao_Notas.Click += delegate { AlertDialog.Builder alerta = new AlertDialog.Builder(this); alerta.SetTitle("Alerta!"); alerta.SetIcon(Android.Resource.Drawable.IcDialogInfo); alerta.SetMessage("Deseja alterar a nota"); alerta.SetPositiveButton("Editar", (senderAlert, args) => { Banco banco = new Banco(); string codNota = Intent.GetStringExtra("codigoNota"); string tituloNota = titulo.Text; string descricaoNota = descricao.Text; banco.EditarNota(codNota, tituloNota, descricaoNota); FuncoesAlerta funcoes = new FuncoesAlerta(); funcoes.LimparTextEdit(titulo, descricao); Toast.MakeText(this, "Salvo com sucesso!", ToastLength.Short).Show(); }); alerta.SetNegativeButton("Voltar", (senderAlert, args) => { var verNota = new Intent(this, typeof(AC_VerNotas)); verNota.PutExtra("codigoUsuario", Intent.GetStringExtra("codigoUsuario")); StartActivity(verNota); Toast.MakeText(this, "Cancelado !", ToastLength.Short).Show(); }); Dialog dialog = alerta.Create(); dialog.Show(); }; //Método para exibir uma alerta e confirmar se o usuário deseja //excluir a nota Button apagar_Nota = FindViewById <Button>(Resource.Id.BT_Ed_Apagar_Notar); apagar_Nota.Click += delegate { AlertDialog.Builder alerta = new AlertDialog.Builder(this); alerta.SetTitle("Alerta!"); alerta.SetIcon(Android.Resource.Drawable.AlertDarkFrame); alerta.SetMessage("Deseja apagar a nota"); alerta.SetPositiveButton("Apagar", (senderAlert, args) => { Banco banco = new Banco(); string codNota = Intent.GetStringExtra("codigoNota"); banco.ApagarNota(codNota); FuncoesAlerta funcoes = new FuncoesAlerta(); funcoes.LimparTextEdit(titulo, descricao); Toast.MakeText(this, "Nota apagada!", ToastLength.Short).Show(); }); alerta.SetNegativeButton("Voltar", (senderAlert, args) => { }); Dialog dialog = alerta.Create(); dialog.Show(); }; }
void CargaInformacionConResultado(string tipoMensajeFinal) { var progress2 = new ProgressDialog(this); progress2.Indeterminate = true; progress2.SetProgressStyle(ProgressDialogStyle.Spinner); progress2.SetMessage("Actualizando información..."); progress2.SetCancelable(false); progress2.Show(); new Thread(new ThreadStart(delegate { Thread.Sleep(2000); string resultadoMetodo = string.Empty; RunOnUiThread(() => { #region prueba //progress2.Hide(); //progress2.Dispose(); //AlertDialog.Builder alert2 = new AlertDialog.Builder(this); //alert2.SetTitle("Información"); //alert2.SetMessage(resultadoMetodo); //alert2.SetPositiveButton("Cerrar", (senderAlert, args) => //{ // var intent = new Intent(this, typeof(MainActivity)); // intent.PutExtra("usuarioinformacion", usuarioinformacion); // RunOnUiThread(() => // { // StartActivity(intent); // }); //}); //alert2.SetNegativeButton("SI", (senderAlert, args) => //{ // CargaInformacionConResultado(tipoMensajeFinal); //}); //Dialog dialog2 = alert2.Create(); //dialog2.Show(); #endregion #region funciona try { var client = new RestClient(urlWebAPI); var request = new RestRequest("api/Procesos/AutenticarUsuario", Method.POST); request.AddObject(new UsuarioBO { Usuario = citaSeleccionada.Usuario, Password = citaSeleccionada.Password }); IRestResponse response = client.Execute(request); if (!string.IsNullOrEmpty(response.Content)) { AutenticarUsuarioResult resultado = Newtonsoft.Json.JsonConvert.DeserializeObject <AutenticarUsuarioResult>(response.Content); if (resultado != null) { citas = resultado.lista; Spinner spinner = FindViewById <Spinner>(Resource.Id.spinner1); spinner.Adapter = new CitasAdapter(this, citas); //spinner.SetSelection(position); if (tipoMensajeFinal == "CI") { spinner.SetSelection(position); progress2.Hide(); progress2.Dispose(); AlertDialog.Builder alert2 = new AlertDialog.Builder(this); alert2.SetTitle("Información"); alert2.SetMessage("Check-In realizado correctamente."); alert2.SetPositiveButton("Aceptar", (senderAlert, args) => { }); Dialog dialog2 = alert2.Create(); dialog2.Show(); } else if (tipoMensajeFinal == "CO") { progress2.Hide(); progress2.Dispose(); AlertDialog.Builder alert2 = new AlertDialog.Builder(this); alert2.SetTitle("Información"); alert2.SetMessage("Check-Out realizado correctamente."); alert2.SetPositiveButton("Aceptar", (senderAlert, args) => { }); Dialog dialog2 = alert2.Create(); dialog2.Show(); } } } else { resultadoMetodo = "Revise su conexión a internet, ¿desea volver a intentar cargar la información del CRM?"; } } catch (Exception ex) { resultadoMetodo = "El siguiente error se ha generado:" + ex.Message + " , ¿desea volver a intentar cargar la información del CRM?"; } if (!string.IsNullOrEmpty(resultadoMetodo)) { progress2.Hide(); progress2.Dispose(); AlertDialog.Builder alert2 = new AlertDialog.Builder(this); alert2.SetTitle("Información"); alert2.SetMessage(resultadoMetodo); alert2.SetPositiveButton("Cerrar", (senderAlert, args) => { var intent = new Intent(this, typeof(MainActivity)); intent.PutExtra("usuarioinformacion", usuarioinformacion); RunOnUiThread(() => { StartActivity(intent); }); }); alert2.SetNegativeButton("SI", (senderAlert, args) => { CargaInformacionConResultado(tipoMensajeFinal); }); Dialog dialog2 = alert2.Create(); dialog2.Show(); } #endregion }); })).Start(); }
void InternalSetPage(Page page) { if (!Forms.IsInitialized) { throw new InvalidOperationException("Call Forms.Init (Activity, Bundle) before this"); } if (_canvas != null) { _canvas.SetPage(page); return; } var busyCount = 0; MessagingCenter.Subscribe(this, Page.BusySetSignalName, (Page sender, bool enabled) => { busyCount = Math.Max(0, enabled ? busyCount + 1 : busyCount - 1); UpdateProgressBarVisibility(busyCount > 0); }); UpdateProgressBarVisibility(busyCount > 0); MessagingCenter.Subscribe(this, Page.AlertSignalName, (Page sender, AlertArguments arguments) => { AlertDialog alert = new AlertDialog.Builder(this).Create(); alert.SetTitle(arguments.Title); alert.SetMessage(arguments.Message); if (arguments.Accept != null) { alert.SetButton((int)DialogButtonType.Positive, arguments.Accept, (o, args) => arguments.SetResult(true)); } alert.SetButton((int)DialogButtonType.Negative, arguments.Cancel, (o, args) => arguments.SetResult(false)); alert.CancelEvent += (o, args) => { arguments.SetResult(false); }; alert.Show(); }); MessagingCenter.Subscribe(this, Page.ActionSheetSignalName, (Page sender, ActionSheetArguments arguments) => { var builder = new AlertDialog.Builder(this); builder.SetTitle(arguments.Title); string[] items = arguments.Buttons.ToArray(); builder.SetItems(items, (sender2, args) => { arguments.Result.TrySetResult(items[args.Which]); }); if (arguments.Cancel != null) { builder.SetPositiveButton(arguments.Cancel, delegate { arguments.Result.TrySetResult(arguments.Cancel); }); } if (arguments.Destruction != null) { builder.SetNegativeButton(arguments.Destruction, delegate { arguments.Result.TrySetResult(arguments.Destruction); }); } AlertDialog dialog = builder.Create(); builder.Dispose(); //to match current functionality of renderer we set cancelable on outside //and return null dialog.SetCanceledOnTouchOutside(true); dialog.CancelEvent += (sender3, e) => { arguments.SetResult(null); }; dialog.Show(); }); _canvas = new Platform(this); if (_application != null) { _application.Platform = _canvas; } _canvas.SetPage(page); _layout.AddView(_canvas.GetViewGroup()); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); this.SetContentView(Resource.Layout.editlayout); patient = FindViewById <EditText>(Resource.Id.numpat3); gef = FindViewById <EditText>(Resource.Id.codgef3); lot = FindViewById <EditText>(Resource.Id.numlot3); quantite = FindViewById <EditText>(Resource.Id.qtedel3); date = FindViewById <EditText>(Resource.Id.datedel3); pages = FindViewById <TextView>(Resource.Id.textpages); enregistrer = FindViewById <Button>(Resource.Id.buttonenr3); suivant = FindViewById <Button>(Resource.Id.buttonnext3); prev = FindViewById <Button>(Resource.Id.buttonprev3); supprimer = FindViewById <Button>(Resource.Id.delbt1); raz = FindViewById <Button>(Resource.Id.buttonreset2); FillandRefresh(); date.Click += (s, e) => { DatePickerDialog datepick = new DatePickerDialog(this, AlertDialog.ThemeDeviceDefaultLight, OnDateSet, DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day); datepick.DatePicker.DateTime = DateTime.Today; datepick.Show(); }; raz.Click += (s, e) => { if (!string.IsNullOrEmpty(patient.Text) || !string.IsNullOrEmpty(gef.Text) || !string.IsNullOrEmpty(lot.Text) || !string.IsNullOrEmpty(quantite.Text) || quantite.Text != "0" || !string.IsNullOrEmpty(date.Text)) { Android.App.AlertDialog.Builder dialog = new AlertDialog.Builder(this); AlertDialog alert = dialog.Create(); alert.SetTitle("Attention"); alert.SetMessage("Les champs de texte seront vidés"); alert.SetButton("OK", (c, ev) => { //Vide les champs date.Text = ""; quantite.Text = ""; lot.Text = ""; gef.Text = ""; patient.Text = ""; Toast.MakeText(Application.Context, "Champs réinitialisés", ToastLength.Short).Show(); }); alert.SetButton2("Annuler", (c, ev) => { //Ne rien faire }); alert.Show(); } }; suivant.Click += (s, e) => { if (ligne < lines.Count() - 1) { ligne++; pages.Text = "Page " + ligne.ToString() + " sur " + totalpages.ToString(); fillform(listItems = lines[ligne].Split(';').ToList()); } }; prev.Click += (s, e) => { if (ligne > 1) { ligne--; pages.Text = "Page " + ligne.ToString() + " sur " + totalpages.ToString(); fillform(listItems = lines[ligne].Split(';').ToList()); } }; enregistrer.Click += (s, e) => { var newline = string.Format("{0};{1};{2};{3};{4};{5}", patient.Text, gef.Text, lot.Text, quantite.Text, date.Text, Settings.Username); ReadReplace(ligne, newline); FillandRefresh(); }; supprimer.Click += (s, e) => { Readdelete(ligne); FillandRefresh(); }; // Create your application here }
void OnClick() { var picker = Element as CoolPicker; var layout = new LinearLayout(Context) { Orientation = wOrientation.Vertical }; if (picker.Items == null || picker.Items.Count == 0) { var confirm = new AlertDialog.Builder(Context); layout.AddView(new EditText(Context) { Text = "リストが設定されていません。", Focusable = false }); layout.SetBackgroundColor(picker.PickerColor.ToAndroid()); confirm.SetTitle("!"); confirm.SetView(layout); confirm.SetPositiveButton(global::Android.Resource.String.Ok, (s, e) => { confirmView = null; }); confirmView = confirm.Create(); confirm.Show(); return; } var dataPicker = new CoolDataPicker(Context) { BackgroundColor = picker.PickerColor }; dataPicker.MaxValue = picker.Items.Count - 1; dataPicker.MinValue = 0; dataPicker.SetDisplayedValues(picker.Items.ToArray()); dataPicker.WrapSelectorWheel = false; dataPicker.DescendantFocusability = DescendantFocusability.BlockDescendants; dataPicker.Value = picker.SelectedIndex; layout.AddView(dataPicker); ElementController.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, true); var builder = new AlertDialog.Builder(Context); builder.SetView(layout); builder.SetTitle(""); builder.SetNegativeButton(global::Android.Resource.String.Cancel, (s, a) => { ElementController.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, false); pickerView = null; }); builder.SetPositiveButton(global::Android.Resource.String.Ok, (s, a) => { ElementController.SetValueFromRenderer(Picker.SelectedIndexProperty, dataPicker.Value); // It is possible for the Content of the Page to be changed on SelectedIndexChanged. // In this case, the Element & Control will no longer exist. if (Element != null) { if (picker.Items.Count > 0 && Element.SelectedIndex >= 0) { Control.Text = picker.Items[Element.SelectedIndex]; } ElementController.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, false); } pickerView = null; }); pickerView = builder.Create(); pickerView.DismissEvent += (sender, args) => { ElementController?.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, false); }; pickerView.Show(); }
public async void GetData(View v) { var ctrl = ((MainActivity)Activity).Ctrl; var pn = v.FindViewById <TextView>(Resource.Id.TaskTimeLog_ProjectName); var tn = v.FindViewById <TextView>(Resource.Id.TaskTimeLog_TaskName); var fab = v.FindViewById <FloatingActionButton>(Resource.Id.TaskTimeLog_fab); pn.Text = ProjectName; tn.Text = TaskName; var pb = new ProgressDialog(Activity) { Indeterminate = true }; pb.SetTitle("Loading"); pb.SetCanceledOnTouchOutside(false); pb.Show(); try { var timelogs = await ctrl.GetTimeLogs(AccountStorage.DataSet, null, null, null, _id, null); Debug.WriteLine("Got data for timelogs :" + timelogs.Count); fab.Click += (sender, args) => { if (timelogs.Count > 0) { Debug.WriteLine("Project Name :" + timelogs[0].Task.Project.Name); Debug.WriteLine("Task Name :" + timelogs[0].Task.FullName); ((MainActivity)Activity).TimeLogEditCallBack(timelogs[0].Task.Project.Name, timelogs[0].Task.FullName, timelogs[0].Task.Id, null); } else { ((MainActivity)Activity).TimeLogEditCallBack(ProjectName, TaskName, _id, null); } }; fab.Show(); foreach (var timelog in timelogs) { Debug.WriteLine(timelog); } var listAdapter = new TaskTimeLogAdapter(Activity, Resource.Layout.TimeLogEntryListItem, timelogs.ToArray()); ListAdapter = listAdapter; if (timelogs.Count > 0) { pn.Text = timelogs[0].Task.Project.Name; tn.Text = timelogs[0].Task.FullName; } pb.Dismiss(); ListView.ItemClick += (sender, args) => { var i = args.Position; Debug.WriteLine("I position :" + i); ((MainActivity)Activity).TimeLogEditCallBack(timelogs[i].Task.Project.Name, timelogs[i].Task.FullName, timelogs[i].Task.Id, timelogs[i]); }; } catch (CannotReachServerException) { if (pb.IsShowing) { pb.Dismiss(); } AlertDialog.Builder builder = new AlertDialog.Builder(Activity); builder.SetTitle("Unable to Connect") .SetMessage("Please check your network connection and try again") .SetNeutralButton("Okay", (sender2, args2) => { builder.Dispose(); ((MainActivity)Activity).FragmentManager.PopBackStack(); }) .SetCancelable(false); AlertDialog alert = builder.Create(); alert.Show(); } catch (WebException we) { if (we.Status == WebExceptionStatus.ProtocolError) { var response = we.Response as HttpWebResponse; if (response != null) { Console.WriteLine("HTTP Status Code: " + (int)response.StatusCode); if (response.StatusCode == HttpStatusCode.Forbidden) { try { if (pb.IsShowing) { pb.Dismiss(); } Toast.MakeText(this.Activity, "Username and password error.", ToastLength.Long).Show(); System.Diagnostics.Debug.WriteLine("We are about to logout"); AccountStorage.ClearStorage(); System.Diagnostics.Debug.WriteLine("Main Activity is :" + Activity == null); System.Diagnostics.Debug.WriteLine("Items in the backstack :" + Activity.FragmentManager.BackStackEntryCount); System.Diagnostics.Debug.WriteLine("Main Activity is :" + Activity == null); Activity.FragmentManager.PopBackStack(null, PopBackStackFlags.Inclusive); System.Diagnostics.Debug.WriteLine("Items in the backstack 2 :" + Activity.FragmentManager.BackStackEntryCount); ((MainActivity)(Activity)).SetDrawerState(false); ((MainActivity)(Activity)).SwitchToFragment(MainActivity.FragmentTypes.Login); } catch (System.Exception e) { System.Diagnostics.Debug.WriteLine("We encountered an error :" + e.Message); } } } else { // no http status code available Toast.MakeText(Activity, "Unable to load the data. Please restart the application.", ToastLength.Short).Show(); } } else { // no http status code availableToast.MakeText(Activity, "Unable to load the data. Please restart the application.", ToastLength.Short).Show(); } } catch (StatusNotOkayException se) { if (pb.IsShowing) { pb.Dismiss(); } AlertDialog.Builder builder = new AlertDialog.Builder(Activity); builder.SetTitle("An Error has occured") .SetMessage("Error :" + se.GetMessage()) .SetNeutralButton("Okay", (sender2, args2) => { builder.Dispose(); }) .SetCancelable(false); AlertDialog alert = builder.Create(); alert.Show(); } catch (Exception e) { // For any other weird exceptions if (pb.IsShowing) { pb.Dismiss(); } AlertDialog.Builder builder = new AlertDialog.Builder(Activity); builder.SetTitle("An Error has occured") .SetNeutralButton("Okay", (sender2, args2) => { builder.Dispose(); }) .SetMessage("Error :" + e.Message) .SetCancelable(false); AlertDialog alert = builder.Create(); alert.Show(); } }
void RenderPages() { Stream inputStream = Assets.Open(fileName); using (var outputStream = this.OpenFileOutput("_sample.pdf", Android.Content.FileCreationMode.Private)) { inputStream.CopyTo(outputStream); } var fileStreamPath = this.GetFileStreamPath("_sample.pdf"); MemoryStream m_memoryStream = new MemoryStream(); File.OpenRead(fileStreamPath.AbsolutePath).CopyTo(m_memoryStream); var renderer = new PdfRenderer(ParcelFileDescriptor.Open(fileStreamPath, ParcelFileMode.ReadOnly)); var screenWidth = Resources.DisplayMetrics.WidthPixels; // render all pages pageCount = renderer.PageCount; for (int i = 0; i < pageCount; i++) { page = renderer.OpenPage(i); // create bitmap at appropriate size var ratio = (float)page.Height / page.Width; var newHeight = screenWidth * ratio; bitmap = Bitmap.CreateBitmap(screenWidth, (int)newHeight, Bitmap.Config.Argb8888); // render PDF page to bitmap page.Render(bitmap, null, null, PdfRenderMode.ForDisplay); // add bitmap to list pages.Add(bitmap); // close the page page.Close(); // if free memory is less than the size of two page bitmaps and we still have pages left to load // we'll stop loading and then display a message about downloading the full doc // * this catch doesn't seem to work on Android O but it worked on a Nexus 5 running Android M, apparently Android O changes some memory handling Debug.WriteLine("\nMemory usage " + i + "\n" + "Bitmap Byte Count: " + bitmap.ByteCount + "\nMemory Available: " + MemoryAvailable()); if (bitmap.ByteCount * 2 > MemoryAvailable() && i < pageCount - 1) { lowMemory = true; break; } } // close the renderer renderer.Close(); // Create an adapter for the RecyclerView, and pass it the // data set (the bitmap list) to manage: mAdapter = new PdfBitmapAdapter(pages); // Register the item click handler (below) with the adapter: mAdapter.ItemClick += OnItemClick; // Plug the adapter into the RecyclerView: mRecyclerView.SetAdapter(mAdapter); if (lowMemory) { try { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.SetTitle("Out Of Memory"); alert.SetMessage("You are only viewing " + pages.Count + " out of " + pageCount + " pages."); alert.SetPositiveButton("OK", (senderAlert, args) => { }); Dialog dialog = alert.Create(); dialog.Show(); } catch (Exception e) { Debug.WriteLine("Exception: " + e.Message); } } }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.myTournaments); var idd = "ca-app-pub-5385963311823976~5875287959"; Android.Gms.Ads.MobileAds.Initialize(ApplicationContext, idd); var adView = FindViewById <AdView>(Resource.Id.adViewMT); var adRequest = new AdRequest.Builder().Build(); adView.LoadAd(adRequest); ListView tournamentsList = FindViewById <ListView>(Resource.Id.listViewTournaments); var mytournamentsTable = con.db.Table <tournament>(); //connection.db.DropTable<winners>(); //connection.db.DropTable<person>(); //connection.db.DropTable<tournament>(); //connection.db.DropTable<personTournament>(); //connection.db.DropTable<tournamentScorer>(); //connection.db.DropTable<results>(); //connection.db.DropTable<points>(); fillList(); tournamentsList.ItemClick += delegate(object sender, Android.Widget.AdapterView.ItemClickEventArgs e) { var selected = tournamentsList.GetItemAtPosition(e.Position); List <int> allPeople = new List <int>(); int id = 0; List <tournament> getID = con.db.Query <tournament>("SELECT * FROM tournament WHERE name = '" + selected + "' "); foreach (var item in getID) { id = item.id; } List <person> getAll1 = con.db.Query <person>("SELECT * FROM people WHERE tournamentID = '" + id + "' "); foreach (var item in getAll1) { allPeople.Add(item.id); } List <personTournament> getAll2 = con.db.Query <personTournament>("SELECT * FROM peopleTournament WHERE tournamentID = '" + id + "' "); foreach (var item in getAll2) { allPeople.Add(item.personID); } if (allPeople.Count < 3) { AlertDialog.Builder dialog = new AlertDialog.Builder(this); dialog.SetTitle("Warning"); dialog.SetMessage("This tournament does not have minimum of 3 players."); dialog.SetNegativeButton("Cancel", (senderAlert, args) => { dialog.Dispose(); }); dialog.SetPositiveButton("Add players", (senderAlert, args) => { Intent intent = new Intent(this, typeof(addNewPlayers)); intent.PutExtra("tournamentName", selected.ToString()); StartActivity(intent); }); Dialog alertDialog = dialog.Create(); alertDialog.Show(); return; } List <tournament> tournamentTypeList = con.db.Query <tournament>("SELECT type FROM tournament where name = '" + selected + "' "); List <string> tournamentType = new List <string>(); foreach (var item in tournamentTypeList) { tournamentType.Add(item.type); } if (tournamentType[0] == "League") { Intent intent = new Intent(this, typeof(leagueType)); intent.PutExtra("tournamentName", selected.ToString()); StartActivity(intent); } }; tournamentsList.ItemLongClick += delegate(object sender, Android.Widget.AdapterView.ItemLongClickEventArgs e) { AlertDialog.Builder dialog = new AlertDialog.Builder(this); dialog.SetTitle("Confirm delete"); dialog.SetMessage("Do you want to delete selected tournament?"); dialog.SetNegativeButton("Cancel", (senderAlert, args) => { dialog.Dispose(); }); dialog.SetPositiveButton("Delete", (senderAlert, args) => { var selected = tournamentsList.GetItemAtPosition(e.Position); string name = selected.ToString(); var data = mytournamentsTable.Where(x => x.name == name).FirstOrDefault(); try { con.db.Delete(data); Toast.MakeText(this, "Successfull", ToastLength.Short).Show(); fillList(); } catch (Exception) { throw; } }); Dialog alertDialog = dialog.Create(); alertDialog.Show(); }; }
//Download private void Download_icon_Click(object sender, EventArgs e) { try { if (Download_icon.Tag.ToString() == "false") { Download_icon.SetImageDrawable(ActivityContext.GetDrawable(Resource.Drawable.ic_action_download_stop)); Download_icon.Tag = "true"; string urlVideo = string.Empty; if (Videodata.source.Contains("youtube") || Videodata.source.Contains("Youtube") || Videodata.source.Contains("youtu")) { urlVideo = VideoInfoRetriever.VideoDownloadstring; if (!string.IsNullOrEmpty(urlVideo)) { VideoControler = new VideoDownloadAsyncControler(urlVideo, Videodata.source, ActivityContext); if (!VideoControler.CheckDownloadLinkIfExits()) { VideoControler.StartDownloadManager(Videodata.name, Videodata); } } else { IMethods.DialogPopup.InvokeAndShowDialog(ActivityContext, ActivityContext.GetString(Resource.String.Lbl_Error), ActivityContext.GetString(Resource.String.Lbl_You_can_not_Download_video), ActivityContext.GetString(Resource.String.Lbl_Ok)); } } else { urlVideo = Videodata.source; VideoControler = new VideoDownloadAsyncControler(urlVideo, Videodata.id, ActivityContext); if (!VideoControler.CheckDownloadLinkIfExits()) { VideoControler.StartDownloadManager(Videodata.name, Videodata); } } } else if (Download_icon.Tag.ToString() == "Downloaded") { try { AlertDialog.Builder builder = new AlertDialog.Builder(ActivityContext); builder.SetTitle(ActivityContext.GetString(Resource.String.Lbl_Delete_video)); builder.SetMessage(ActivityContext.GetString(Resource.String.Lbl_Do_You_want_to_remove_video)); builder.SetPositiveButton(ActivityContext.GetString(Resource.String.Lbl_Yes), delegate(object o, DialogClickEventArgs args) { try { VideoDownloadAsyncControler.RemoveDiskVideoFile(Videodata.id + ".mp4"); Download_icon.SetImageDrawable(ActivityContext.GetDrawable(Resource.Drawable.ic_action_download)); Download_icon.Tag = "false"; } catch (Exception exception) { Crashes.TrackError(exception); } }); builder.SetNegativeButton(ActivityContext.GetString(Resource.String.Lbl_No), delegate(object o, DialogClickEventArgs args) { }); var alert = builder.Create(); alert.Show(); } catch (System.Exception exception) { Crashes.TrackError(exception); } } else { Download_icon.SetImageDrawable(ActivityContext.GetDrawable(Resource.Drawable.ic_action_download)); Download_icon.Tag = "false"; VideoControler.StopDownloadManager(); } } catch (System.Exception exception) { Crashes.TrackError(exception); } }
public static void ShowChangeLog(Context ctx, Action onDismiss) { AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(ctx, Android.Resource.Style.ThemeHoloLightDialog)); builder.SetTitle(ctx.GetString(Resource.String.ChangeLog_title)); List <string> changeLog = new List <string> { ctx.GetString(Resource.String.ChangeLog_1_04), ctx.GetString(Resource.String.ChangeLog_1_03), ctx.GetString(Resource.String.ChangeLog_1_02), #if !NoNet ctx.GetString(Resource.String.ChangeLog_1_01g), ctx.GetString(Resource.String.ChangeLog_1_01d), #endif ctx.GetString(Resource.String.ChangeLog_1_01), ctx.GetString(Resource.String.ChangeLog_1_0_0e), ctx.GetString(Resource.String.ChangeLog_1_0_0), ctx.GetString(Resource.String.ChangeLog_0_9_9c), ctx.GetString(Resource.String.ChangeLog_0_9_9), ctx.GetString(Resource.String.ChangeLog_0_9_8c), ctx.GetString(Resource.String.ChangeLog_0_9_8b), ctx.GetString(Resource.String.ChangeLog_0_9_8), #if !NoNet //0.9.7b fixes were already included in 0.9.7 offline ctx.GetString(Resource.String.ChangeLog_0_9_7b), #endif ctx.GetString(Resource.String.ChangeLog_0_9_7), ctx.GetString(Resource.String.ChangeLog_0_9_6), ctx.GetString(Resource.String.ChangeLog_0_9_5), ctx.GetString(Resource.String.ChangeLog_0_9_4), ctx.GetString(Resource.String.ChangeLog_0_9_3_r5), ctx.GetString(Resource.String.ChangeLog_0_9_3), ctx.GetString(Resource.String.ChangeLog_0_9_2), ctx.GetString(Resource.String.ChangeLog_0_9_1), ctx.GetString(Resource.String.ChangeLog_0_9), ctx.GetString(Resource.String.ChangeLog_0_8_6), ctx.GetString(Resource.String.ChangeLog_0_8_5), ctx.GetString(Resource.String.ChangeLog_0_8_4), ctx.GetString(Resource.String.ChangeLog_0_8_3), ctx.GetString(Resource.String.ChangeLog_0_8_2), ctx.GetString(Resource.String.ChangeLog_0_8_1), ctx.GetString(Resource.String.ChangeLog_0_8), ctx.GetString(Resource.String.ChangeLog_0_7), ctx.GetString(Resource.String.ChangeLog) }; String version; try { PackageInfo packageInfo = ctx.PackageManager.GetPackageInfo(ctx.PackageName, 0); version = packageInfo.VersionName; } catch (PackageManager.NameNotFoundException) { version = ""; } string warning = ""; if (version.Contains("pre")) { warning = ctx.GetString(Resource.String.PreviewWarning); } builder.SetPositiveButton(Android.Resource.String.Ok, (dlgSender, dlgEvt) => { ((AlertDialog)dlgSender).Dismiss(); }); builder.SetCancelable(false); WebView wv = new WebView(ctx); wv.SetBackgroundColor(Color.White); wv.LoadDataWithBaseURL(null, GetLog(changeLog, warning, ctx), "text/html", "UTF-8", null); //builder.SetMessage(""); builder.SetView(wv); Dialog dialog = builder.Create(); dialog.DismissEvent += (sender, e) => { onDismiss(); }; dialog.Show(); /*TextView message = (TextView)dialog.FindViewById(Android.Resource.Id.Message); * * * message.TextFormatted = Html.FromHtml(ConcatChangeLog(ctx, changeLog.ToArray())); * message.AutoLinkMask=MatchOptions.WebUrls;*/ }
protected internal void BTSalvar_Click(object sender, EventArgs e) { AlertDialog.Builder builder = new AlertDialog.Builder(this); AlertDialog alerta = builder.Create(); AplicacaoService apliService = new AplicacaoService(); AvaliacaoService avalService = new AvaliacaoService(); if (idEstudo_ > 0 && int.Parse(idEquipamentoSelect) > 0) { var date = ""; if (textDate.Text == "") { date = DateTime.Now.ToString(); } else { date = textDate.Text; } var datechuva = ""; if (textChuva.Text == "") { datechuva = null; } else { datechuva = textChuva.Text; } string Velocidade_Vento = "0"; if (textVento.Text == "") { Velocidade_Vento = "0"; } else { Velocidade_Vento = textVento.Text.Replace("km/h", ""); } decimal Umidade_Relativa = 0; if (textUmidade.Text == "") { Umidade_Relativa = 0; } else { Umidade_Relativa = decimal.Parse(textUmidade.Text.Replace("%", "")); } decimal Percentual_Nuvens = 0; if (textNuvens.Text == "") { Percentual_Nuvens = 0; } else { Percentual_Nuvens = decimal.Parse(textNuvens.Text.Replace("%", "")); } decimal Chuva_Volume = 0; if (textVolumeChuva.Text == "") { Chuva_Volume = 0; } else { Chuva_Volume = decimal.Parse(textVolumeChuva.Text); } decimal BBCH = 0; if (textBBCH.Text == "") { BBCH = 0; } else { BBCH = decimal.Parse(textBBCH.Text); } var aplicacao = new Aplicacao { idInstalacao = idInstalacao, Data_Aplicacao = DateTime.Parse(date), Umidade_Relativa = Umidade_Relativa, Temperatura = textTemperatura.Text, Velocidade_Vento = Convert.ToDecimal(Velocidade_Vento.Replace(".", ",")), Percentual_Nuvens = Percentual_Nuvens, Chuva_Data = Convert.ToDateTime(datechuva), Chuva_Volume = Chuva_Volume, idEquipamento = int.Parse(idEquipamentoSelect), BBCH = BBCH, Observacoes = textObservacoes.Text, Longitude = longitude.ToString(), Latitude = latitude.ToString(), Data_Realizada = DateTime.Now, idUsuario = int.Parse(Settings.GeneralSettings), idEstudo_Planejamento = idPlanejamento }; try { if (apliService.SalvarAplicacao(aplicacao) == true) { if (apliService.GerarPlanejamentoAplicacao(idEstudo_, aplicacao.Data_Aplicacao)) { avalService.GerarPlanejamentoAvaliacao(idEstudo_, aplicacao.Data_Aplicacao); } AplicacaoService aps = new AplicacaoService(); var validaPlan = aps.GetPlanejamentoAplic(idEstudo_); if (validaPlan.Count > 0) { if (validaPlan[0].Num_Aplicacao == 1) { aplicacao.idEstudo_Planejamento = validaPlan[0].idEstudo_Planejamento_Aplicacao; var last = apliService.LastID(); aplicacao.IdAplicacao = last.IdAplicacao; apliService.UpdateAplicacao(aplicacao); } } alerta.SetTitle("Sucesso!"); alerta.SetIcon(Android.Resource.Drawable.IcInputAdd); alerta.SetMessage("Aplicação Salva com Sucesso!"); alerta.SetButton("OK", (s, ev) => { alerta.Dismiss(); }); alerta.Show(); LimparCampos(); } else { alerta.SetTitle("ERRO!"); alerta.SetIcon(Android.Resource.Drawable.IcDialogAlert); alerta.SetMessage("Erro ao salvar a Aplicação!"); alerta.SetButton("OK", (s, ev) => { alerta.Dismiss(); }); alerta.Show(); } } catch { alerta.SetTitle("ERRO!"); alerta.SetIcon(Android.Resource.Drawable.IcDialogAlert); alerta.SetMessage("Erro ao salvar a Aplicação!"); alerta.SetButton("OK", (s, ev) => { alerta.Dismiss(); }); alerta.Show(); } } else { alerta.SetTitle("ERRO!"); alerta.SetIcon(Android.Resource.Drawable.IcDialogAlert); alerta.SetMessage("Favor preencher todos os campos obrigatorios!"); alerta.SetButton("OK", (s, ev) => { alerta.Dismiss(); }); alerta.Show(); } }
void DisplayMessageBox( string title, string message, Note.MessageBoxResult onResult ) { Rock.Mobile.Threading.Util.PerformOnUIThread( delegate { AlertDialog.Builder dlgAlert = new AlertDialog.Builder( Rock.Mobile.PlatformSpecific.Android.Core.Context ); dlgAlert.SetTitle( title ); dlgAlert.SetMessage( message ); dlgAlert.SetNeutralButton( GeneralStrings.Yes, delegate { onResult( 0 ); }); dlgAlert.SetPositiveButton( GeneralStrings.No, delegate(object sender, DialogClickEventArgs ev ) { onResult( 1 ); } ); dlgAlert.Create( ).Show( ); } ); }
public View GetSampleContent(Context con) { ScrollView scroll = new ScrollView(con); bool isTablet = SfMaskedEditText.IsTabletDevice(con); LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(12, 12, 12, 12); TextView headLabel = new TextView(con); headLabel.TextSize = 30; headLabel.SetTextColor(Color.ParseColor("#262626")); headLabel.Typeface = Typeface.DefaultBold; headLabel.Text = "Funds Transfer"; linear.AddView(headLabel); TextView fundTransferLabelSpacing = new TextView(con); fundTransferLabelSpacing.SetHeight(40); linear.AddView(fundTransferLabelSpacing); TextView textToAccount = new TextView(con); textToAccount.SetTextColor(Color.ParseColor("#6d6d72")); textToAccount.TextSize = 16; textToAccount.Typeface = Typeface.Default; textToAccount.Text = "To Account"; textToAccount.SetPadding(0, 0, 0, 10); linear.AddView(textToAccount); sfToAccount = new SfMaskedEdit(con); sfToAccount.Mask = "0000 0000 0000 0000"; sfToAccount.Gravity = GravityFlags.Start; sfToAccount.ValidationMode = InputValidationMode.KeyPress; sfToAccount.ValueMaskFormat = MaskFormat.ExcludePromptAndLiterals; sfToAccount.Hint = "1234 1234 1234 1234"; sfToAccount.SetHintTextColor(Color.LightGray); linear.AddView(sfToAccount); erroToAccount = new TextView(con); erroToAccount.SetTextColor(Color.Red); erroToAccount.TextSize = 12; erroToAccount.Typeface = Typeface.Default; linear.AddView(erroToAccount); TextView textDesc = new TextView(con); textDesc.Text = "Description"; textDesc.Typeface = Typeface.Default; textDesc.SetPadding(0, 30, 0, 10); textDesc.TextSize = 16; linear.AddView(textDesc); sfDesc = new SfMaskedEdit(con); sfDesc.Mask = ""; sfDesc.Gravity = GravityFlags.Start; sfDesc.ValidationMode = InputValidationMode.KeyPress; sfDesc.ValueMaskFormat = MaskFormat.ExcludePromptAndLiterals; sfDesc.Hint = "Enter description"; sfDesc.SetHintTextColor(Color.LightGray); linear.AddView(sfDesc); TextView textAmount = new TextView(con); textAmount.Text = "Amount"; textAmount.Typeface = Typeface.Default; textAmount.SetPadding(0, 30, 0, 10); textAmount.TextSize = 16; linear.AddView(textAmount); amountMask = new SfMaskedEdit(con); amountMask.Mask = "$ 0,000.00"; amountMask.Gravity = GravityFlags.Start; amountMask.ValidationMode = InputValidationMode.KeyPress; amountMask.ValueMaskFormat = MaskFormat.IncludePromptAndLiterals; amountMask.Hint = "$ 3,874.00"; amountMask.SetHintTextColor(Color.LightGray); linear.AddView(amountMask); errotextAmount = new TextView(con); errotextAmount.SetTextColor(Color.Red); errotextAmount.TextSize = 12; errotextAmount.Typeface = Typeface.Default; linear.AddView(errotextAmount); TextView textEmail = new TextView(con); textEmail.Text = "Email ID"; textEmail.Typeface = Typeface.Default; textEmail.SetPadding(0, 30, 0, 10); textEmail.TextSize = 16; linear.AddView(textEmail); emailMask = new SfMaskedEdit(con); emailMask.Mask = @"\w+@\w+\.\w+"; emailMask.MaskType = MaskType.RegEx; emailMask.Gravity = GravityFlags.Start; emailMask.ValidationMode = InputValidationMode.KeyPress; emailMask.ValueMaskFormat = MaskFormat.ExcludePromptAndLiterals; emailMask.Hint = "*****@*****.**"; emailMask.SetHintTextColor(Color.LightGray); linear.AddView(emailMask); errotextEmail = new TextView(con); errotextEmail.SetTextColor(Color.Red); errotextEmail.TextSize = 12; errotextEmail.Typeface = Typeface.Default; linear.AddView(errotextEmail); TextView textPhone = new TextView(con); textPhone.Text = "Mobile Number "; textPhone.Typeface = Typeface.Default; textPhone.SetPadding(0, 30, 0, 10); textPhone.TextSize = 16; linear.AddView(textPhone); phoneMask = new SfMaskedEdit(con); phoneMask.Mask = "+1 000 000 0000"; phoneMask.Gravity = GravityFlags.Start; phoneMask.ValueMaskFormat = MaskFormat.ExcludePromptAndLiterals; phoneMask.ValidationMode = InputValidationMode.KeyPress; phoneMask.Hint = "+1 323 339 3392"; phoneMask.SetHintTextColor(Color.LightGray); linear.AddView(phoneMask); errotextPhone = new TextView(con); errotextPhone.SetTextColor(Color.Red); errotextPhone.TextSize = 12; errotextPhone.Typeface = Typeface.Default; linear.AddView(errotextPhone); TextView searchButtonSpacing = new TextView(con); searchButtonSpacing.SetHeight(30); Button searchButton = new Button(con); searchButton.SetWidth(ActionBar.LayoutParams.MatchParent); searchButton.SetHeight(40); searchButton.Text = "TRANSFER MONEY"; searchButton.SetTextColor(Color.White); searchButton.SetBackgroundColor(Color.Gray); searchButton.Click += (object sender, EventArgs e) => { if (string.IsNullOrEmpty(sfToAccount.Text) || string.IsNullOrEmpty(sfDesc.Text) || string.IsNullOrEmpty(amountMask.Text) || string.IsNullOrEmpty(emailMask.Text) || string.IsNullOrEmpty(phoneMask.Text)) { resultsDialog.SetMessage("Please fill all the required data!"); } else if ((sfToAccount.HasError || sfDesc.HasError || amountMask.HasError || emailMask.HasError || phoneMask.HasError)) { resultsDialog.SetMessage("Please enter valid details"); } else { resultsDialog.SetMessage(string.Format("Amount of {0} has been transferred successfully!", amountMask.Value)); sfToAccount.Value = string.Empty; sfDesc.Value = string.Empty; amountMask.Value = string.Empty; emailMask.Value = string.Empty; phoneMask.Value = string.Empty; } resultsDialog.Create().Show(); }; linear.AddView(searchButtonSpacing); linear.AddView(searchButton); sfToAccount.ValueChanged += SfToAccount_ValueChanged; sfToAccount.MaskInputRejected += SfToAccount_MaskInputRejected; amountMask.ValueChanged += AmountMask_ValueChanged; amountMask.MaskInputRejected += AmountMask_MaskInputRejected; emailMask.ValueChanged += EmailMask_ValueChanged; emailMask.MaskInputRejected += EmailMask_MaskInputRejected; phoneMask.ValueChanged += PhoneMask_ValueChanged; phoneMask.MaskInputRejected += PhoneMask_MaskInputRejected; //results dialog resultsDialog = new AlertDialog.Builder(con); resultsDialog.SetTitle("Status"); resultsDialog.SetPositiveButton("OK", (object sender, DialogClickEventArgs e) => { }); resultsDialog.SetCancelable(true); scroll.AddView(linear); return(scroll); }
private void spawnFilterDialog() { selectedItems.Add(0); selectedItems.Add(1); selectedItems.Add(2); var builder = new AlertDialog.Builder(ViewContext) .SetTitle("Filter Events") .SetMultiChoiceItems(items, new bool[] {true,true,true}, MultiListClicked); builder.SetPositiveButton("Ok", OkClicked); builder.Create(); builder.Show(); }
private void MAdapter_ItemDelete(object sender, int e) { if (flagLokacijaPotvrda && filtriraneAnkete.Count == 1) { string nazivLokacije = db.Query <DID_Lokacija>( "SELECT * " + "FROM DID_Lokacija " + "WHERE SAN_Id = ?", lokacijaId).FirstOrDefault().SAN_Naziv; AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.SetTitle("Upozorenje!"); alert.SetMessage("Lokacija: " + nazivLokacije + " je zaključana. Ova anketa je jedina na lokaciji te ukoliko obrišete anketu automatski će se obrisati potvrda. Jeste li sigurni da želite obrisati anketu?"); alert.SetPositiveButton("OBRIŠI", (senderAlert, arg) => { localOdradeneAnketeEdit.PutBoolean("visited", true); localOdradeneAnketeEdit.Commit(); localPozicijaEdit.PutString("sifraPartnera", sifraPartnera); localPozicijaEdit.Commit(); Guid anketaId = filtriraneAnkete[e].Id; int pozicijaId = filtriraneAnkete[e].ANK_POZ_Id; if (pozicijaId < 0) { db.Delete <DID_LokacijaPozicija>(pozicijaId); } DeleteMaterijaleNaAnketama(pozicijaId); db.Delete <DID_Anketa>(anketaId); //db.Execute( // "DELETE FROM DID_AnketaMaterijali " + // "WHERE RadniNalog = ? " + // "AND PozicijaId = ?", radniNalogId, pozicijaId); db.Execute( "DELETE FROM DID_Potvrda_Materijal " + "WHERE Potvrda = ?", potvrda.FirstOrDefault().Id); db.Query <DID_Potvrda_Djelatnost>( "DELETE FROM DID_Potvrda_Djelatnost " + "WHERE Potvrda = ?", potvrda.FirstOrDefault().Id); db.Query <DID_Potvrda_Nametnik>( "DELETE FROM DID_Potvrda_Nametnik " + "WHERE Potvrda = ?", potvrda.FirstOrDefault().Id); db.Delete <DID_Potvrda>(potvrdaId); //Update lokacije db.Query <DID_RadniNalog_Lokacija>( "UPDATE DID_RadniNalog_Lokacija " + "SET Status = 2 " + "WHERE Lokacija = ? " + "AND RadniNalog = ?", lokacijaId, radniNalogId); UpdateStatusRadniNalog(); intent = new Intent(this, typeof(Activity_OdradeneAnkete)); StartActivity(intent); }); alert.SetNegativeButton("ODUSTANI", (senderAlert, arg) => { }); Dialog dialog = alert.Create(); dialog.Show(); } else if (flagLokacijaPotvrda && filtriraneAnkete.Count > 1) { string nazivLokacije = db.Query <DID_Lokacija>( "SELECT * " + "FROM DID_Lokacija " + "WHERE SAN_Id = ?", lokacijaId).FirstOrDefault().SAN_Naziv; AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.SetTitle("Upozorenje!"); alert.SetMessage("Lokacija: " + nazivLokacije + " je zaključana. Ako obrišete anketu obrisati će se i materijali vezani za odabranu poziciju. Jeste li sigurni da želite obrisati anketu?"); alert.SetPositiveButton("OBRIŠI", (senderAlert, arg) => { localOdradeneAnketeEdit.PutBoolean("visited", true); localOdradeneAnketeEdit.Commit(); localPozicijaEdit.PutString("sifraPartnera", sifraPartnera); localPozicijaEdit.Commit(); Guid anketaId = filtriraneAnkete[e].Id; int pozicijaId = filtriraneAnkete[e].ANK_POZ_Id; if (pozicijaId < 0) { db.Delete <DID_LokacijaPozicija>(pozicijaId); } DeleteMaterijaleNaAnketama(pozicijaId); db.Delete <DID_Anketa>(anketaId); //db.Execute( // "DELETE FROM DID_AnketaMaterijali " + // "WHERE RadniNalog = ? " + // "AND PozicijaId = ?", radniNalogId, pozicijaId); db.Execute( "DELETE FROM DID_Potvrda_Materijal " + "WHERE Potvrda = ?", potvrda.FirstOrDefault().Id); db.Execute( "INSERT INTO DID_Potvrda_Materijal (Potvrda, Materijal, Utroseno, MaterijalNaziv) " + "SELECT pot.Id, mat.MaterijalSifra, TOTAL(mat.Kolicina), mat.MaterijalNaziv " + "FROM DID_AnketaMaterijali mat " + "INNER JOIN DID_LokacijaPozicija poz ON poz.POZ_Id = mat.PozicijaId " + "INNER JOIN DID_Potvrda pot ON pot.RadniNalog = mat.RadniNalog " + "AND pot.Lokacija = poz.SAN_Id " + "WHERE pot.Id = ? " + "GROUP BY mat.MaterijalSifra, mat.MjernaJedinica", potvrda.FirstOrDefault().Id); var listaMaterijalaPotvrda = db.Query <DID_Potvrda_Materijal>("SELECT * FROM DID_Potvrda_Materijal WHERE Potvrda = ?", potvrda.FirstOrDefault().Id); foreach (var materijal in listaMaterijalaPotvrda) { db.Execute( "UPDATE DID_Potvrda_Materijal " + "SET SinhronizacijaPrivremeniKljuc = ? " + "WHERE Id = ?", materijal.Id, materijal.Id); } intent = new Intent(this, typeof(Activity_OdradeneAnkete)); StartActivity(intent); }); alert.SetNegativeButton("ODUSTANI", (senderAlert, arg) => { }); Dialog dialog = alert.Create(); dialog.Show(); } else { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.SetTitle("Upozorenje!"); alert.SetMessage("Brisanjem ankete obrisati će se i materijali vezani uz ovu poziciju. Jeste li sigurni da želite obrisati anketu?"); alert.SetPositiveButton("OBRIŠI", (senderAlert, arg) => { localOdradeneAnketeEdit.PutBoolean("visited", true); localOdradeneAnketeEdit.Commit(); localPozicijaEdit.PutString("sifraPartnera", sifraPartnera); localPozicijaEdit.Commit(); Guid anketaId = filtriraneAnkete[e].Id; int pozicijaId = filtriraneAnkete[e].ANK_POZ_Id; if (pozicijaId < 0) { db.Delete <DID_LokacijaPozicija>(pozicijaId); } db.Delete <DID_Anketa>(anketaId); DeleteMaterijaleNaAnketama(pozicijaId); //db.Execute( // "DELETE FROM DID_AnketaMaterijali " + // "WHERE RadniNalog = ? " + // "AND PozicijaId = ?", radniNalogId, pozicijaId); intent = new Intent(this, typeof(Activity_OdradeneAnkete)); StartActivity(intent); }); alert.SetNegativeButton("ODUSTANI", (senderAlert, arg) => { }); Dialog dialog = alert.Create(); dialog.Show(); } }