public override void OnBackPressed() { var builder = new Android.App.AlertDialog.Builder(this); builder.SetTitle ("Exit."); builder.SetIcon (Android.Resource.Drawable.IcDialogAlert); builder.SetMessage("Exit App?"); builder.SetPositiveButton("OK", (s, e) => { System.Environment.Exit(0); }); builder.SetNegativeButton("Cancel", (s, e) => { }); builder.Create().Show(); }
public override void DisplayMessage(MessageDisplayParams messageParams) { Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(this.context); builder.SetTitle(messageParams.Title); builder.SetMessage(messageParams.Message); if (messageParams.PositiveAction != null) { builder.SetPositiveButton(messageParams.PositiveLabel ?? DefaultPositiveLabel, (s, e) => { messageParams.PositiveAction(); }); } if (messageParams.NegativeAction != null) { builder.SetNegativeButton(messageParams.NegativeLabel ?? DefaultNegativeLabel, (s, e) => { messageParams.NegativeAction(); }); } if (messageParams.NeutralAction != null) { builder.SetNeutralButton(messageParams.NeutralLabel ?? string.Empty, (s, e) => { messageParams.NeutralAction(); }); } var dialog = builder.Create(); dialog.DismissEvent += (sender, e) => { this.messages.Remove(messageParams); }; this.messages.Add(messageParams); this.dialogs.Add(dialog); dialog.Show(); }
protected async override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SupportActionBar.SetDisplayHomeAsUpEnabled(true); SupportActionBar.Elevation = 0; SetContentView(Resource.Layout.generic_list); Recycler = FindViewById <RecyclerView>(Resource.Id.gridView_items); Recycler.SetLayoutManager(new LinearLayoutManager(this)); SelectMode = Intent.GetBooleanExtra(nameof(SelectMode), false); CourseID = Intent.GetIntExtra(nameof(CourseID), 1); CurCourse = await Course.DB.RowsAsync.FirstOrDefaultAsync(c => c.ID == CourseID); TitlesLayout = FindViewById <LinearLayout>(Resource.Id.layout_title); TextOne = FindViewById <TextView>(Resource.Id.text_title1); TextTwo = FindViewById <TextView>(Resource.Id.text_title2); ExamBtn = FindViewById <Button>(Resource.Id.btn_floating_action2); ExamBtn.Visibility = ViewStates.Visible; ExamBtn.Click += async(o, e) => { await CurCourse.LoadUserExaminations(); await CurCourse.LoadAllExercises(); var allexercises = CurCourse.AllExercises; var exercises = CurCourse.UserExaminations; var passes = new List <UserExamination>(); foreach (var item in exercises) { await item.LoadUserExaminationDetails(); var details = item.UserExaminationDetails; foreach (var item2 in details) { await item2.LoadQuestion(); var q = item2.Question; await q.LoadAnswers(); await item2.LoadAnswer(); } var correctanswers = details.Where(c => c.AnswerID != null && c.Answer.IsCorrect); var wronganswers = details.Where(c => c.AnswerID != null && !c.Answer.IsCorrect); var percentage = 100 * correctanswers.Count() / details.Count; if (percentage >= 70) { passes.Add(item); } } var overalpercentage = allexercises.Count > 0 ? 100 * passes.Count / allexercises.Count : 0; var requiredExercises = allexercises.Count * 70 / 100; if (overalpercentage >= 70) { var intent = new Intent(this, typeof(InstructionActivity)); intent.PutExtra(nameof(CourseID), CourseID); intent.PutExtra("ExamTypeID", (int)ExaminationType.EXAMINATION); StartActivity(intent); OverridePendingTransition(Resource.Animation.side_in_right, Resource.Animation.side_out_left); Finish(); } else { Android.App.AlertDialog.Builder dialog = new Android.App.AlertDialog.Builder(this); Android.App.AlertDialog alert = dialog.Create(); alert.SetTitle("Information"); alert.SetCanceledOnTouchOutside(false); alert.SetMessage($"Number of attempted exercises: {exercises.Count}.\nPassed exercises: {passes.Count}\nOveral Pass rate: {overalpercentage}%\nYou need to pass at least {requiredExercises} short exercises to qualify for the final exam"); alert.SetIcon(Resource.Drawable.ic_account_key); alert.SetButton("OK", (c, ev) => { alert.Dismiss(); }); alert.Show(); } }; TitlesLayout.Visibility = ViewStates.Visible; TextOne.Visibility = ViewStates.Visible; TextTwo.Visibility = ViewStates.Visible; if (SelectMode) { Title = "Select module.."; } }
private void AddNotebookButton_Click(object sender, EventArgs e) { var builder = new Android.App.AlertDialog.Builder(this); builder.SetTitle("Add Notebook"); EditText edit = new EditText(this); builder.SetView(edit); builder.SetPositiveButton("Save", (alertDialogSender, args) => { /* do stuff on OK */ string notebookName = edit.Text; //TODO:: TempSolution maybe add one more layer for handling CRUD operations var repo = Kernel.Get<INotebooksRepository>(); int rowschanged = repo.Add(new Notebook() { Id = Guid.NewGuid().ToString(), Name = notebookName, CreatedDate = DateTime.UtcNow, ModifiedDate = DateTime.UtcNow, }); if (rowschanged == 1) { chosenNotebookId = Guid.Parse(repo.GetByName(notebookName).Id); } notebooksAdapter.RefreshContent(); notebooksAdapter.NotifyDataSetChanged(); RefreshNotesListContent(); }); builder.Show(); }
public override bool OnOptionsItemSelected(IMenuItem item) { int id = item.ItemId; if (id == Resource.Id.ActionBar_Search) { if (searchBar.Visibility == ViewStates.Gone) { searchBar.Visibility = ViewStates.Visible; searchBar.RequestFocus(); InputMethodManager imm = (InputMethodManager)GetSystemService(Context.InputMethodService); imm.ShowSoftInput(searchBar, ShowFlags.Implicit); } else { searchBar.Visibility = ViewStates.Gone; InputMethodManager inputMethodManager = (InputMethodManager)GetSystemService(Context.InputMethodService); inputMethodManager.ToggleSoftInput(0, HideSoftInputFlags.ImplicitOnly); } return(true); } else if (id == Resource.Id.ActionBar_Sort) { SetupBoxes(); RegisterSortReceiver(); FragmentTransaction trans = FragmentManager.BeginTransaction(); SortByFragment sortby = new SortByFragment(); sortby.Show(trans, "Sort_By"); return(true); } else if (id == Resource.Id.ActionBar_PlaylistManager) { SetupBoxes(); Intent intent = new Intent(this, typeof(PlaylistManagerActivity)); StartActivity(intent); OverridePendingTransition(Resource.Animation.SlidingRightAnim, Resource.Animation.SlidingLeftAnim); return(true); } else if (id == Resource.Id.ActionBar_Advanced) { SetupBoxes(); Intent intent = new Intent(this, typeof(AdvancedActivity)); StartActivity(intent); return(true); } else if (id == Resource.Id.ActionBar_Loopback) { FragmentTransaction trans = FragmentManager.BeginTransaction(); LoopbackSettingsFragment loopback = new LoopbackSettingsFragment(); loopback.Show(trans, "LoopBack"); return(true); } else if (id == Resource.Id.ActionBar_Refresh) { ShowProgress(); ThreadPool.QueueUserWorkItem(o => { PapMediaPlayer.ViewManager.DataLoader.DataLoader loader = new ViewManager.DataLoader.DataLoader(this); ViewManager = new AllTracksManager(this, loader.Load(true)); RunOnUiThread(() => grid.Adapter = ViewManager.GetAdapter()); RunOnUiThread(() => HideProgress()); }); } else if (id == Resource.Id.ActionBar_About) { using (Android.App.AlertDialog.Builder help = new Android.App.AlertDialog.Builder(this, Resource.Style.MyDialogTheme)) { help.SetTitle("About"); help.SetIcon(Resource.Drawable.About); help.SetMessage("\n\nPap Media Player\n\nDeveloper Konstantinos Pap\n\nPowered by Pap Industries \n\nLoading Screens by Nikolaos Pothakis\n\nCopyrights © Konstantinos Pap 2018-2020."); help.Show(); } } return(base.OnOptionsItemSelected(item)); }
public BluetoothPrinter(Android.App.Activity activity, PrinterType type, string Number) { this.as_Number = Number; this.printerType = type; this.activity = activity; //获得本地的蓝牙适配器 localAdapter = Android.Bluetooth.BluetoothAdapter.DefaultAdapter; if (string.IsNullOrEmpty(Number)) { Android.Widget.Toast.MakeText(activity, "传入的单号为空,打印失败", Android.Widget.ToastLength.Short).Show(); return; } //打开蓝牙设备 if (!localAdapter.IsEnabled) { Android.Content.Intent enableIntent = new Android.Content.Intent(Android.Bluetooth.BluetoothAdapter.ActionRequestEnable); activity.StartActivityForResult(enableIntent, 1); } //静默打开 if (!localAdapter.IsEnabled) { localAdapter.Enable(); } if (!localAdapter.IsEnabled)//用户拒绝打开或系统限制权限 { Android.Widget.Toast.MakeText(activity, "蓝牙未打开", Android.Widget.ToastLength.Short).Show(); return; } //获得已配对的设备列表 bondedDevices = new List<Android.Bluetooth.BluetoothDevice>(localAdapter.BondedDevices); if (bondedDevices.Count <= 0) { Android.Widget.Toast.MakeText(activity, "未找到已配对的蓝牙设备", Android.Widget.ToastLength.Short).Show(); return; } string[] items = new string[bondedDevices.Count]; for (int i = 0; i < bondedDevices.Count; i++) { items[i] = bondedDevices[i].Name; } Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(activity); builder.SetTitle("请选择打印设备:"); builder.SetItems(items, new System.EventHandler<Android.Content.DialogClickEventArgs>(items_click)); builder.SetNegativeButton("取消", delegate { return; }); builder.Show(); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Create your application here SetContentView(Resource.Layout.History); try { nGXPrinter = NGXPrinter.NgxPrinterInstance; nGXPrinter.InitService(this, this); } catch (Exception ex) { ExceptionLog.LogDetails(this, "Printer not connected " + ex.Message); Console.WriteLine(ex.Message); } var clearAlertDialog = new Android.App.AlertDialog.Builder(this); clearAlertDialog.SetTitle("Clear History"); clearAlertDialog.SetMessage("Do you want to clear history ?"); clearAlertDialog.SetPositiveButton("OK", (ss, se) => { ClearHistory(); }); clearAlertDialog.SetNegativeButton("Cancel", (ss, se) => { }); var home = FindViewById <Button>(Resource.Id.btnHomeFromHistory); var btnPrint = FindViewById <Button>(Resource.Id.btnHistoryPrint); btnclearHistory = FindViewById <Button>(Resource.Id.btnClearHistory); var btnHome = FindViewById <Button>(Resource.Id.btnHomeFromHistory); linearLayout = FindViewById <LinearLayout>(Resource.Id.baseLinearLayout); ParentLinearLayout = FindViewById <LinearLayout>(Resource.Id.parentLinearLayout); btnclearHistory.Click += (s, e) => { clearAlertDialog.Show(); }; btnPrint.Click += BtnPrint_Click; btnHome.Click += BtnHome_Click; historyList = FindViewById <ListView>(Resource.Id.historylistView); billHistory = FuelDB.Singleton.GetBillHitory(); try { if (billHistory?.Count() > 0) { adapter = new BillHistoryListAdapter(this, billHistory.ToList()); historyList.Adapter = adapter; DisableClearButton(true); } else { Toast.MakeText(this, "There is no history to show..", ToastLength.Short).Show(); DisableClearButton(false); } } catch { Toast.MakeText(this, "There is no history to show..", ToastLength.Short).Show(); DisableClearButton(false); } }
protected override void OnCreate(Bundle savedInstanceState) { usuarios = new List <User> { new User { pass = "******", username = "******", pisto = 10000 }, new User { pass = "******", username = "******", pisto = 500 }, new User { pass = "******", username = "******", pisto = 1000 } }; base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.activity_main); //Inicializo las variables LinearLayout layoutLogin = FindViewById <LinearLayout>(Resource.Id.linearLayoutLogin); RelativeLayout layoutPist = FindViewById <RelativeLayout>(Resource.Id.relativeLayout1); FloatingActionButton fabin = FindViewById <FloatingActionButton>(Resource.Id.fabin); FloatingActionButton fabout = FindViewById <FloatingActionButton>(Resource.Id.fabout); Button btnLogin = FindViewById <Button>(Resource.Id.btnLogin); EditText txtUsername = FindViewById <EditText>(Resource.Id.txtUsername); EditText txtpass = FindViewById <EditText>(Resource.Id.txtPass); EditText txtPisto = FindViewById <EditText>(Resource.Id.txtCantPisto); TextView lblLogin = FindViewById <TextView>(Resource.Id.lblLogin); TextView lblUsername = FindViewById <TextView>(Resource.Id.lblUsername); TextView lblpisto = FindViewById <TextView>(Resource.Id.lblPistoTotal); layoutLogin.Visibility = ViewStates.Visible; layoutPist.Visibility = ViewStates.Invisible; fabin.Click += (sender, e) => { Android.App.AlertDialog alerta = new Android.App.AlertDialog.Builder(this).Create(); double cant = Convert.ToDouble(txtPisto.Text); alerta.SetTitle("Deposito"); alerta.SetMessage("$ " + cant); alerta.Show(); usuarioLogin.pisto += cant; txtPisto.Text = ""; lblpisto.Text = $"Cantidad total $ {usuarioLogin.pisto:N2}"; }; fabout.Click += (sender, e) => { double cant = Convert.ToDouble(txtPisto.Text); Android.App.AlertDialog alerta = new Android.App.AlertDialog.Builder(this).Create(); if (cant <= usuarioLogin.pisto) { alerta.SetTitle("Retiro"); alerta.SetMessage("$ " + cant); alerta.Show(); usuarioLogin.pisto -= cant; txtPisto.Text = ""; } else { alerta.SetTitle("Error"); alerta.SetMessage("No hay fondos suficientes"); alerta.Show(); } lblpisto.Text = $"Cantidad total $ {usuarioLogin.pisto:N2}"; }; btnLogin.Click += (sender, e) => { var user = usuarios.Find(u => u.username == txtUsername.Text); if (user == null) { lblLogin.Text = "No existe el usuario"; return; } if (user.pass != txtpass.Text) { lblLogin.Text = "Contraseña incorrecta"; return; } usuarioLogin = user; lblUsername.Text = usuarioLogin.username; lblpisto.Text = $"Cantidad total $ {usuarioLogin.pisto:N2}"; layoutLogin.Visibility = ViewStates.Invisible; layoutPist.Visibility = ViewStates.Visible; }; }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Create your application here SetContentView(Resource.Layout.FuelEntry); alertDialog = new Android.App.AlertDialog.Builder(this); alertDialog.SetTitle("Fuel is from petrol bunk"); alertDialog.SetMessage("Do you want to proceed ?"); alertDialog.SetPositiveButton("OK", (s, e) => { StoreDetils(); }); alertDialog.SetNegativeButton("Cancel", (s, e) => { }); // var resposeString = WebService.GetDataFromWebService("LoadVD"); try { VehicleList = FuelDB.Singleton.GetValue().ToList(); billDetailsList = FuelDB.Singleton.GetBillDetails().ToList().FirstOrDefault(); // FuelLiters = FuelDB.Singleton.GetFuel().ToList(); } catch (Exception w) { Console.WriteLine(w.Message); } if (VehicleList != null) { myVehiclelist = VehicleList.Select(I => I.RegNo).Distinct().ToArray(); } lblTitle = FindViewById <TextView>(Resource.Id.lblTittle); vehicleNumber = FindViewById <AutoCompleteTextView>(Resource.Id.vehicleNumber); if (myVehiclelist != null) { var adapter = new ArrayAdapter <String>(this, Resource.Layout.select_dialog_item_material, myVehiclelist); //var adapter = new AutoSuggestAdapter(this, Resource.Layout.select_dialog_item_material, myVehiclelist.ToList()); vehicleNumber.Adapter = adapter; vehicleNumber.Threshold = 1; vehicleNumber.ItemClick += VehicleNumber_ItemClick; vehicleNumber.TextChanged += VehicleNumber_TextChanged; } billNumber = FindViewById <TextView>(Resource.Id.txtBillNumber); billNumber.Text = billDetailsList?.BillPrefix + billDetailsList?.BillCurrentNumber; dateTimeNow = FindViewById <TextView>(Resource.Id.lbldateTime).Text = DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture); fuelTypeSpinner = FindViewById <Spinner>(Resource.Id.fuelSpinner); fuelTypeSpinner.Adapter = new ArrayAdapter(this, Resource.Layout.select_dialog_item_material, new string[] { "Outward", "Inwards" }); fuelFormSpinner = FindViewById <Spinner>(Resource.Id.fuelFormSpinner); fuelFormSpinner.Adapter = new ArrayAdapter(this, Resource.Layout.select_dialog_item_material, StockList); var bunkDetailsLayout = FindViewById <LinearLayout>(Resource.Id.layBunkDetails); cashModeSpinner = FindViewById <Spinner>(Resource.Id.paymentMode); cashModeSpinner.Adapter = new ArrayAdapter(this, Resource.Layout.select_dialog_item_material, new string[] { "Cash", "Credit" }); vehicleTypeSpinner = FindViewById <Spinner>(Resource.Id.vehicleType); vehicleTypeAdapter = new ArrayAdapter(this, Resource.Layout.select_dialog_item_material, new string[] { "Select", "Line Vehicle", "InterCard", "Loader", "Genset 1", "Genset 2", "Genset 3" }); vehicleTypeSpinner.ItemSelected += VehicleTypeSpinner_ItemSelected; //VehicleTypeSpinner_ItemClick; var layMeterFault = FindViewById <LinearLayout>(Resource.Id.layMeterFault); checkBox = FindViewById <CheckBox>(Resource.Id.chckMeterFault); checkBox.CheckedChange += (s, e) => { if (fuelTypeSpinner.SelectedItem.ToString() == "Outward") { layMeterFault.Visibility = checkBox.Checked ? Android.Views.ViewStates.Gone : Android.Views.ViewStates.Visible; } txtClosingKMS.Text = string.Empty; lblkmpl.Text = "KMPL"; }; driverNameSpinner = FindViewById <Spinner>(Resource.Id.driverName); fuelToFill = FindViewById <EditText>(Resource.Id.fuelToFill); fuelAvailable = FindViewById <TextView>(Resource.Id.fuelAvailable); txtOpeningKMS = FindViewById <TextView>(Resource.Id.txtOpeningKMS); txtClosingKMS = FindViewById <EditText>(Resource.Id.txtClosingKMS); lblkmpl = FindViewById <TextView>(Resource.Id.lblkmpl); txtFilledBy = FindViewById <EditText>(Resource.Id.txtFilledBy); txtRate = FindViewById <EditText>(Resource.Id.txtRate); lblTotalPrice = FindViewById <TextView>(Resource.Id.lblTotalPrice); txtRemarks = FindViewById <EditText>(Resource.Id.txtRemarks); imgFuel = FindViewById <ImageView>(Resource.Id.imgFuel); fuelToFill.TextChanged += (s, e) => CheckFuelAvailbility(); txtRate.TextChanged += (s, e) => CalculateFuelTotalAmount(); //txtOpeningKMS.TextChanged += (s, e) => //{ // if (!string.IsNullOrEmpty(txtOpeningKMS.Text) && !string.IsNullOrEmpty(txtClosingKMS.Text) // && string.IsNullOrEmpty(fuelToFill.Text)) // { // GetKMPL(); // } //}; driverNameSpinner.ItemSelected += (s, ev) => { if (!isDriverNameSpinnerSelected) { isDriverNameSpinnerSelected = true; driverNameSpinner.PerformClick(); } else { txtOpeningKMS.Text = VehicleList.Where((a => a.DriverName == driverNameSpinner.SelectedItem.ToString())) .Distinct().Select(i => i.OpeningKM).Distinct().First(); fuelToFill.RequestFocus(); } }; if (billDetailsList != null) { fuelAvailable.Text = $"{billDetailsList.AvailableLiters}"; } txtClosingKMS.TextChanged += (s, e) => { if (txtOpeningKMS.Text.Equals("0")) { return; } if (!string.IsNullOrEmpty(txtOpeningKMS.Text) && !string.IsNullOrEmpty(txtClosingKMS.Text) && !string.IsNullOrEmpty(fuelToFill.Text)) { if (Convert.ToDecimal(txtClosingKMS.Text) > Convert.ToDecimal(txtOpeningKMS.Text) && Convert.ToDecimal(fuelToFill.Text) > 0) { GetKMPL(); } else { lblkmpl.Text = "KMPL"; } } }; //var pref = PreferenceManager.GetDefaultSharedPreferences(this); //var billnumber = pref.GetInt(Utilities.BILLNUMBER, 0); //var billnumber = AppPreferences.GetInt(this, Utilities.BILLNUMBER); // var billnumber = FuelDB.Singleton.GetBillDetails().First()?.BillCurrentNumber; //Console.WriteLine(billnumber); //if (billnumber == 0) //{ // billNumber.Text = Utilities.BILL_NUMBER.ToString(); // //pref.Edit().PutInt("billnumber", Convert.ToInt32(billNumber.Text)); //} //else //{ // ++billnumber; // billNumber.Text = billnumber.ToString(); //} var btnStore = FindViewById <LinearLayout>(Resource.Id.btnStore); btnStore.Click += (s, e) => { //if (fuelSpinner.SelectedItem.ToString() != null && fuelFormSpinner.SelectedItem.ToString() != null // && vehicleNumber.Text != string.Empty && vehicleTypeSpinner.SelectedItem.ToString() != null) //{ //} //else //{ // Toast.MakeText(this, "Please enter all the values..", ToastLength.Short).Show(); //} //if (!string.IsNullOrEmpty(txtOpeningKMS.Text) && !string.IsNullOrEmpty(txtClosingKMS.Text)) //{ // if (Convert.ToDecimal(txtClosingKMS.Text) < Convert.ToDecimal(txtOpeningKMS.Text)) // { // var alertDialog = new Android.App.AlertDialog.Builder(this); // alertDialog.SetTitle("Enter valid destination KM"); // alertDialog.SetMessage("Please check starting KM and closing KM"); // alertDialog.SetPositiveButton("OK", (ss, se) => { }); // alertDialog.Show(); // } //} if (vehicleTypeSpinner.SelectedItemPosition.Equals(0)) { Toast.MakeText(this, "Select Vehicle Type...", ToastLength.Short).Show(); return; } if (fuelFormSpinner.SelectedItem.Equals("Stock")) { StoreDetils(); } else { alertDialog.Show(); } }; fuelTypeSpinner.ItemSelected += (s, e) => { fuelFormSpinner.Adapter = null; //StockList = null; if (fuelTypeSpinner.SelectedItem.Equals("Inwards")) { fuelFormSpinner.Adapter = new ArrayAdapter(this, Resource.Layout.select_dialog_item_material, new string[] { "Bunk" }); layMeterFault.Visibility = Android.Views.ViewStates.Gone; FindViewById <LinearLayout>(Resource.Id.layFuelEntry).SetBackgroundResource(Resource.Color.backgroundInward); lblTitle.SetBackgroundResource(Resource.Color.btnAndTitleBackgroundGreen); btnStore.SetBackgroundResource(Resource.Color.btnAndTitleBackgroundGreen); layMeterFault.Visibility = Android.Views.ViewStates.Gone; checkBox.Visibility = Android.Views.ViewStates.Gone; //StockList = new string[] { "Bunk" }; } else { fuelFormSpinner.Adapter = new ArrayAdapter(this, Resource.Layout.select_dialog_item_material, new string[] { "Stock", "Bunk" }); layMeterFault.Visibility = Android.Views.ViewStates.Visible; FindViewById <LinearLayout>(Resource.Id.layFuelEntry).SetBackgroundColor(Color.White); lblTitle.SetBackgroundResource(Resource.Color.borderColor); btnStore.SetBackgroundResource(Resource.Color.borderColor); layMeterFault.Visibility = Android.Views.ViewStates.Visible; checkBox.Visibility = Android.Views.ViewStates.Visible; // StockList = new string[] { "Stock", "Bunk" }; } ClearAllFields(); //fuelFormSpinner.PerformClick(); //fuelFormSpinnerAdapter.NotifyDataSetChanged(); }; fuelFormSpinner.ItemSelected += (s, e) => { if (fuelFormSpinner.SelectedItem.Equals("Stock")) { bunkDetailsLayout.Visibility = Android.Views.ViewStates.Gone; btnStore.SetBackgroundResource(Resource.Color.borderColor); lblTitle.SetBackgroundResource(Resource.Color.borderColor); FindViewById <LinearLayout>(Resource.Id.layFuelEntry).SetBackgroundColor(Color.White); imgFuel.Visibility = Android.Views.ViewStates.Gone; } else { bunkDetailsLayout.Visibility = Android.Views.ViewStates.Visible; if (fuelTypeSpinner.SelectedItem.Equals("Outward")) { FindViewById <LinearLayout>(Resource.Id.layFuelEntry).SetBackgroundResource(Resource.Color.backgroundBunk); btnStore.SetBackgroundColor(Color.Brown); lblTitle.SetBackgroundResource(Resource.Color.btnAndTitleBackgroundRed); } //else //{ // btnStore.SetBackgroundColor(Color.Red); // lblTitle.SetBackgroundColor(Color.Red); // FindViewById<LinearLayout>(Resource.Id.layFuelEntry).SetBackgroundColor(Color.White); //} imgFuel.Visibility = Android.Views.ViewStates.Visible; //btnStore.SetCompoundDrawables(Resources.GetDrawable(Resource.Drawable.ic_launcher), null, null, null); } }; }
private void DialogToShowAccountsOnDevice () { var am = AccountManager.Get (this); // "this" references the current Context var accounts = am.GetAccountsByType ("com.google"); var miaAlert = new Android.App.AlertDialog.Builder (this); if (accounts != null && accounts.Length > 0) { miaAlert.SetTitle ("i found an account name! and total # = " + accounts.Length); miaAlert.SetMessage (accounts [0].Name); } else { miaAlert.SetTitle ("No Account Found"); miaAlert.SetMessage ("None"); } var alert = miaAlert.Create (); alert.Show (); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.TaskDetail); var toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar); this.SetSupportActionBar(toolbar); var isEdit = false; if (Intent.HasExtra(Constants.Extras.Task)) { isEdit = true; this.task = JsonConvert.DeserializeObject<MobileTask>(Intent.GetStringExtra(Constants.Extras.Task)); } else { this.task = new MobileTask(); } this.description = this.FindViewById<EditText>(Resource.Id.description); this.description.Text = this.task.Description; this.date = this.FindViewById<TextView>(Resource.Id.date); this.date.Text = this.task.DateDue != null ? this.task.DateDue.Value.ToString("ddd, M/d/yy h:mm tt") : null; this.changeDate = this.FindViewById<Button>(Resource.Id.changeDate); this.changeDate.Click += (sender, args) => { var calendar = Calendar.GetInstance(Java.Util.TimeZone.Default); var date = DateTime.Now; if (this.task.DateDue != null) { calendar.Time = new Date(this.task.DateDue.Value.Millisecond); date = this.task.DateDue.Value; } var picker = new DatePickerDialog(this, this, date.Year, date.Month - 1, date.Day); picker.Show(); }; this.specifyDateDue = this.FindViewById<CheckBox>(Resource.Id.specifyDateDue); this.specifyDateDue.CheckedChange += (sender, args) => { if (args.IsChecked) { this.date.Visibility = ViewStates.Visible; this.changeDate.Visibility = ViewStates.Visible; } else { this.date.Visibility = ViewStates.Gone; this.changeDate.Visibility = ViewStates.Gone; this.task.DateDue = null; } }; this.specifyDateDue.Checked = this.task.DateDue != null; this.completed = this.FindViewById<CheckBox>(Resource.Id.completed); this.completed.Checked = this.task.IsCompleted; var saveButton = this.FindViewById<Button>(Resource.Id.save); saveButton.Click += async delegate { this.task.Description = description.Text; this.task.IsCompleted = completed.Checked; await MobileService.Instance.UpsertTaskAsync(this.task); this.Finish(); }; var deleteButton = this.FindViewById<Button>(Resource.Id.delete); if (isEdit) { deleteButton.Click += delegate { var builder = new Android.App.AlertDialog.Builder(this) .SetTitle("Are you sure?") .SetMessage("Delete '" + task.Description + "'?") .SetPositiveButton(Resource.String.Yes, async (sender, args) => { await MobileService.Instance.DeleteTaskAsync(task.Id); this.Finish(); }) .SetNegativeButton(Resource.String.No, (sender, args) => { /* Do nothing */ }); builder.Create().Show(); }; } else { deleteButton.Visibility = ViewStates.Gone; } }
protected override void OnTapped() { base.OnTapped(); #if __IOS__ App.Navigation.Navigation.PushAsync(new SelectionPage(this, text.Text, Items, Key, DefaultValue)); #endif #if __ANDROID__ var builder = new Android.App.AlertDialog.Builder(Forms.Context); int checkedItem; if (Values == null) { checkedItem = Settings.Current.GetValueOrDefault<int>(Key, DefaultValue); } else { checkedItem = Array.IndexOf(Values, Settings.Current.GetValueOrDefault<string>(Key, Values[DefaultValue])); checkedItem = checkedItem < 0 ? 0 : checkedItem; } builder.SetTitle(text.Text); builder.SetSingleChoiceItems(Items, checkedItem, (sender, args) => { if (Values == null) { Settings.Current.AddOrUpdateValue<int>(Key, args.Which); } else { Settings.Current.AddOrUpdateValue<string>(Key, Values[args.Which]); } Update(); }); var dialog = builder.Create(); dialog.SetButton(Catalog.GetString("Ok"), (s, e) => { dialog.Dismiss(); }); dialog.Show(); #endif }
private void DeleteFolderOrFile (string path) { popupWindow.Dismiss (); var alertDialogConfirmDelete = new Android.App.AlertDialog.Builder (Activity); alertDialogConfirmDelete.SetTitle("Waarschuwing"); alertDialogConfirmDelete.SetMessage("Bent u zeker van deze verwijder actie? \nDeze actie is niet terug te draaien."); alertDialogConfirmDelete.SetPositiveButton ("Verwijderen", async delegate { try { parentActivity.ShowProgressDialog ("Verwijderen... Een ogenblik geduld a.u.b."); bool deleteSucceed = await DataLayer.Instance.DeleteFileOrFolder (path); parentActivity.HideProgressDialog (); if (!deleteSucceed) { Toast.MakeText (Android.App.Application.Context, "Verwijderen mislukt - druk op ververs en probeer het a.u.b. opnieuw", ToastLength.Long).Show (); } else { Toast.MakeText (Android.App.Application.Context, "Verwijderen succesvol", ToastLength.Short).Show (); //Refresh listview RefreshData (); } } catch (Exception ex){ Insights.Report(ex); parentActivity.HideProgressDialog (); Toast.MakeText (Android.App.Application.Context, "Verwijderen mislukt - druk op ververs en probeer het a.u.b. opnieuw", ToastLength.Long).Show (); } }); alertDialogConfirmDelete.SetNegativeButton ("Annuleren", delegate { alertDialogConfirmDelete.Dispose(); }); alertDialogConfirmDelete.Create ().Show (); }
private async void OpenFileIn (TreeNode clickedItem) { try { if (popupWindow != null) { popupWindow.Dismiss (); } string mimeTypeOfClickedItem = MimeTypeHelper.GetMimeType (clickedItem.Path); clickedItem.Type = mimeTypeOfClickedItem; if (clickedItem.Type.Equals ("application/pdf")) { Intent intent = new Intent (Intent.ActionView); new Thread (new ThreadStart (async delegate { //Show progress dialog while loading parentActivity.HideProgressDialog (); parentActivity.ShowProgressDialog (null); string fullFilePath = await DataLayer.Instance.GetFilePath (clickedItem.Path); //Controleer internet verbinding var connectivityManager = (ConnectivityManager)Android.App.Application.Context.GetSystemService (Context.ConnectivityService); var activeConnection = connectivityManager.ActiveNetworkInfo; if ((activeConnection != null) && activeConnection.IsConnected) { //Internet verbinding gedetecteerd //Create temp file string temporaryFilePath = System.IO.Path.Combine ("/storage/emulated/0/Download", clickedItem.Name); if (File.Exists (temporaryFilePath)) { File.Delete (temporaryFilePath); } //Save settings of last opened file ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences (Activity); ISharedPreferencesEditor editor = prefs.Edit (); editor.PutString ("fileNameLastOpenedPdf", clickedItem.Name); editor.PutString ("pathLastOpenedPdf", clickedItem.Path); editor.PutString ("temporaryFilePath", temporaryFilePath); editor.PutBoolean ("isFavorite", clickedItem.IsFavorite); editor.Commit (); //Save temporary file in filesystem Byte[] fileBytes = File.ReadAllBytes (fullFilePath); File.WriteAllBytes (temporaryFilePath, fileBytes); Android.Net.Uri uri = Android.Net.Uri.Parse ("file://" + temporaryFilePath); intent.SetDataAndType (uri, clickedItem.Type); parentActivity.HideProgressDialog (); if(File.Exists (temporaryFilePath)){ Activity.StartActivity (intent); } else { Toast.MakeText (Android.App.Application.Context, "Openen bestand mislukt", ToastLength.Long).Show (); } } else { //Geen internet verbinding var alertDialogConfirmDelete = new Android.App.AlertDialog.Builder (Activity); alertDialogConfirmDelete.SetTitle ("Geen verbinding"); alertDialogConfirmDelete.SetMessage ("U heeft momenteel geen internet verbinding. Het maken van PDF annotaties is daarom niet mogelijk."); alertDialogConfirmDelete.SetPositiveButton ("OK", async delegate { Android.Net.Uri uri = Android.Net.Uri.Parse ("file://" + fullFilePath); intent.SetDataAndType (uri, clickedItem.Type); parentActivity.HideProgressDialog (); Activity.StartActivity (intent); }); alertDialogConfirmDelete.Create ().Show (); } })).Start (); } else {//Ander bestandstype dan PDF openen //Show progress dialog while loading parentActivity.HideProgressDialog (); parentActivity.ShowProgressDialog (null); string fullFilePath = await DataLayer.Instance.GetFilePath (clickedItem.Path); Intent intent = new Intent(Intent.ActionView, Android.Net.Uri.Parse (CustomContentProvider.CONTENT_URI + fullFilePath)); intent.SetFlags (ActivityFlags.GrantReadUriPermission); intent.SetFlags (ActivityFlags.NewTask); intent.SetFlags (ActivityFlags.ClearWhenTaskReset); Activity.StartActivity (intent); } } catch (Exception ex){ Insights.Report(ex); Console.WriteLine (ex.Message); parentActivity.HideProgressDialog (); if (ex is ActivityNotFoundException) { Toast.MakeText (Android.App.Application.Context, "Geen app op uw apparaat gevonden om dit bestandstype te kunnen openen", ToastLength.Long).Show (); } else { Toast.MakeText (Android.App.Application.Context, "Openen bestand mislukt", ToastLength.Long).Show (); } } }
protected override void OnCreate(Bundle savedInstanceState) { //bitopiApplication = (BitopiApplication)this.ApplicationContext; builder = new Android.App.AlertDialog.Builder(this); builder.SetMessage("Hello, World!"); builder.SetNegativeButton("Cancel", (s, e) => { /* do something on Cancel click */ }); base.OnCreate(savedInstanceState); _MyTaskList = new MyTaskList(this); _approvalType = (ApprovalType)(Convert.ToInt16(Intent.GetStringExtra("ApprovalType"))); _approvalRoleType = (ApprovalRoleType)(Convert.ToInt16(Intent.GetStringExtra("ApprovalRoleType"))); SupportRequestWindowFeature(WindowCompat.FeatureActionBar); SupportActionBar.SetDisplayShowCustomEnabled(true); SupportActionBar.SetCustomView(Resource.Layout.custom_actionbar); rltitle = FindViewById <RelativeLayout>(Resource.Id.rltitle); tvHeaderName = FindViewById <TextView>(Resource.Id.tvHeaderName); SetContentView(Resource.Layout.TNAMyTaskList); lvMyTask = FindViewById <AnimatedExpandableListView>(Resource.Id.lvMyTask); tvMsg = FindViewById <TextView>(Resource.Id.tvMsg); tvMsg.Visibility = ViewStates.Gone; _chkApproveAll = FindViewById <CheckBox>(Resource.Id.chkSelectAll); rlMsg = FindViewById <RelativeLayout>(Resource.Id.rlMsg); rlapprovalDetail = FindViewById <RelativeLayout>(Resource.Id.rlapprovalDetail); switch (bitopiApplication.MyTaskType) { case MyTaskType.UNSEEN: tvMsg.Text = "You don't have any unseen Task"; tvHeaderName.Text = "My Unseen Task"; break; case MyTaskType.SEEN: tvMsg.Text = "You don't have any seen Task"; tvHeaderName.Text = "My Seen Task"; break; case MyTaskType.COMPLETED: tvMsg.Text = "You don't have any completed Task"; tvHeaderName.Text = "My Completed Task"; break; } RLleft_drawer = FindViewById <RelativeLayout>(Resource.Id.RLleft_drawer); mDrawerLayout = FindViewById <DrawerLayout>(Resource.Id.drawer_layout); FindViewById <ImageButton>(Resource.Id.btnDrawermenu).Visibility = ViewStates.Visible; FindViewById <ImageButton>(Resource.Id.btnDrawermenu).Click += (s, e) => { if (mDrawerLayout.IsDrawerOpen(RLleft_drawer)) { mDrawerLayout.CloseDrawer(RLleft_drawer); } else { mDrawerLayout.OpenDrawer(RLleft_drawer); } }; //LoadDrawerView(); }
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Use this to return your custom view for this Fragment View myView = inflater.Inflate(Resource.Layout.Review1, container, false); user = myView.FindViewById <TextView>(Resource.Id.logo); RestaurantName = myView.FindViewById <EditText>(Resource.Id.resName); reviews = myView.FindViewById <EditText>(Resource.Id.comment); reviewBtn = myView.FindViewById <Button>(Resource.Id.rbtn); reviewshowBtn = myView.FindViewById <Button>(Resource.Id.r1btn); Android.App.AlertDialog.Builder alert = new Android.App.AlertDialog.Builder(localContext); reviewBtn.Click += delegate { user.Text = user1; var value1 = RestaurantName.Text; var value2 = reviews.Text; if (value1.Equals(" ") || value1.Equals("") || value2.Equals(" ") || value2.Equals("")) { alert.SetTitle("Error"); alert.SetMessage(" Please Enter A Value...."); alert.SetPositiveButton("OK", (senderAlert, args) => { Toast.MakeText(localContext, "Please Enter a Valid! Value", ToastLength.Short).Show(); }); Dialog dialog = alert.Create(); dialog.Show(); } else { DBHelper obj = new DBHelper(localContext); obj.InsertValue1(user1, value1, value2); alert.SetMessage(" Review Added successfull"); alert.SetPositiveButton("OK", (senderAlert, args) => { Toast.MakeText(localContext, "Thanks ", ToastLength.Short).Show(); Dialog dialog = alert.Create(); dialog.Show(); Intent back = new Intent(localContext, typeof(UserTab)); StartActivity(back); }); } }; reviewshowBtn.Click += delegate { Intent newScreen = new Intent(localContext, typeof(Showreview)); StartActivity(newScreen); user.Text = user1; var r = RestaurantName.Text; var rv = reviews.Text; if (r.Equals(" ") || r.Equals("") || rv.Equals(" ") || rv.Equals("")) { alert.SetTitle("Error"); alert.SetMessage(" Please Enter A Value...."); alert.SetPositiveButton("OK", (senderAlert, args) => { Toast.MakeText(localContext, "Please Enter a Valid! Value", ToastLength.Short).Show(); }); Dialog dialog = alert.Create(); dialog.Show(); } }; // Create your application here return(myView); }
public override void OnBackPressed() { var builder = new Android.App.AlertDialog.Builder(this); builder.SetTitle ("Exit."); builder.SetIcon (Android.Resource.Drawable.IcDialogAlert); builder.SetMessage("Exit App?"); builder.SetPositiveButton("OK", (s, e) => { mSharedPreferences = this.GetSharedPreferences ("CheckInPrefs", FileCreationMode.Private); ISharedPreferencesEditor editor = mSharedPreferences.Edit (); editor.Remove ("SessionKey"); editor.Commit (); if (!(geofenceRequestIntent == null)) { geofenceRequestIntent.Cancel (); } Finish(); Android.OS.Process.KillProcess(Android.OS.Process.MyPid()); //System.Environment.Exit(0); }); builder.SetNegativeButton("Cancel", (s, e) => { }); builder.Create().Show(); }
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup root = (ViewGroup)inflater.Inflate(Resource.Layout.fragment_content_addactivity, null); txt_main = root.FindViewById <TextView>(Resource.Id.txt_main); txt_item_lvl1 = root.FindViewById <TextView>(Resource.Id.txt_item_lvl1); img_item_lvl1 = root.FindViewById <ImageView>(Resource.Id.img_item_lvl1); try { if (Arguments != null) { if (objSelectedItem == null) { objSelectedItem = new List <ItemPayloadModelWithBase64>(); } objSelectedItem = Newtonsoft.Json.JsonConvert.DeserializeObject <List <ItemPayloadModelWithBase64> >(Arguments.GetString("siteparam")); if (objSelectedItem.FirstOrDefault() != null) { txt_main.Text = "Selected Category:"; img_item_lvl1.Visibility = ViewStates.Visible; txt_item_lvl1.Visibility = ViewStates.Visible; txt_item_lvl1.Text = objSelectedItem.FirstOrDefault() != null?objSelectedItem.FirstOrDefault().ItemName : ""; img_item_lvl1.SetImageBitmap(BitmapHelpers.Base64ToBitmap(objSelectedItem.FirstOrDefault().ItemIcon)); } else { txt_main.Text = "Select Sub-Category:"; img_item_lvl1.Visibility = ViewStates.Gone; txt_item_lvl1.Visibility = ViewStates.Gone; } } else { objSelectedItem = null; txt_main.Text = "Select Category:"; img_item_lvl1.Visibility = ViewStates.Gone; txt_item_lvl1.Visibility = ViewStates.Gone; } } catch (Exception ex) { } try { string mStringLoginInfo = string.Empty; string mStringSessionToken = string.Empty; try { objdb = new DBaseOperations(); var lstu = objdb.selectTable(); if (lstu != null && lstu.Count > default(int)) { var uobj = lstu.FirstOrDefault(); if (uobj.Password == " ") { throw new Exception("Please login again"); } mStringLoginInfo = uobj.EmailId; mStringSessionToken = uobj.AuthToken; } } catch { } if (string.IsNullOrEmpty(mStringSessionToken)) { throw new Exception("Token does not exists"); } if (objSelectedItem == null || objSelectedItem.Count() <= default(int)) { var client = new RestClient(Common.UrlBase); var request = new RestRequest("Product/GetCategoryList", Method.GET); request.AddHeader("Content-Type", "application/json"); request.AddHeader("TokenKey", mStringSessionToken); IRestResponse response = client.Execute(request); var content = response.Content; var responseObj = Newtonsoft.Json.JsonConvert.DeserializeObject <IList <CategoryMasterResponse> >(content); if (responseObj != null && responseObj.Count() > default(int)) { var gtypecodes = new List <string>(); var gstrings = responseObj.Select(r => r.ProductTypeName).ToList(); var gcodes = responseObj.Select(r => r.ProductTypeId).ToList(); //responseObj.Select(r => r.pr) var gimages = BitmapHelpers.GetImageListFromUrlList(responseObj.Select(r => r.catImageName).ToList(), mStringSessionToken, this.Activity.Resources); gstrings.Add("Back to Dashboard"); gcodes.Add("BCK"); foreach (var x in gcodes) { gtypecodes.Add(ProductType.None.GetHashCode().ToString()); } gimages.Add(BitmapFactory.DecodeResource(this.Activity.Resources, Resource.Drawable.back)); gridViewString = gstrings.ToArray(); gridViewCodeString = gcodes.ToArray(); gridViewTypeCodeString = gtypecodes.ToArray(); gridViewImages = gimages.ToArray(); } else { throw new Exception("No item found"); } } else if (objSelectedItem.Count() > default(int) && !string.IsNullOrEmpty(objSelectedItem.FirstOrDefault().ItemCode)) { var gstrings = new List <string>(); var gcodes = new List <string>(); var gtypecodes = new List <string>(); IList <Bitmap> gimages = new List <Bitmap>(); var client = new RestClient(Common.UrlBase); var request = new RestRequest("Product/GetSubCategoryList", Method.GET); request.AddHeader("Content-Type", "application/json"); request.AddHeader("TokenKey", mStringSessionToken); request.AddQueryParameter("catId", System.Net.WebUtility.UrlEncode(objSelectedItem.FirstOrDefault().ItemCode.Replace("Ø", ""))); IRestResponse response = client.Execute(request); var content = response.Content; var responseObj = Newtonsoft.Json.JsonConvert.DeserializeObject <IList <ProductDetailResponse> >(content); if (responseObj != null && responseObj.Count() > default(int)) { gstrings = responseObj.Select(r => r.ProductName).ToList(); gcodes = responseObj.Select(r => r.ProductId).ToList(); gtypecodes = responseObj.Select(r => r.prodType.GetHashCode().ToString()).ToList(); gimages = BitmapHelpers.GetImageListFromUrlList(responseObj.Select(r => r.prodImageName).ToList(), mStringSessionToken, this.Activity.Resources); gstrings.Add(string.Format("Back to {0}", responseObj.FirstOrDefault().ProductTypeName)); gcodes.Add(string.Format("Ø{0}", responseObj.Select(r => r.CategoryID).FirstOrDefault())); gtypecodes.Add(ProductType.None.GetHashCode().ToString()); gimages.Add(BitmapFactory.DecodeResource(this.Activity.Resources, Resource.Drawable.back)); } gstrings.Add("Back to Dashboard"); gcodes.Add("BCK"); gtypecodes.Add(ProductType.None.GetHashCode().ToString()); gimages.Add(BitmapFactory.DecodeResource(this.Activity.Resources, Resource.Drawable.backtoprevious)); gstrings.Add("Add New Product"); gcodes.Add("NPR"); gtypecodes.Add(ProductType.None.GetHashCode().ToString()); gimages.Add(BitmapFactory.DecodeResource(this.Activity.Resources, Resource.Drawable.addprd)); gridViewString = gstrings.ToArray(); gridViewCodeString = gcodes.ToArray(); gridViewTypeCodeString = gtypecodes.ToArray(); gridViewImages = gimages.ToArray(); } } catch (Exception ex) { this.Activity.RunOnUiThread(() => { Android.App.AlertDialog.Builder alertDiag = new Android.App.AlertDialog.Builder(this.Activity); alertDiag.SetTitle(Resource.String.DialogHeaderError); alertDiag.SetMessage(ex.Message); alertDiag.SetIcon(Resource.Drawable.alert); alertDiag.SetPositiveButton(Resource.String.DialogButtonOk, (senderAlert, args) => { DashboardFragment objFragment = new DashboardFragment(); Android.Support.V4.App.FragmentTransaction tx = FragmentManager.BeginTransaction(); tx.Replace(Resource.Id.m_main, objFragment, Constants.dashboard); tx.Commit(); }); Dialog diag = alertDiag.Create(); diag.Show(); diag.SetCanceledOnTouchOutside(false); }); } try { if (gridViewCodeString.Count() == gridViewImages.Count()) { _generic_grid_menu_bitmap_helper adapterViewAndroid = new _generic_grid_menu_bitmap_helper(this.Activity, gridViewString, gridViewCodeString, gridViewTypeCodeString, gridViewImages); androidGridView = root.FindViewById <GridView>(Resource.Id.grid_view_activities); new System.Threading.Thread(new System.Threading.ThreadStart(() => { if (this.Activity != null) { this.Activity.RunOnUiThread(() => { androidGridView.SetAdapter(adapterViewAndroid); }); } })).Start(); androidGridView.ItemClick += (sndr, argus) => ItemSearch_clicked(sndr, argus, this.Activity); } else { throw new Exception("No data available. Please report to admin"); } } catch (Exception ex) { this.Activity.RunOnUiThread(() => { Android.App.AlertDialog.Builder alertDiag = new Android.App.AlertDialog.Builder(this.Activity); alertDiag.SetTitle(Resource.String.DialogHeaderError); alertDiag.SetMessage(ex.Message); alertDiag.SetIcon(Resource.Drawable.alert); alertDiag.SetPositiveButton(Resource.String.DialogButtonOk, (senderAlert, args) => { DashboardFragment objFragment = new DashboardFragment(); Android.Support.V4.App.FragmentTransaction tx = FragmentManager.BeginTransaction(); tx.Replace(Resource.Id.m_main, objFragment, Constants.dashboard); tx.Commit(); }); Dialog diag = alertDiag.Create(); diag.Show(); diag.SetCanceledOnTouchOutside(false); }); } return(root); }
void ListView_OnItemLongClick (object sender, AdapterView.ItemLongClickEventArgs e) { LocalBox clickedItem = foundLocalBoxes [e.Position]; LayoutInflater inflater = (LayoutInflater)Activity.GetSystemService (Context.LayoutInflaterService); View popupView; popupView = inflater.Inflate (Resource.Layout.custom_popup_root, null); PopupWindow popupWindow = new PopupWindow (popupView, e.View.Width, e.View.Height); //Hide popup window when clicking outside its view popupWindow.Focusable = true; popupWindow.Update (); popupWindow.SetBackgroundDrawable(new BitmapDrawable()); popupWindow.ShowAsDropDown (e.View, 0, - e.View.Height); ImageButton buttonDelete = (ImageButton) popupView.FindViewById(Resource.Id.button_popup_root_delete); buttonDelete.Click += delegate { popupWindow.Dismiss(); var alertDialogConfirmDelete = new Android.App.AlertDialog.Builder (Activity); alertDialogConfirmDelete.SetTitle("Waarschuwing"); alertDialogConfirmDelete.SetMessage("Weet u zeker dat u deze Pleiobox wilt verwijderen? \nDeze actie is niet terug te draaien."); alertDialogConfirmDelete.SetPositiveButton ("Verwijderen", async delegate { try{ DataLayer.Instance.DeleteLocalBox(clickedItem.Id); ResetUIToBeginState(true); UpdateLocalBoxes(); List<LocalBox> registeredLocalBoxes = await DataLayer.Instance.GetLocalBoxes (); if (registeredLocalBoxes.Count == 0) { HomeActivity homeActivity = (HomeActivity)Activity; homeActivity.ShowLoginDialog(); } //Reset logo //imageViewLogo.SetImageResource (Resource.Drawable.beeldmerk_belastingdienst); }catch (Exception ex){ Insights.Report(ex); Toast.MakeText (Android.App.Application.Context, "Het verwijderen van de Pleiobox is mislukt", ToastLength.Short).Show (); } }); alertDialogConfirmDelete.SetNegativeButton ("Annuleren", delegate { alertDialogConfirmDelete.Dispose(); }); alertDialogConfirmDelete.Create ().Show (); }; }
private async void clickBtnLogIn(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(username.Text) || string.IsNullOrEmpty(username.Text)) { Snackbar bar = Snackbar.Make(parentLayout, "Fill username", Snackbar.LengthLong); bar.SetText(Html.FromHtml("<font color=\"#000000\">Fill username</font>")); Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout)bar.View; layout.SetMinimumHeight(100); layout.SetBackgroundColor(Android.Graphics.Color.White); layout.TextAlignment = TextAlignment.Center; layout.ScrollBarSize = 16; bar.SetActionTextColor(Android.Content.Res.ColorStateList.ValueOf(Android.Graphics.Color.Red)); bar.SetDuration(Snackbar.LengthLong); bar.SetAction("Ok", (v) => { }); bar.Show(); } else if (string.IsNullOrWhiteSpace(password.Text) || string.IsNullOrEmpty(password.Text)) { Snackbar bar = Snackbar.Make(parentLayout, Html.FromHtml("<font color=\"#000000\">Fill password</font>"), Snackbar.LengthLong); Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout)bar.View; layout.SetMinimumHeight(100); layout.SetBackgroundColor(Android.Graphics.Color.White); layout.TextAlignment = TextAlignment.Center; layout.ScrollBarSize = 16; bar.SetActionTextColor(Android.Content.Res.ColorStateList.ValueOf(Android.Graphics.Color.Red)); bar.SetDuration(Snackbar.LengthLong); bar.SetAction("Ok", (v) => { }); bar.Show(); } else { var progressDialog = new ProgressDialog(this); try { progressDialog.SetIcon(2130968582); progressDialog.SetCancelable(true); progressDialog.SetMessage("Please wait!"); progressDialog.SetProgressStyle(ProgressDialogStyle.Spinner); progressDialog.Show(); var client = new HttpClient(); var keyValueLogIn = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("username", username.Text), new KeyValuePair <string, string>("password", password.Text), new KeyValuePair <string, string>("grant_type", "password") }; var request = new HttpRequestMessage(HttpMethod.Post, "UrlApiToken"); request.Content = new FormUrlEncodedContent(keyValueLogIn); var response = await client.SendAsync(request); var content = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { TokenModel tokenFromServer = JsonConvert.DeserializeObject <TokenModel>(content); var jsonContent = JsonConvert.SerializeObject(username.Text); var LogIncontent = new StringContent(jsonContent, Encoding.ASCII, "application/json"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenFromServer.access_token); response = await client.PostAsync("UrlApi" + "api/Account/userdata", LogIncontent); var userData = await response.Content.ReadAsStringAsync(); User user = JsonConvert.DeserializeObject <User>(userData); var userSession = new UserSession { FirstName = user.FirstName, LastName = user.LastName, userId = user.userId, Token = tokenFromServer.access_token, user_image = user.user_image }; con.Insert(userSession); progressDialog.Cancel(); StartActivity(typeof(MainActivity)); } else { LogInError logInError = JsonConvert.DeserializeObject <LogInError>(content); var alertLogInError = new Android.App.AlertDialog.Builder(this); alertLogInError.SetTitle(logInError.error); alertLogInError.SetMessage(logInError.error_description); username.Text = ""; password.Text = ""; Snackbar bar = Snackbar.Make(parentLayout, Html.FromHtml("<font color=\"#000000\">" + logInError.error + " - " + logInError.error_description + "</font>"), Snackbar.LengthLong); Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout)bar.View; layout.SetMinimumHeight(100); layout.SetBackgroundColor(Android.Graphics.Color.White); layout.TextAlignment = TextAlignment.Center; layout.ScrollBarSize = 16; bar.SetActionTextColor(Android.Content.Res.ColorStateList.ValueOf(Android.Graphics.Color.Red)); bar.SetDuration(Snackbar.LengthLong); bar.SetAction("Ok", (v) => { }); bar.Show(); progressDialog.Cancel(); } } catch (HttpRequestException httpEx) { Snackbar bar = Snackbar.Make(parentLayout, Html.FromHtml("<font color=\"#000000\">Please check your internet connection!</font>"), Snackbar.LengthLong); Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout)bar.View; layout.SetMinimumHeight(100); layout.SetBackgroundColor(Android.Graphics.Color.White); layout.TextAlignment = TextAlignment.Center; layout.ScrollBarSize = 16; bar.SetActionTextColor(Android.Content.Res.ColorStateList.ValueOf(Android.Graphics.Color.Red)); bar.SetDuration(Snackbar.LengthIndefinite); bar.SetAction("Ok", (v) => { }); bar.Show(); progressDialog.Cancel(); } catch (Exception ex) { Snackbar bar = Snackbar.Make(parentLayout, Html.FromHtml("<font color=\"#000000\">Error: " + ex + "</font>"), Snackbar.LengthLong); Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout)bar.View; layout.SetMinimumHeight(100); layout.SetBackgroundColor(Android.Graphics.Color.White); layout.TextAlignment = TextAlignment.Center; layout.ScrollBarSize = 16; bar.SetActionTextColor(Android.Content.Res.ColorStateList.ValueOf(Android.Graphics.Color.Red)); bar.SetDuration(Snackbar.LengthIndefinite); bar.SetAction("Ok", (v) => { }); bar.Show(); progressDialog.Cancel(); } } }
//closeActivity is for finish() activity public static void dialogErrorInternet(Activity context,int errorType,int close){ context.RunOnUiThread (() => { string errorMsg = ""; if(errorType == errorInternet){ errorMsg = "Ralat. Sila semak sambungan internet anda."; }else if(errorType == errorServer){ errorMsg = "Ralat. Server Pi1M dalam proses penyelenggaraan ."; } Android.App.AlertDialog alertDialog; Android.App.AlertDialog.Builder alertDialogBuilder = new Android.App.AlertDialog.Builder (context); alertDialogBuilder .SetTitle ("Masalah") .SetMessage (string.Format (errorMsg)) .SetCancelable (false) .SetPositiveButton ("OK", delegate { if(close==closeActivity){ context.Finish (); } }); alertDialog = alertDialogBuilder.Create (); alertDialog.Show (); }); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.purchase_activity); spinner_purchase1 = FindViewById <Spinner>(Resource.Id.spinner_pur1); spinner_purchase2 = FindViewById <Spinner>(Resource.Id.spinner_pur2); logo_pur = FindViewById <ImageView>(Resource.Id.image_logo_pur); purchase_button = FindViewById <Button>(Resource.Id.purchase_btn); listView1 = FindViewById <ListView>(Resource.Id.listView1); date = FindViewById <EditText>(Resource.Id.edt_txt_date); alert = new Android.App.AlertDialog.Builder(this); myDB = new DBHelper(this); ic = myDB.PurchaseID(); ic.MoveToFirst(); pur_id = ic.GetInt(ic.GetColumnIndexOrThrow("max_id")) + 1; ic = myDB.vendor_list(); int j = 1; while (ic.MoveToNext()) { var a = ic.GetString(ic.GetColumnIndex("v_company_name")); var b = ic.GetInt(ic.GetColumnIndex("vendor_id")); vendor_dict.Add(a, b); vendor.Add(a); j++; } ic = myDB.category_list(); myUnit1.Add("All Categories"); int k = 0; while (ic.MoveToNext()) { var a = ic.GetString(ic.GetColumnIndex("cat_name")); var b = ic.GetInt(ic.GetColumnIndex("cat_id")); myUnit1.Add(a); category_dict.Add(a, b); k++; } purchase_button.Click += delegate { myDB.insertPurchase(pur_id, ven_id, date.Text, total_amt); }; listView1.ItemClick += listView_ItemClick1; date.Text = System.DateTime.Now.ToShortDateString(); //myDB = new DBHelper(this); showProductList(); spinner_purchase1.Adapter = new ArrayAdapter (this, Android.Resource.Layout.SimpleListItem1, vendor); spinner_purchase1.ItemSelected += MyItemSelectedMethod2; spinner_purchase2.Adapter = new ArrayAdapter (this, Android.Resource.Layout.SimpleListItem1, myUnit1); spinner_purchase2.ItemSelected += MyItemSelectedMethod3; sv = FindViewById <Android.Widget.SearchView>(Resource.Id.searchID_pro); sv.QueryTextChange += Sv_QueryTextChange; }
public void btnCloseA_OnClick(object sender, EventArgs EventArgs) { var builder = new Android.App.AlertDialog.Builder(this); builder.SetTitle ("Exit."); builder.SetIcon (Android.Resource.Drawable.IcDialogAlert); builder.SetMessage("Exit App?"); builder.SetPositiveButton("OK", (s, e) => { Finish(); Android.OS.Process.KillProcess(Android.OS.Process.MyPid()); //System.Environment.Exit(0); }); builder.SetNegativeButton("Cancel", (s, e) => { }); builder.Create().Show(); }
// async void example(){ // ParseObject gameScore = new ParseObject("GameScore"); // gameScore["score"] = 1337; // gameScore["playerName"] = "Sean Plott"; // await gameScore.SaveAsync(); // } protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // ParseClient.Initialize("LNAuxom26NKczyL2hfU3deDyFvxkR9vAEVt3NYom", // "pTK01DCWyIlw3DQJludWbtnBgvpe2PqNFKa8aDmm"); //example (); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); string Dominio_webservice = "http://alertapp-jovel.rhcloud.com/index.php/Mobile"; WebServices = new Dictionary<string, System.Uri> { {"getDenuncias",new System.Uri(Dominio_webservice+"/getDenuncias")}, {"setDenuncia",new System.Uri(Dominio_webservice+"/setDenuncia")}, {"getDenunciaPicture",new System.Uri(Dominio_webservice+"/getDenunciaPicture")} }; //este diccionario dejo de usarse pero puede resultar util luego ColorTipoDenuncia = new Dictionary<int, float>{ {1, BitmapDescriptorFactory.HueRed}, {2, BitmapDescriptorFactory.HueAzure}, {3, BitmapDescriptorFactory.HueGreen}, {4, BitmapDescriptorFactory.HueYellow}, }; MarkerTipoDenuncia = new Dictionary<int, int>{ {1, Resource.Drawable.corte_marker}, {2, Resource.Drawable.fuga_marker}, {3, Resource.Drawable.damage_marker}, {4, Resource.Drawable.otros_marker} }; btnNormal = FindViewById<Button>(Resource.Id.btnNormal); btnSatellite = FindViewById<Button>(Resource.Id.btnSatellite); ibtnReload = FindViewById<ImageButton>(Resource.Id.ibtnReload); ibtnGps = FindViewById<ImageButton>(Resource.Id.ibtnGps); ibtnSearch = FindViewById<ImageButton>(Resource.Id.ibtnSearch); txtBuscar = FindViewById<EditText>(Resource.Id.txtBuscar); txtBuscar.ClearFocus(); btnNormal.RequestFocus(); btnNormal.Click +=btnNormal_Click; btnSatellite.Click +=btnSatellite_Click; txtBuscar.EditorAction += txtBuscar_EditorAction; ibtnReload.Click += ibtnReload_Click; ibtnGps.Click += ibtnGps_Click; ibtnSearch.Click += ibtnSearch_Click; toolBar = FindViewById<SupportToolbar>(Resource.Id.toolbar); toolBar.SetTitleTextColor(Color.White); mDrawerLayout = FindViewById<DrawerLayout>(Resource.Id.drawe_layout); mLeftDrawer = FindViewById<ListView>(Resource.Id.left_drawer); SetSupportActionBar(toolBar); mLeftDataSet = new List<string>(); mLeftDataSet.Add("Bienvenido Luis Jovel"); mLeftDataSet.Add("Listado de Denuncias"); mLeftDataSet.Add("Filtrar Resultados"); mLeftDataSet.Add(" Ver Todos"); mLeftDataSet.Add(" Corte de servicio"); mLeftDataSet.Add(" Fuga de Agua"); mLeftDataSet.Add(" Daño a Infraestructura"); mLeftDataSet.Add(" Otros"); mLeftDataSet.Add("Cerrar Sesion"); mLeftAdapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, mLeftDataSet); mLeftDrawer.ItemClick += mLeftDrawer_ItemClick; mLeftDrawer.Adapter = mLeftAdapter; mDrawerToggle = new MyActionBarDrawerToggle( this, mDrawerLayout, Resource.String.openDrawer, Resource.String.closeDrawer ); mDrawerLayout.SetDrawerListener(mDrawerToggle); SupportActionBar.SetHomeButtonEnabled(true); SupportActionBar.SetDisplayShowTitleEnabled(true); SupportActionBar.SetDisplayHomeAsUpEnabled(true); mDrawerToggle.SyncState(); //GPS NUEVO setupGPS(); SetUpMap(); //GPS OBSOLETO // InitializeLocationManager(); cliente = new WebClient(); //llamar a web service cliente.DownloadDataAsync(WebServices["getDenuncias"]); cliente.DownloadDataCompleted += cliente_DownloadDataCompleted; //alertdialog builder = new Android.App.AlertDialog.Builder(this); alert = builder.Create(); }
/// <summary> /// Begins an asynchronous operation showing a dialog. /// </summary> /// <returns>An object that represents the asynchronous operation. /// For more on the async pattern, see Asynchronous programming in the Windows Runtime.</returns> /// <remarks>In some cases, such as when the dialog is closed by the system out of your control, your result can be an empty command. /// Returns either the command selected which destroyed the dialog, or an empty command. /// For example, a dialog hosted in a charms window will return an empty command if the charms window has been dismissed.</remarks> public Task<IUICommand> ShowAsync() { if (Commands.Count > MaxCommands) { throw new InvalidOperationException(); } #if __ANDROID__ Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity); Android.App.AlertDialog dialog = builder.Create(); dialog.SetTitle(Title); dialog.SetMessage(Content); if (Commands.Count == 0) { dialog.SetButton(-1, Resources.System.GetString(Android.Resource.String.Cancel), new EventHandler<Android.Content.DialogClickEventArgs>(Clicked)); } else { for (int i = 0; i < Commands.Count; i++) { dialog.SetButton(-1 - i, Commands[i].Label, new EventHandler<Android.Content.DialogClickEventArgs>(Clicked)); } } dialog.Show(); return Task.Run<IUICommand>(() => { _handle.WaitOne(); return _selectedCommand; }); #elif __IOS__ || __TVOS__ uac = UIAlertController.Create(Title, Content, UIAlertControllerStyle.Alert); if (Commands.Count == 0) { uac.AddAction(UIAlertAction.Create("Close", UIAlertActionStyle.Cancel | UIAlertActionStyle.Default, ActionClicked)); } else { for (int i = 0; i < Commands.Count; i++) { UIAlertAction action = UIAlertAction.Create(Commands[i].Label, CancelCommandIndex == i ? UIAlertActionStyle.Cancel : UIAlertActionStyle.Default, ActionClicked); uac.AddAction(action); } } UIViewController currentController = UIApplication.SharedApplication.KeyWindow.RootViewController; while (currentController.PresentedViewController != null) currentController = currentController.PresentedViewController; currentController.PresentViewController(uac, true, null); return Task.Run<IUICommand>(() => { _handle.WaitOne(); return _selectedCommand; }); #elif __MAC__ NSAlert alert = new NSAlert(); alert.AlertStyle = NSAlertStyle.Informational; alert.InformativeText = Content; alert.MessageText = Title; foreach(IUICommand command in Commands) { var button = alert.AddButton(command.Label); } alert.BeginSheetForResponse(NSApplication.SharedApplication.MainWindow, NSAlert_onEnded); return Task.Run<IUICommand>(() => { _handle.WaitOne(); return _selectedCommand; }); #elif WINDOWS_PHONE List<string> buttons = new List<string>(); foreach(IUICommand uic in this.Commands) { buttons.Add(uic.Label); } if (buttons.Count == 0) { buttons.Add("Close"); } MessageDialogAsyncOperation asyncOperation = new MessageDialogAsyncOperation(this); string contentText = Content; // trim message body to 255 chars if (contentText.Length > 255) { contentText = contentText.Substring(0, 255); } while(Microsoft.Xna.Framework.GamerServices.Guide.IsVisible) { Thread.Sleep(250); } Microsoft.Xna.Framework.GamerServices.Guide.BeginShowMessageBox( string.IsNullOrEmpty(Title) ? " " : Title, contentText, buttons, (int)DefaultCommandIndex, // can choose which button has the focus Microsoft.Xna.Framework.GamerServices.MessageBoxIcon.None, // can play sounds result => { int? returned = Microsoft.Xna.Framework.GamerServices.Guide.EndShowMessageBox(result); // process and fire the required handler if (returned.HasValue) { if (Commands.Count > returned.Value) { IUICommand theCommand = Commands[returned.Value]; asyncOperation.SetResults(theCommand); if (theCommand.Invoked != null) { theCommand.Invoked(theCommand); } } else { asyncOperation.SetResults(null); } } else { asyncOperation.SetResults(null); } }, null); return asyncOperation.AsTask<IUICommand>(); #elif WINDOWS_UWP if (Commands.Count < 3 && Windows.Foundation.Metadata.ApiInformation.IsApiContractPresent("Windows.UI.ApplicationSettings.ApplicationsSettingsContract", 1)) { Windows.UI.Xaml.Controls.ContentDialog cd = new Windows.UI.Xaml.Controls.ContentDialog(); cd.Title = Title; cd.Content = Content; if(Commands.Count == 0) { cd.PrimaryButtonText = "Close"; } else { cd.PrimaryButtonText = Commands[0].Label; cd.PrimaryButtonClick += Cd_PrimaryButtonClick; if(Commands.Count > 1) { cd.SecondaryButtonText = Commands[1].Label; cd.SecondaryButtonClick += Cd_SecondaryButtonClick; } } return Task.Run<IUICommand>(async () => { ManualResetEvent mre = new ManualResetEvent(false); IUICommand command = null; await cd.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { ContentDialogResult dr = await cd.ShowAsync(); if (Commands.Count > 0) { switch (dr) { case ContentDialogResult.Primary: command = Commands[0]; if(Commands[0].Invoked != null) { Commands[0].Invoked.Invoke(Commands[0]); } break; case ContentDialogResult.Secondary: command = Commands[1]; if (Commands[1].Invoked != null) { Commands[1].Invoked.Invoke(Commands[1]); } break; } } }); mre.WaitOne(); return command; }); } else { Windows.UI.Popups.MessageDialog dialog = new Windows.UI.Popups.MessageDialog(Content, Title); foreach (IUICommand command in Commands) { dialog.Commands.Add(new Windows.UI.Popups.UICommand(command.Label, (c)=> { command.Invoked(command); }, command.Id)); } return Task.Run<IUICommand>(async () => { Windows.UI.Popups.IUICommand command = await dialog.ShowAsync(); if (command != null) { int i = 0; foreach(Windows.UI.Popups.IUICommand c in dialog.Commands) { if(command == c) { break; } i++; } return Commands[i]; } return null; }); } #elif WIN32 return Task.Run<IUICommand>(() => { IUICommand cmd = ShowTaskDialog(); if (cmd != null) { cmd.Invoked?.Invoke(cmd); } return cmd; }); #else throw new PlatformNotSupportedException(); #endif }
protected override async void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.list_layout); Android.App.AlertDialog.Builder alert = new Android.App.AlertDialog.Builder(this); alert.SetTitle("No internet connection"); alert.SetMessage("You need internet connection to use this app"); alert.SetNegativeButton("OK", (senderAlert, args) => { }); Dialog dialog = alert.Create(); var MainActivity = new Intent(this, typeof(MainActivity)); List <string> nameList = new List <string>(); Dictionary <string, string> valuePairs = new Dictionary <string, string>(); string option = Intent.GetSerializableExtra("ButtonName").ToString(); var current = Connectivity.NetworkAccess; switch (current) { case NetworkAccess.Unknown: dialog.Show(); StartActivity(MainActivity); break; case NetworkAccess.None: dialog.Show(); StartActivity(MainActivity); break; case NetworkAccess.Local: dialog.Show(); StartActivity(MainActivity); break; case NetworkAccess.ConstrainedInternet: dialog.Show(); StartActivity(MainActivity); break; case NetworkAccess.Internet: SharpTrooperCore core = new SharpTrooperCore(); using (UserDialogs.Instance.Loading()) { switch (option) { case ("Planets"): for (int i = 1; i < 8; i++) { SharpEntityResults <Planet> Data; Data = await core.GetAllPlanets(i.ToString()); foreach (var item in Data.results) { valuePairs.Add(item.name, item.url); } } break; case ("People"): for (int i = 1; i < 10; i++) { SharpEntityResults <People> Data; Data = await core.GetAllPeople(i.ToString()); foreach (var item in Data.results) { if (item.name == "Sly Moore") { continue; } valuePairs.Add(item.name, item.url); } } break; case ("Films"): for (int i = 1; i < 2; i++) { SharpEntityResults <Film> Data; Data = await core.GetAllFilms(i.ToString()); foreach (var item in Data.results) { valuePairs.Add(item.title, item.url); } } break; case ("Species"): for (int i = 1; i < 5; i++) { SharpEntityResults <Specie> Data; Data = await core.GetAllSpecies(i.ToString()); foreach (var item in Data.results) { valuePairs.Add(item.name, item.url); } } break; case ("StarShips"): for (int i = 1; i < 5; i++) { SharpEntityResults <Starship> Data; Data = await core.GetAllStarships(i.ToString()); foreach (var item in Data.results) { valuePairs.Add(item.name, item.url); } } break; case ("Vehicles"): for (int i = 1; i < 5; i++) { SharpEntityResults <Vehicle> Data; Data = await core.GetAllVehicles(i.ToString()); foreach (var item in Data.results) { valuePairs.Add(item.name, item.url); } } break; } break; } } foreach (KeyValuePair <string, string> kvp in valuePairs) { nameList.Add(kvp.Key); } ListView listview = FindViewById <ListView>(Resource.Id.listView_selectedOption); listview.Adapter = new CustomAdapter(this, nameList); listview.ItemClick += delegate(object sender, AdapterView.ItemClickEventArgs args) { var item = listview.Adapter.GetItem(args.Position).ToString(); var url = valuePairs[item]; int index = nameList.FindIndex(x => x == item); var ItemActivity = new Intent(this, typeof(ItemActivity)); ItemActivity.PutExtra("OptionName", option); ItemActivity.PutExtra("ItemName", item); ItemActivity.PutExtra("ItemUrl", url); StartActivity(ItemActivity); }; }
//The top up method that will validate the user payment public async void onTopUpClick(int amount) { //Creating indicator object var topUpDialog = ProgressDialog.Show(this, "Please wait...", "Validating your payment...", true); try { var amountText = FindViewById <EditText>(Resource.Id.input_amount); // Use Stripe's library to make request StripeConfiguration.SetApiKey("sk_test_Ep5V2ffFq69TP6cDSEf71fr2"); var chargeOptions = new StripeChargeCreateOptions() { Amount = amount, Currency = "usd", Description = "Top Up", SourceTokenOrExistingSourceId = "tok_amex" // obtained with Stripe.js }; //Creating charge service object that will validate the banking card var chargeService = new StripeChargeService(); StripeCharge charge = chargeService.Create(chargeOptions); if (charge.Paid) { //Initializing the user table IMobileServiceTable <Wallet> walletTable = client.GetTable <Wallet>(); //Getting the Wallet details from the Database List <Wallet> currentBalance = await walletTable.Where (item => item.Email == client.CurrentUser.UserId).ToListAsync(); //Checking if the user has a wallet already if (currentBalance.Count > 0) { wallet = currentBalance[0]; //Adding the top up to the previous wallet balance wallet.Balance = Convert.ToString(Convert.ToInt32(wallet.Balance) + Convert.ToInt32(amountText.Text)); //Creating important extra parameters for the backend request var extraParameters = new Dictionary <string, string>(); extraParameters.Add("userId", user.Id); extraParameters.Add("type", "topUp"); extraParameters.Add("parkingId", "1"); //Sending update wallet request to the backend await walletTable.UpdateAsync(wallet, extraParameters); //Showing success message Android.App.AlertDialog.Builder alertSuccess = new Android.App.AlertDialog.Builder(this); alertSuccess.SetTitle("Top Up"); alertSuccess.SetMessage("Top is successful"); alertSuccess.SetPositiveButton("Ok", (senderAlertSucces, argsSuccess) => { Intent walletActivityIntent = new Intent(Application.Context, typeof(WalletActivity)); walletActivityIntent.PutExtra("User", JsonConvert.SerializeObject(user)); this.StartActivity(walletActivityIntent); Finish(); }); Dialog dialogSuccess = alertSuccess.Create(); dialogSuccess.Show(); } //If the user has no wallet, it will be created else { //Assigning wallet Email to the user and creating new balance wallet.Email = user.Email; wallet.Balance = amountText.Text; //Creating necessary extra parameters for the backend request Dictionary <string, string> extraParameters = new Dictionary <string, string>(); extraParameters.Add("Id", user.Id); extraParameters.Add("type", "topUp"); extraParameters.Add("parkingId", "1"); //Inserting new wallet to the Database await walletTable.InsertAsync(wallet, extraParameters); //Creating success message Android.App.AlertDialog.Builder alertSuccess = new Android.App.AlertDialog.Builder(this); alertSuccess.SetTitle("Top Up"); alertSuccess.SetMessage("Top is successful"); alertSuccess.SetPositiveButton("Ok", (senderAlertSucces, argsSuccess) => { Intent walletActivityIntent = new Intent(Application.Context, typeof(WalletActivity)); walletActivityIntent.PutExtra("User", JsonConvert.SerializeObject(user)); this.StartActivity(walletActivityIntent); Finish(); }); Dialog dialogSuccess = alertSuccess.Create(); dialogSuccess.Show(); } } } //All possible exceptions from Stripe service catch (StripeException e) { switch (e.StripeError.ErrorType) { case "card_error": Console.WriteLine(" Code: " + e.StripeError.Code); Console.WriteLine("Message: " + e.StripeError.Message); break; case "api_connection_error": break; case "api_error": break; case "authentication_error": break; case "invalid_request_error": break; case "rate_limit_error": break; case "validation_error": break; default: // Unknown Error Type break; } } }
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { DataBase.db = DataBase.getDataBase(); DataBase.db.createDataBase(); string folder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); Log.Info("DB_PATH", folder); long elementId; var view = inflater.Inflate(Resource.Layout.SecondFragmentLayout, container, false); lstData = view.FindViewById <ListView>(Resource.Id.listView); //Задаем текст для пустого списка var emptyView = inflater.Inflate(Resource.Layout.emptyList, container, false); lstData.EmptyView = emptyView.FindViewById <TextView>(Resource.Id.empty); var btnAdd = view.FindViewById <FloatingActionButton>(Resource.Id.btnAdd); var btnRefresh = view.FindViewById <Button>(Resource.Id.btnRefresh); var btnDeleteAll = view.FindViewById <Button>(Resource.Id.btnDeleteAll); //Загружаем данные из бд и обновляем список задач LoadData(); //Добавить новую задачу btnAdd.Click += delegate { //Создаем пустую запись в бд Resources.Model.Task task = new Resources.Model.Task() { Name = "", Date = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day), Time = new DateTime(1, 1, 1, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second), Description = "", Category = "Спорт", Priority = "0", Done = false }; var t = System.Threading.Tasks.Task.Factory.StartNew(() => { DataBase.db.insertIntoTableTask(task); }); t.Wait(); t.Dispose(); //Создаем окно для добавления новой задачи Android.Support.V4.App.FragmentTransaction ft = FragmentManager.BeginTransaction(); Android.Support.V4.App.Fragment prev = FragmentManager.FindFragmentByTag("dialog"); //Передаем id новой заметки для корректной записи в бд Bundle frag_bundle = new Bundle(); frag_bundle.PutLong("Id", task.Id); if (prev != null) { ft.Remove(prev); } ft.AddToBackStack(null); _activity._taskWindow = DialogWindow.NewInstance(frag_bundle); var act = _activity._taskWindow.Activity; //Показываем окно _activity._taskWindow.SetActivity(_activity); _activity._taskWindow.Show(ft, "dialog"); }; btnRefresh.Click += delegate { LoadData(); }; // Эта кнопка удаляет все выполненные задачи btnDeleteAll.Click += delegate { Android.App.AlertDialog.Builder delDoneDialog = new Android.App.AlertDialog.Builder(_activity); delDoneDialog.SetTitle("Удалить все выполненные задачи"); delDoneDialog.SetMessage("Вы уверены?"); delDoneDialog.SetPositiveButton("Да", (senderAlert, args) => { DataBase.db.delAllDoneTask(); _activity._fragment2.LoadData(); }); delDoneDialog.SetNegativeButton("Нет", (senderAlert, args) => { return; }); Dialog dialog = delDoneDialog.Create(); dialog.Show(); //delDoneWindow.Show; }; //Просмотр/ редактирование существующей задачи lstData.ItemClick += (s, e) => { for (int i = 0; i < lstData.Count; i++) { if (e.Position == i) { //Получаем id выбранного в списке элемента var t = System.Threading.Tasks.Task.Factory.StartNew(() => { elementId = DataBase.db.selectQuery(lstData.Adapter.GetItemId(e.Position)); return(elementId); }); t.Wait(); Android.Support.V4.App.FragmentTransaction ft = FragmentManager.BeginTransaction(); //Remove fragment else it will crash as it is already added to backstack Android.Support.V4.App.Fragment prev = FragmentManager.FindFragmentByTag("dialog"); Bundle frag_bundle = new Bundle(); frag_bundle.PutLong("Id", t.Result); t.Dispose(); if (prev != null) { ft.Remove(prev); } ft.AddToBackStack(null); _activity._taskWindow = DialogWindow.NewInstance(frag_bundle); _activity._taskWindow.SetActivity(_activity); _activity._taskWindow.Show(ft, "dialog"); } } //Заполняем поля данными var txtName = e.View.FindViewById <TextView>(Resource.Id.textView1); var checkedBox = e.View.FindViewById <CheckBox>(Resource.Id.chkBox); //var txtDone = e.View.FindViewById<TextView>(Resource.Id.textView5); checkedBox.SetOnCheckedChangeListener(null); }; //Удержание на элементе lstData.ItemLongClick += (s, e) => { if (DataBase.db.getSettings()[0].fastDel == true || DataBase.db.getSettings()[0].fastDel == null) { Android.App.AlertDialog.Builder delDialog = new Android.App.AlertDialog.Builder(_activity); delDialog.SetTitle("Удалить задачу"); delDialog.SetMessage("Вы уверены?"); delDialog.SetPositiveButton("Да", (senderAlert, args) => { for (int i = 0; i < lstData.Count; i++) { if (e.Position == i) { var selected_Element = DataBase.db.get_Element(lstData.Adapter.GetItemId(e.Position))[0]; DataBase.db.delTask(selected_Element.Id); _activity._fragment2.LoadData(); Toast.MakeText(_activity, "Задача удалена", ToastLength.Long).Show(); } } }); delDialog.SetNegativeButton("Нет", (senderAlert, args) => { return; }); Dialog dialog = delDialog.Create(); dialog.Show(); } }; return(view); }
/// <summary> /// Shows the context menu in the preferred placement relative to the specified selection. /// </summary> /// <param name="selection">The coordinates (in DIPs) of the selected rectangle, relative to the window.</param> /// <param name="preferredPlacement">The preferred placement of the context menu relative to the selection rectangle.</param> /// <returns></returns> public Task<IUICommand> ShowForSelectionAsync(Rect selection, Placement preferredPlacement) { if (Commands.Count > MaxCommands) { throw new InvalidOperationException(); } #if WINDOWS_UWP return Task.Run<IUICommand>(async () => { foreach (IUICommand command in Commands) { _menu.Commands.Add(new Windows.UI.Popups.UICommand(command.Label, new Windows.UI.Popups.UICommandInvokedHandler((c2) => { command.Invoked?.Invoke(command); }), command.Id)); } Windows.Foundation.Rect r = new Windows.Foundation.Rect(selection.X, selection.Y, selection.Width, selection.Height); var c = await _menu.ShowForSelectionAsync(r, (Windows.UI.Popups.Placement)((int)preferredPlacement)); return c == null ? null : new UICommand(c.Label, new UICommandInvokedHandler((c2) => { c2.Invoked?.Invoke(c2); }), c.Id); }); #elif __ANDROID__ Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity); Android.App.AlertDialog dialog = builder.Create(); dialog.SetTitle(Title); dialog.SetMessage(Content); if (Commands.Count == 0) { dialog.SetButton(-1, Resources.System.GetString(Android.Resource.String.Cancel), new EventHandler<Android.Content.DialogClickEventArgs>(Clicked)); } else { for (int i = 0; i < Commands.Count; i++) { dialog.SetButton(-1 - i, Commands[i].Label, new EventHandler<Android.Content.DialogClickEventArgs>(Clicked)); } } dialog.Show(); return Task.Run<IUICommand>(() => { handle.WaitOne(); return _selectedCommand; }); #elif __IOS__ uac = UIAlertController.Create("", "", UIAlertControllerStyle.ActionSheet); if (Commands.Count == 0) { uac.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel | UIAlertActionStyle.Default, ActionClicked)); } else { for (int i = 0; i < Commands.Count; i++) { UIAlertAction action = UIAlertAction.Create(Commands[i].Label, UIAlertActionStyle.Default, ActionClicked); uac.AddAction(action); } } UIViewController currentController = UIApplication.SharedApplication.KeyWindow.RootViewController; while (currentController.PresentedViewController != null) currentController = currentController.PresentedViewController; // set layout requirements for iPad var popoverController = uac.PopoverPresentationController; if(popoverController != null) { popoverController.SourceView = currentController.View; popoverController.SourceRect = new CoreGraphics.CGRect(selection.X, selection.Y, selection.Width, selection.Height); popoverController.PermittedArrowDirections = PlacementHelper.ToArrowDirection(preferredPlacement); } currentController.PresentViewController(uac, true, null); return Task.Run<IUICommand>(() => { handle.WaitOne(); return _selectedCommand; }); #else throw new PlatformNotSupportedException(); #endif }
public override View GetGroupView(int groupPosition, bool isExpanded, View convertView, ViewGroup parent) { MyTaskDBModel model = MatchItems[groupPosition]; View view = convertView; Holder holder = null; //if (convertView == null) // { if (bitopiApplication.MyTaskType == MyTaskType.UNSEEN) { view = LayoutInflater.From(_context).Inflate(Resource.Layout.MyTaskUnSeenRow, parent, false); } if (bitopiApplication.MyTaskType == MyTaskType.SEEN) { view = LayoutInflater.From(_context).Inflate(Resource.Layout.MyTaskSeenRow, parent, false); } if (bitopiApplication.MyTaskType == MyTaskType.COMPLETED) { view = LayoutInflater.From(_context).Inflate(Resource.Layout.MyTaskCompletedRow, parent, false); } // visiblePosArray[position%visiblePosArray.length]=position; if (bitopiApplication.MyTaskType == MyTaskType.UNSEEN) { holder = new Holder(); } else { holder = new Holder2(); } if (holder is Holder2) { ((Holder2)holder).remarks = view.FindViewById <TextView>(Resource.Id.etRemarks); ((Holder2)holder).commitedDate = view.FindViewById <TextView>(Resource.Id.etCommitedDate); } else { holder.remarks = view.FindViewById <EditText>(Resource.Id.etRemarks); holder.commitedDate = view.FindViewById <EditText>(Resource.Id.etCommitedDate); } if (bitopiApplication.MyTaskType == MyTaskType.UNSEEN || bitopiApplication.MyTaskType == MyTaskType.SEEN) { holder.ckbox = view.FindViewById <CheckBox>(Resource.Id.chckApprove); } //} //else //{ // holder = convertView.Tag as Holder; // if (!(holder is Holder2)) // { // holder.ckbox.SetOnClickListener(null); // holder.ckbox.Checked = false; // holder.commitedDate.Click += null; // holder.remarks.KeyPress += null; // } //} if (model.IsDisabled) { holder.ckbox.Enabled = false; if (bitopiApplication.MyTaskType == MyTaskType.UNSEEN) { holder.commitedDate.Enabled = holder.remarks.Enabled = false; } } if (bitopiApplication.MyTaskType == MyTaskType.UNSEEN || bitopiApplication.MyTaskType == MyTaskType.SEEN) { holder.ckbox.Click += (sender, e) => { var builder = new Android.App.AlertDialog.Builder(_context); builder.SetMessage("Are you sure to seen this task?"); if (bitopiApplication.MyTaskType == MyTaskType.UNSEEN) { model.Remarks = holder.remarks.Text;//etUserName.SetBackgroundResource(Resource.Drawable.rounded_textview_error); if (holder.commitedDate.Text == "") { holder.commitedDate.SetBackgroundResource(Resource.Drawable.rounded_textview_error); ((CheckBox)sender).Checked = false; return; } else { holder.commitedDate.SetBackgroundResource(Resource.Drawable.rounded_textview); } } builder.SetPositiveButton("OK", (s, ev) => { CheckBox senderCheckBox = ((CheckBox)sender); View parentView = (View)senderCheckBox.Parent; Holder holder1 = parentView.Tag as Holder; ; var progressDialog = ProgressDialog.Show(_context, null, "Please wait...", true); new Thread(new ThreadStart(() => { TNARepository repo = new TNARepository(); int result = 0; if (bitopiApplication.MyTaskType == MyTaskType.UNSEEN) { result = repo.SetTaskUnSeentoSeen(_MyTaskList[holder.GroupPostiion], bitopiApplication.User.UserCode).Result; } if (bitopiApplication.MyTaskType == MyTaskType.SEEN) { result = repo.SetTaskSeenToComplete(_MyTaskList[holder.GroupPostiion], bitopiApplication.User.UserCode).Result; } if (result == 1) { _MyTaskList[holder1.GroupPostiion].IsDisabled = true; } _context.RunOnUiThread(() => { if (result == 1) { //ListViewAnimationHelper helper = new ListViewAnimationHelper(adapter, lvMyTask, MatchItems); //helper.animateRemoval(lvMyTask, parentView); int position = lvMyTask.GetPositionForView(parentView); MatchItems.RemoveAt(position); NotifyDataSetChanged(); if (MatchItems.Count == 0 && calback != null) { calback(); } progressDialog.Dismiss(); Toast.MakeText(_context, "Has been seen", ToastLength.Short).Show(); } else { ((CheckBox)sender).Checked = false; Toast.MakeText(_context, "Data Save Failed. Please Try Later", ToastLength.Short).Show(); } }); })).Start(); }); builder.SetNegativeButton("CANCEL", (s, ev) => { ((CheckBox)sender).Checked = false; }); builder.Create().Show(); }; } if (holder is Holder2) { ((Holder2)holder).remarks.Text = model.Remarks; ((Holder2)holder).commitedDate.Text = model.CommittedDate; } else { (holder).remarks.Text = model.Remarks; holder.commitedDate.Text = model.PlannedDate; } (view.FindViewById <TextView>(Resource.Id.tvTask)).Text = model.Task; (view.FindViewById <TextView>(Resource.Id.tvShimpentDate)).Text = model.ShipmentDate; if (bitopiApplication.MyTaskType == MyTaskType.UNSEEN) { holder.commitedDate.Click += (s, e) => { DateTime SetDate; if (holder.commitedDate.Text == "") { SetDate = DateTime.Today; //model.ActualDate= holder.commitedDate.Text = SetDate.Date.ToString("dd/MM/yyyy"); } else { //DateTime.TryParseExact(holder.commitedDate.Text, "dd/MM/yyyy", new CultureInfo("en-US"), //DateTimeStyles.None, //out SetDate); SetDate = Convert.ToDateTime(holder.commitedDate.Text); } DatePickerDialog dialog = new DatePickerDialog(_context, (sender, evnt) => { model.PlannedDate = model.CommittedDate = holder.commitedDate.Text = evnt.Date.ToString("dd/MM/yyyy"); holder.commitedDate.SetBackgroundResource(Resource.Drawable.rounded_textview); }, SetDate.Year, SetDate.Month - 1, SetDate.Day); dialog.DatePicker.MinDate = SetDate.Millisecond; dialog.Show(); }; holder.remarks.TextChanged += (s, e) => { model.Remarks = holder.remarks.Text; }; if (currentlyFocusedRow == groupPosition) { holder.remarks.RequestFocus(); } (view.FindViewById <EditText>(Resource.Id.etCommitedDate)).FocusableInTouchMode = false; //(view.FindViewById<EditText>(Resource.Id.etRemarks)).FocusableInTouchMode = true; holder.remarks.OnFocusChangeListener = new CustomOnFocusChangeListener(this, groupPosition, lvMyTask); } //(view.FindViewById<EditText>(Resource.Id.etCommitedDate)).Click += (s, e) => //{ // sender = s; // _context.ShowDialog(); //}; //view.Tag = groupPosition; holder.GroupPostiion = groupPosition; view.Tag = holder; return(view); }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.Main); //sets the content view to the layout Button btnPlay = FindViewById <Button>(Resource.Id.btnPlay); //connects the elements from the layout Button btnScores = FindViewById <Button>(Resource.Id.BtnScores); Button btnExit = FindViewById <Button>(Resource.Id.btnExit); var db = new SQLiteConnection(dbPath2); //opens a connection to SQLLite db.CreateTable <WordsListDatabase>(); // creates my table with empty fields var table = db.Table <WordsListDatabase>(); //connects to the table in the database if (table.Count() != 0) //do nothing if table already has words init { Toast.MakeText(this, "WORDS DATABASE EXISTS", ToastLength.Short).Show(); //toast message to check if database exists. } else if (table.Count() == 0) //add the records if the table is empty { Toast.MakeText(this, "WORDS DATABASE CREATED", ToastLength.Long).Show(); //toast message when table gets created WordsListDatabase word0 = new WordsListDatabase("FERMENT"); //creates an emtry in the table WordsListDatabase word1 = new WordsListDatabase("DISTINCTIVE"); WordsListDatabase word2 = new WordsListDatabase("POTATOES"); WordsListDatabase word3 = new WordsListDatabase("SMOKY"); WordsListDatabase word4 = new WordsListDatabase("FRUITY"); WordsListDatabase word5 = new WordsListDatabase("GRAVY"); WordsListDatabase word6 = new WordsListDatabase("MATURED"); WordsListDatabase word7 = new WordsListDatabase("SWEET"); WordsListDatabase word8 = new WordsListDatabase("SAUSAGE"); WordsListDatabase word9 = new WordsListDatabase("NUTRITIOUS"); WordsListDatabase word10 = new WordsListDatabase("CABBAGE"); WordsListDatabase word11 = new WordsListDatabase("AEDJVLDS"); WordsListDatabase word12 = new WordsListDatabase("JOKES"); WordsListDatabase word13 = new WordsListDatabase("REPUTATION"); WordsListDatabase word14 = new WordsListDatabase("SERVED"); WordsListDatabase word15 = new WordsListDatabase("POISON"); WordsListDatabase word16 = new WordsListDatabase("WHISKEY"); WordsListDatabase word17 = new WordsListDatabase("RAW"); WordsListDatabase word18 = new WordsListDatabase("POISON"); WordsListDatabase word19 = new WordsListDatabase("CRUST"); WordsListDatabase word20 = new WordsListDatabase("TRUST"); WordsListDatabase word21 = new WordsListDatabase("CULINARY"); WordsListDatabase word22 = new WordsListDatabase("FRIED"); WordsListDatabase word23 = new WordsListDatabase("CHEESE"); WordsListDatabase word24 = new WordsListDatabase("MIXED"); db.Insert(word0); db.Insert(word1); db.Insert(word2); db.Insert(word3); db.Insert(word4); //inserts the emtry into the table db.Insert(word5); db.Insert(word6); db.Insert(word7); db.Insert(word8); db.Insert(word9); db.Insert(word10); db.Insert(word11); db.Insert(word12); db.Insert(word13); db.Insert(word14); db.Insert(word15); db.Insert(word16); db.Insert(word17); db.Insert(word18); db.Insert(word19); db.Insert(word20); db.Insert(word21); db.Insert(word22); db.Insert(word23); db.Insert(word24); } btnPlay.Click += delegate { StartActivity(typeof(PlayerActivity)); var db2 = new SQLiteConnection(dbPath); //connection for the sqllite database db2.CreateTable <PlayerDatabase>(); //creates table from the class file }; btnScores.Click += delegate { StartActivity(typeof(ScoresActivity)); //starts defined activity var db2 = new SQLiteConnection(dbPath); //connection for the sqllite database db2.CreateTable <PlayerDatabase>(); //creates table from the class file }; btnExit.Click += delegate { Android.App.AlertDialog.Builder dialog = new Android.App.AlertDialog.Builder(this, Android.App.AlertDialog.ThemeHoloDark); Android.App.AlertDialog alert = dialog.Create(); alert.SetCancelable(false); alert.SetTitle("EXIT GAME"); alert.SetMessage("Are You Sure?"); alert.SetButton("YES", (c, ev) => { Process.KillProcess(Process.MyPid()); }); alert.SetButton2("NO", (c, ev) => { alert.Cancel(); }); alert.Show(); }; }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.activity_container_condition); condition = FindViewById <RelativeLayout>(Resource.Id.condition); s_open_close_container = FindViewById <EditText>(Resource.Id.s_open_close_container); s_lock_unlock_door = FindViewById <EditText>(Resource.Id.s_lock_unlock_door); btn_open_close_container = FindViewById <Button>(Resource.Id.btn_open_close_container); btn_lock_unlock_door = FindViewById <Button>(Resource.Id.btn_lock_unlock_door); btn_save_status_container = FindViewById <Button>(Resource.Id.btn_save_parameters); box_lay_fold = FindViewById <ImageView>(Resource.Id.box_lay_fold); s_situation_container = FindViewById <Spinner>(Resource.Id.s_situation); s_open_close_container.Focusable = false; s_open_close_container.LongClickable = false; s_lock_unlock_door.Focusable = false; s_lock_unlock_door.LongClickable = false; GetInfoAboutBox(); s_situation_container.ItemSelected += new EventHandler <AdapterView.ItemSelectedEventArgs>(Spinner_ItemSelected); var adapter = ArrayAdapter.CreateFromResource(this, Resource.Array.a_situation_loaded_container, Android.Resource.Layout.SimpleSpinnerItem); adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); s_situation_container.Adapter = adapter; btn_save_status_container.Click += async delegate { try { StaticBox.Sensors["Состояние контейнера"] = (s_open_close_container.Text == "сложен")?"0":"1"; StaticBox.Sensors["Состояние дверей"] = (s_lock_unlock_door.Text == "закрыта")?"0":"1"; StaticBox.Sensors["Местоположение контейнера"] = a_situation; var o_data = await ContainerService.EditBox(); if (o_data.Status == "1") { Toast.MakeText(this, o_data.Message, ToastLength.Long).Show(); GetInfoAboutBox(); } else { GetInfoAboutBox(); StaticBox.CameraOpenOrNo = 1; Intent authActivity = new Intent(this, typeof(Auth.SensorsDataActivity)); StartActivity(authActivity); } } catch (Exception ex) { Toast.MakeText(this, "" + ex.Message, ToastLength.Long).Show(); } }; //изменение состояния контейнера btn_open_close_container.Click += async delegate { try { if (s_open_close_container.Text == "сложен") { s_open_close_container.Text = "разложен"; s_lock_unlock_door.Text = "открыта"; box_lay_fold.SetImageResource(Resource.Drawable.open_door); } else { s_open_close_container.Text = "сложен"; s_lock_unlock_door.Text = "открыта"; box_lay_fold.SetImageResource(Resource.Drawable.close_box); } } catch (Exception ex) { Toast.MakeText(this, "" + ex.Message, ToastLength.Long).Show(); } }; //изменение состояния дверей btn_lock_unlock_door.Click += async delegate { try { if (s_lock_unlock_door.Text == "закрыта") { s_lock_unlock_door.Text = "открыта"; box_lay_fold.SetImageResource(Resource.Drawable.open_door); } else if (s_lock_unlock_door.Text == "открыта" && s_open_close_container.Text == "разложен") { s_lock_unlock_door.Text = "закрыта"; box_lay_fold.SetImageResource(Resource.Drawable.close_door); } else if (s_open_close_container.Text == "сложен" && s_lock_unlock_door.Text == "открыта") { Android.App.AlertDialog.Builder alert = new Android.App.AlertDialog.Builder(this); alert.SetTitle("Внимание !"); alert.SetMessage("Невозможно изменить состояние дверей."); alert.SetPositiveButton("Закрыть", (senderAlert, args) => { Toast.MakeText(this, "Предупреждение было закрыто!", ToastLength.Short).Show(); }); Dialog dialog = alert.Create(); dialog.Show(); } else if (s_open_close_container.Text == null && s_lock_unlock_door.Text == null) { Android.App.AlertDialog.Builder alert = new Android.App.AlertDialog.Builder(this); alert.SetTitle("Внимание !"); alert.SetMessage("Невозможно изменить состояние дверей и контейнера."); alert.SetPositiveButton("Закрыть", (senderAlert, args) => { Toast.MakeText(this, "Предупреждение было закрыто!", ToastLength.Short).Show(); }); Dialog dialog = alert.Create(); dialog.Show(); } else { Android.App.AlertDialog.Builder alert = new Android.App.AlertDialog.Builder(this); alert.SetTitle("Внимание !"); alert.SetMessage("Невозможно изменить состояние дверей."); alert.SetPositiveButton("Закрыть", (senderAlert, args) => { Toast.MakeText(this, "Предупреждение было закрыто!", ToastLength.Short).Show(); }); Dialog dialog = alert.Create(); dialog.Show(); } } catch (Exception ex) { Toast.MakeText(this, "" + ex.Message, ToastLength.Long).Show(); } }; }
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.Inflate(Resource.Layout.fragment_crime, container, false); if (Build.VERSION.SdkInt >= BuildVersionCodes.Honeycomb) { // Using ParentActivity and NavUtils causes OnCreate to be called again // in CrimeListFragment, causing the subtitle view to be reset // if (NavUtils.GetParentActivityName(Activity) != null) { Activity.ActionBar.SetDisplayHomeAsUpEnabled(true); // } } mTitleField = (EditText)v.FindViewById(Resource.Id.crime_title_edittext); mTitleField.SetText(mCrime.Title, TextView.BufferType.Normal); mTitleField.BeforeTextChanged += (object sender, Android.Text.TextChangedEventArgs e) => { // nothing for now }; mTitleField.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) => { mCrime.Title = e.Text.ToString(); mCallBacks.OnCrimeUpdated(); }; mTitleField.AfterTextChanged += (object sender, Android.Text.AfterTextChangedEventArgs e) => { // nothing for now }; // One DateTime Button mDateButton = (Button)v.FindViewById(Resource.Id.crime_date_button); mDateButton.Click += (sender, e) => { Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(Activity); builder.SetTitle(Resource.String.date_or_time_alert_title); builder.SetPositiveButton(Resource.String.date_or_time_alert_date, (object date, DialogClickEventArgs de) => { Android.Support.V4.App.FragmentManager fm = Activity.SupportFragmentManager; DatePickerFragment dialog = DatePickerFragment.NewInstance(mCrime.Date); dialog.SetTargetFragment(this, REQUEST_DATE); dialog.Show(fm, CrimeFragment.DIALOG_DATE); }); builder.SetNegativeButton(Resource.String.date_or_time_alert_time, (object time, DialogClickEventArgs de) => { Android.Support.V4.App.FragmentManager fm = Activity.SupportFragmentManager; TimePickerFragment dialog = TimePickerFragment.NewInstance(mCrime.Date); dialog.SetTargetFragment(this, REQUEST_TIME); dialog.Show(fm, CrimeFragment.DIALOG_TIME); }); builder.Show(); }; // Separate date and time buttons // mDateButton = (Button)v.FindViewById(Resource.Id.crime_date_button); // mDateButton.Click += (sender, e) => { // FragmentManager fm = Activity.SupportFragmentManager; // DatePickerFragment dialog = DatePickerFragment.NewInstance(mCrime.Date); // dialog.SetTargetFragment(this, REQUEST_DATE); // dialog.Show(fm, CrimeFragment.DIALOG_DATE); // }; // // mTimeButton = (Button)v.FindViewById(Resource.Id.crime_time_button); // mTimeButton.Click += (sender, e) => { // FragmentManager fm = Activity.SupportFragmentManager; // TimePickerFragment dialog = TimePickerFragment.NewInstance(mCrime.Date); // dialog.SetTargetFragment(this, REQUEST_TIME); // dialog.Show(fm, CrimeFragment.DIALOG_TIME); // }; UpdateDateTime(); mSolvedCheckBox = (CheckBox)v.FindViewById(Resource.Id.crime_solved_checkbox); mSolvedCheckBox.Checked = mCrime.Solved; mSolvedCheckBox.CheckedChange += (object sender, CompoundButton.CheckedChangeEventArgs e) => { mCrime.Solved = e.IsChecked; mCallBacks.OnCrimeUpdated(); }; mPhotoView = v.FindViewById<ImageView>(Resource.Id.crime_imageView); mPhotoView.Click += (object sender, EventArgs e) => { Photo p = mCrime.Photo; if (p == null) return; Android.Support.V4.App.FragmentManager fm = Activity.SupportFragmentManager; // BNR // string path = Activity.GetFileStreamPath(p.Filename).AbsolutePath; if (p.Filename != null) ImageFragment.NewInstance(p.Filename, p.GetRotation()).Show(fm, DIALOG_IMAGE); }; mPhotoView.LongClick += (object sender, View.LongClickEventArgs e) => { if (mCrime.Photo != null) { AlertDialog.Builder ad = new AlertDialog.Builder(Activity); ad.SetTitle(mCrime.Title); ad.SetMessage("Do you really want to delete the photo evidence of this crime?"); ad.SetCancelable(true); ad.SetPositiveButton("DELETE", delegate(object s, DialogClickEventArgs evt) { if (File.Exists(mCrime.Photo.Filename)) { File.Delete(mCrime.Photo.Filename); mCrime.Photo = null; mPhotoView.SetImageDrawable(null); } }); ad.SetNegativeButton("Cancel", (s, evt) => {}); ad.Show(); } }; // From Xamarin guide mPhotoButton = v.FindViewById<ImageButton>(Resource.Id.crime_imageButton); if (IsAppToTakePicture()) { CreateDirectoryForPictures(); mPhotoButton.Click += (object sender, EventArgs e) => { // From xamarin guide Intent intent = new Intent(MediaStore.ActionImageCapture); PhotoApp._file = new Java.IO.File(PhotoApp._dir, String.Format("{0}.jpg", Guid.NewGuid())); intent.PutExtra(MediaStore.ExtraOutput, Android.Net.Uri.FromFile(PhotoApp._file)); StartActivityForResult(intent, REQUEST_PHOTO); // From BNR Book - trying Xamarin method above // Intent i = new Intent(Activity, typeof(CrimeCameraActivity)); // StartActivityForResult(i, REQUEST_PHOTO); }; } else { mPhotoButton.Enabled = false; } // If camera is not available, disable button - checked in the if statement above // just shows another method // PackageManager pm = Activity.PackageManager; // if (!pm.HasSystemFeature(PackageManager.FeatureCamera) && !pm.HasSystemFeature(PackageManager.FeatureCameraFront)) { // mPhotoButton.Enabled = false; // } Button reportButton = v.FindViewById<Button>(Resource.Id.crime_reportButton); reportButton.Click += (object sender, EventArgs e) => { Intent i = new Intent(Intent.ActionSend); i.SetType("text/plain"); i.PutExtra(Intent.ExtraText, GetCrimeReport()); i.PutExtra(Intent.ExtraSubject, GetString(Resource.String.crime_report_subject)); i = Intent.CreateChooser(i, GetString(Resource.String.send_report)); StartActivity(i); }; mSuspectButton = v.FindViewById<Button>(Resource.Id.crime_suspectButton); mCallButton = v.FindViewById<Button>(Resource.Id.crime_callButton); mSuspectButton.Click += (object sender, EventArgs e) => { Intent i = new Intent(Intent.ActionPick, ContactsContract.Contacts.ContentUri); StartActivityForResult(i, REQUEST_CONTACT); }; if (mCrime.Suspect != null) { mSuspectButton.Text = GetString(Resource.String.crime_report_suspect, mCrime.Suspect); } if (mCrime.PhoneNumber != null) { mCallButton.Text = GetString(Resource.String.crime_report_call) + " " + mCrime.PhoneNumber; mCallButton.Enabled = true; } else { mCallButton.Enabled = false; } mCallButton.Click += (object sender, EventArgs e) => { Intent i = new Intent(Intent.ActionDial, Android.Net.Uri.Parse("tel:" + mCrime.PhoneNumber));//.Replace("(","").Replace(")","").Replace("-",""))); StartActivity(i); }; return v; }
//when submit button clicked //to add user into database //when user didn't put anything into the textbox and show the error message by using alert dialog private void BtnSubmit_Click(object sender, EventArgs e) { string inputemail = tbxEmail.Text.ToString(); var emailvalidate = isValidEmail(inputemail); if (tbxFirstName.Text == "" && tbxLastName.Text == "" && tbxDOB.Text == "" && tbxEmail.Text == "" && tbxPassword.Text == "") { AlertDialog.Builder alertDialog = new Android.App.AlertDialog.Builder(this); alertDialog.SetTitle("This field is required"); alertDialog.SetMessage("First name, last name, date of birth, email and password cannot be blanks!"); alertDialog.SetNeutralButton("OK", delegate { alertDialog.Dispose(); }); Dialog dialog = alertDialog.Create(); alertDialog.Show(); } else if (tbxFirstName.Text == "") { AlertDialog.Builder alertDialog = new Android.App.AlertDialog.Builder(this); alertDialog.SetTitle("This field is required"); alertDialog.SetMessage("First name cannot be blanks!"); alertDialog.SetNeutralButton("OK", delegate { alertDialog.Dispose(); }); Dialog dialog = alertDialog.Create(); alertDialog.Show(); } else if (tbxLastName.Text == "") { AlertDialog.Builder alertDialog = new Android.App.AlertDialog.Builder(this); alertDialog.SetTitle("This field is required"); alertDialog.SetMessage("Last name cannot be blanks!"); alertDialog.SetNeutralButton("OK", delegate { alertDialog.Dispose(); }); Dialog dialog = alertDialog.Create(); alertDialog.Show(); } else if (tbxDOB.Text == "") { AlertDialog.Builder alertDialog = new Android.App.AlertDialog.Builder(this); alertDialog.SetTitle("This field is required"); alertDialog.SetMessage("Date of Birth cannot be blanks!"); alertDialog.SetNeutralButton("OK", delegate { alertDialog.Dispose(); }); Dialog dialog = alertDialog.Create(); alertDialog.Show(); } else if (inputemail == "" && emailvalidate == false) { AlertDialog.Builder alertDialog = new Android.App.AlertDialog.Builder(this); alertDialog.SetTitle("This field is required"); alertDialog.SetMessage("Email cannot be blanks and format is incorrect!"); alertDialog.SetNeutralButton("OK", delegate { alertDialog.Dispose(); }); Dialog dialog = alertDialog.Create(); alertDialog.Show(); } else if (tbxPassword.Text == "") { AlertDialog.Builder alertDialog = new Android.App.AlertDialog.Builder(this); alertDialog.SetTitle("This field is required"); alertDialog.SetMessage("Password cannot be blanks!"); alertDialog.SetNeutralButton("OK", delegate { alertDialog.Dispose(); }); Dialog dialog = alertDialog.Create(); alertDialog.Show(); } else { //to call database into user string dbFilePath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "users.db"); var db = new SQLiteConnection(dbFilePath); db.CreateTable <User>(); User u = new User() { FirstName = tbxFirstName.Text, LastName = tbxLastName.Text, DOB = tbxDOB.Text, Email = tbxEmail.Text, Password = tbxPassword.Text }; //user created int id = dBMgr.insertUser(u); //to show added message by using toast Toast.MakeText(this, "Added!", ToastLength.Short).Show(); } }
private void SendEmail(ProgressDialog dialog, Activity curActivity, string subject, string notes) { try { string mStringLoginInfo = string.Empty; string mStringSessionToken = string.Empty; try { var objdb = new DBaseOperations(); var lstu = objdb.selectTable(); if (lstu != null && lstu.Count > default(int)) { var uobj = lstu.FirstOrDefault(); if (uobj.Password == " ") { throw new Exception("Please login again"); } mStringLoginInfo = uobj.EmailId; mStringSessionToken = uobj.AuthToken; } } catch { } using (MailMessage mail = new MailMessage()) { using (SmtpClient SmtpServer = new SmtpClient(CommonEmailSetup.Host)) { mail.From = new MailAddress(CommonEmailSetup.AdminEmailID); mail.To.Add(CommonEmailSetup.SupportEmailID); mail.Subject = string.Format("Mail From: {0}, Subject: {1}", mStringLoginInfo, subject); mail.Body = string.Format("<b>Mail From:</b> {0}<br><b>Notes:</b><br>{1}", mStringLoginInfo, notes.Replace("\n", "<br>")); mail.IsBodyHtml = true; SmtpServer.Port = CommonEmailSetup.Port; SmtpServer.EnableSsl = true; SmtpServer.UseDefaultCredentials = false; SmtpServer.Credentials = new System.Net.NetworkCredential(CommonEmailSetup.AdminEmailID, CommonEmailSetup.AdminEmalPassword); //SmtpServer.Send(mail); SmtpServer.SendMailAsync(mail); curActivity.RunOnUiThread(() => { Android.App.AlertDialog.Builder alertDiag = new Android.App.AlertDialog.Builder(curActivity); alertDiag.SetTitle(Resource.String.DialogHeaderGeneric); alertDiag.SetMessage("Thank you for contacting with us. We will get back to you soon"); alertDiag.SetIcon(Resource.Drawable.success); alertDiag.SetPositiveButton(Resource.String.DialogButtonOk, (senderAlert, args) => { DashboardFragment objFragment = new DashboardFragment(); Android.Support.V4.App.FragmentTransaction tx = FragmentManager.BeginTransaction(); tx.Replace(Resource.Id.m_main, objFragment, Constants.dashboard); tx.Commit(); }); Dialog diag = alertDiag.Create(); diag.Show(); diag.SetCanceledOnTouchOutside(false); }); } } } catch (Exception ex) { curActivity.RunOnUiThread(() => { Android.App.AlertDialog.Builder alertDiag = new Android.App.AlertDialog.Builder(curActivity); alertDiag.SetTitle(Resource.String.DialogHeaderError); alertDiag.SetMessage(ex.Message); alertDiag.SetIcon(Resource.Drawable.alert); alertDiag.SetPositiveButton(Resource.String.DialogButtonOk, (senderAlert, args) => { }); Dialog diag = alertDiag.Create(); diag.Show(); diag.SetCanceledOnTouchOutside(false); }); } finally { if (dialog != null && dialog.IsShowing) { dialog.Hide(); dialog.Dismiss(); } } }
private void ItemSearch_clicked(object sender, AdapterView.ItemClickEventArgs e, Activity currentActivity) { androidGridView.ItemClick -= (sndr, argus) => ItemSearch_clicked(sndr, argus, currentActivity); try { if (gridViewCodeString[e.Position] == "BCK") { DashboardFragment objFragment = new DashboardFragment(); Android.Support.V4.App.FragmentTransaction tx = FragmentManager.BeginTransaction(); tx.Replace(Resource.Id.m_main, objFragment, Constants.dashboard); tx.Commit(); } else if (gridViewCodeString[e.Position] == "NPR") { if (objSelectedItem == null) { objSelectedItem = new List <ItemPayloadModelWithBase64>(); } objSelectedItem.Add(new ItemPayloadModelWithBase64() { ItemName = gridViewString[e.Position], ItemCode = gridViewCodeString[e.Position], ItemIcon = BitmapHelpers.BitmapToBase64(gridViewImages[e.Position]), prdType = (ProductType)Convert.ToInt32(gridViewTypeCodeString[e.Position]) }); Bundle utilBundle = new Bundle(); utilBundle.PutString("siteparam", Newtonsoft.Json.JsonConvert.SerializeObject(objSelectedItem)); AddProductFragment objFragment = new AddProductFragment(); objFragment.Arguments = utilBundle; Android.Support.V4.App.FragmentTransaction tx = FragmentManager.BeginTransaction(); tx.Replace(Resource.Id.m_main, objFragment, Constants.dashboard); tx.Commit(); } else { //Identification of parent selection if (gridViewCodeString[e.Position].Contains("Ø")) { objSelectedItem = null; } if (objSelectedItem == null) { objSelectedItem = new List <ItemPayloadModelWithBase64>(); } objSelectedItem.Add(new ItemPayloadModelWithBase64() { ItemName = gridViewString[e.Position], ItemCode = gridViewCodeString[e.Position], ItemIcon = BitmapHelpers.BitmapToBase64(gridViewImages[e.Position]), prdType = (ProductType)Convert.ToInt32(gridViewTypeCodeString[e.Position]) }); if (gridViewCodeString[e.Position].Contains("Ø")) { AddActivityFragment objFragment = new AddActivityFragment(); Android.Support.V4.App.FragmentTransaction tx = FragmentManager.BeginTransaction(); tx.Replace(Resource.Id.m_main, objFragment, Constants.addactivity); tx.Commit(); } else { Bundle utilBundle = new Bundle(); if (objSelectedItem == null || objSelectedItem.Count() <= default(int)) { AddActivityFragment objFragment = new AddActivityFragment(); Android.Support.V4.App.FragmentTransaction tx = FragmentManager.BeginTransaction(); tx.Replace(Resource.Id.m_main, objFragment, Constants.addactivity); tx.Commit(); } else if (objSelectedItem != null && objSelectedItem.Count() > default(int) && objSelectedItem.Count() <= 1) { utilBundle.PutString("siteparam", Newtonsoft.Json.JsonConvert.SerializeObject(objSelectedItem)); AddActivityFragment objFragment = new AddActivityFragment(); objFragment.Arguments = utilBundle; Android.Support.V4.App.FragmentTransaction tx = FragmentManager.BeginTransaction(); tx.Replace(Resource.Id.m_main, objFragment, Constants.addactivity); tx.Commit(); } else if (objSelectedItem != null && objSelectedItem.Count() > 1) { utilBundle.PutString("siteparam", Newtonsoft.Json.JsonConvert.SerializeObject(objSelectedItem)); AddSelectedItemFragment objFragment = new AddSelectedItemFragment(); objFragment.Arguments = utilBundle; Android.Support.V4.App.FragmentTransaction tx = FragmentManager.BeginTransaction(); tx.Replace(Resource.Id.m_main, objFragment, Constants.addactivity); tx.Commit(); } } } } catch (Exception ex) { currentActivity.RunOnUiThread(() => { Android.App.AlertDialog.Builder alertDiag = new Android.App.AlertDialog.Builder(currentActivity); alertDiag.SetTitle(Resource.String.DialogHeaderError); alertDiag.SetMessage(ex.Message); alertDiag.SetIcon(Resource.Drawable.alert); alertDiag.SetPositiveButton(Resource.String.DialogButtonOk, (senderAlert, args) => { androidGridView.ItemClick += (sndr, argus) => ItemSearch_clicked(sndr, argus, currentActivity); }); Dialog diag = alertDiag.Create(); diag.Show(); diag.SetCanceledOnTouchOutside(false); }); } }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); string[] Example = new string[0]; string[] Example1 = new string[0]; string[] ClearArray = { "" }; spinnerRule = FindViewById <Spinner>(Resource.Id.spinner1); spinnerStep = FindViewById <Spinner>(Resource.Id.spinner2); MarkovAlg Markov = new MarkovAlg(); var RESULT = FindViewById <EditText>(Resource.Id.RESULT); // Get our button from the layout resource, // and attach an event to it Button nextRule = FindViewById <Button>(Resource.Id.nextRule); Button ansver = FindViewById <Button>(Resource.Id.ansver); Button ACCEPT = FindViewById <Button>(Resource.Id.ACCEPT); Button Exit = FindViewById <Button>(Resource.Id.Exit); Button Help = FindViewById <Button>(Resource.Id.Help); Button Clear = FindViewById <Button>(Resource.Id.Clear); Clear.Click += delegate { Markov.Clear(); Array.Clear(Example, 0, Example.Length); Array.Clear(Example1, 0, Example1.Length); count = 0; i = 0; k = 0; RESULT.Text = " All Clear"; FindViewById <EditText>(Resource.Id.rule1).Text = ""; FindViewById <EditText>(Resource.Id.rule2).Text = ""; FindViewById <EditText>(Resource.Id.original).Text = ""; spinnerRule.Adapter = new ArrayAdapter <string>(this, Android.Resource.Layout.SimpleSpinnerDropDownItem, ClearArray); spinnerStep.Adapter = new ArrayAdapter <string>(this, Android.Resource.Layout.SimpleSpinnerDropDownItem, ClearArray); }; Exit.Click += delegate { this.FinishAffinity(); }; Help.Click += delegate { Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(this); Android.App.AlertDialog alertDialog = builder.Create(); alertDialog.SetTitle("Help"); alertDialog.SetMessage("Empty symbol it's ' " + " ' (Spacebar) \n For enteryng Original word press Accept \n For eneryng every rule press Next Rule"); alertDialog.Show(); }; ACCEPT.Click += delegate { Markov.ReadOriginal(FindViewById <EditText>(Resource.Id.original).Text); }; nextRule.Click += delegate { if (FindViewById <EditText>(Resource.Id.rule1).Text == "" && FindViewById <EditText>(Resource.Id.rule2).Text == "") { Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(this); Android.App.AlertDialog Validation = builder.Create(); Validation.SetTitle("Error"); Validation.SetMessage("One from rules must be diferent from NULL"); Validation.Show(); } else { Markov.ReadRule(FindViewById <EditText>(Resource.Id.rule1).Text, FindViewById <EditText>(Resource.Id.rule2).Text, count); Array.Resize <string>(ref Example, count + 1); Example[count] = (count + 1).ToString() + " rule - " + FindViewById <EditText>(Resource.Id.rule1).Text + " -> " + " " + FindViewById <EditText>(Resource.Id.rule2).Text; spinnerRule.Adapter = new ArrayAdapter <string>(this, Android.Resource.Layout.SimpleSpinnerDropDownItem, Example); count = count + 1; FindViewById <EditText>(Resource.Id.rule1).Text = ""; FindViewById <EditText>(Resource.Id.rule2).Text = ""; } }; i = 0; ansver.Click += delegate { if (Markov.Result() == "") { Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(this); Android.App.AlertDialog Error = builder.Create(); Error.SetTitle("Help"); Error.SetMessage("Enter original word"); Error.Show(); } else { k = count; int RuleCount = 0; Array.Resize <string>(ref Example1, RuleCount + 1); Example1[RuleCount] = "Original String " + Markov.Result(); spinnerStep.Adapter = new ArrayAdapter <string>(this, Android.Resource.Layout.SimpleSpinnerDropDownItem, Example1); RuleCount = 1; int CycleControl = 0; { while (i < count) { CycleControl++; if (CycleControl > 1000) { Markov.CycleControl(); break; } if (Markov.Contains(Markov.rules[i, 0])) { Markov.replace(Markov.rules[i, 0], Markov.rules[i, 1]); Array.Resize <string>(ref Example1, RuleCount + 1); Example1[RuleCount] = (RuleCount + 1).ToString() + " step - " + Markov.Result(); spinnerStep.Adapter = new ArrayAdapter <string>(this, Android.Resource.Layout.SimpleSpinnerDropDownItem, Example1); RuleCount++; if (Markov.end(i)) { break; } i = 0; } else { i++; } } ; } } RESULT.Text = Markov.Result(); }; }
public void ReceiveMessage(Data data, string Endpoint) { if (MsgList.Count == 0 || !ChatActivity.device.EndPoint.Equals(Endpoint)) { MsgList.Clear(); Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(this); builder.SetTitle("You got a message !"); builder.SetMessage(Endpoint + " is trying to send a message to you. do you want to accept?"); builder.SetNegativeButton("Cancel", (senderAlert, args) => { string msgStr = "Refuse"; Data data = Data.FromBytes(System.Text.Encoding.UTF8.GetBytes(msgStr)); mTransferEngine.SendData(Endpoint, data).AddOnSuccessListener(new TaskListener(this, "Refuse Connection")).AddOnFailureListener(new TaskListener(this, "Refuse Connection")); return; }); builder.SetPositiveButton("Yes", (senderAlert, args) => { string str = System.Text.Encoding.UTF8.GetString(data.AsBytes()); Log.Debug(TAG, "OnReceived [Message] success. msgStr-------->>>>" + str); if (!str.EndsWith(":msg input")) { return; } str = str.Split(":")[0]; MessageBean item = new MessageBean(); item.MyName = MyEndPoint; item.FriendName = FindDevice(Endpoint).Name; item.Msg = str; item.Type = (MessageBean.TYPE_RECEIVE_TEXT); MsgList.Add(item); Intent chat = new Intent(); chat.SetClass(this, typeof(ChatActivity)); chat.SetFlags(ActivityFlags.ClearTop); chat.PutExtra("DeviceID", AvaliableDevicesList.IndexOf(FindDevice(Endpoint))); StartActivity(chat); }); Dialog dialog = builder.Create(); dialog.Show(); } else { string str = System.Text.Encoding.UTF8.GetString(data.AsBytes()); Log.Debug(TAG, "OnReceived [Message] success. msgStr-------->>>>" + str); if (!str.EndsWith(":msg input")) { return; } str = str.Split(":")[0]; MessageBean item = new MessageBean(); item.MyName = MyEndPoint; item.FriendName = FindDevice(Endpoint).Name; item.Msg = str; item.Type = (MessageBean.TYPE_RECEIVE_TEXT); MsgList.Add(item); Intent chat = new Intent(); chat.SetClass(this, typeof(ChatActivity)); chat.SetFlags(ActivityFlags.ClearTop); chat.PutExtra("DeviceID", AvaliableDevicesList.IndexOf(FindDevice(Endpoint))); StartActivity(chat); } }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.SignUpPage); // Create your application here EditText uName = FindViewById <EditText>(Resource.Id.uName); EditText pWord = FindViewById <EditText>(Resource.Id.pWord); EditText rePWord = FindViewById <EditText>(Resource.Id.rePWord); EditText email = FindViewById <EditText>(Resource.Id.email); Button signUp = FindViewById <Button>(Resource.Id.signUp); signUp.Click += async(s, e) => { Android.App.AlertDialog.Builder message = new Android.App.AlertDialog.Builder(this); string name = uName.Text; string pin = pWord.Text; string rePin = rePWord.Text; string em = email.Text; string encoded = ""; int responseString; if ((name != "") && (pin != "") && (rePin != "") && (em != "")) { if (pin.Equals(rePin)) { if (IsValidEmail(em)) { try { string orig = pin; byte[] salt; new RNGCryptoServiceProvider().GetBytes(salt = new byte[16]); var pbkdf2 = new Rfc2898DeriveBytes(orig, salt, 10000); byte[] hash = pbkdf2.GetBytes(20); byte[] hashBytes = new byte[36]; Array.Copy(salt, 0, hashBytes, 0, 16); Array.Copy(hash, 0, hashBytes, 16, 20); encoded = Convert.ToBase64String(hashBytes); Console.WriteLine(encoded); var response = await RunPostAsync(name, encoded, em); responseString = int.Parse(response); //Console.WriteLine(response); if (responseString == 1) { message.SetTitle("Successful!!"); message.SetMessage("You have resiger successfully!"); message.SetNegativeButton("OK", (c, ev) => { Intent intent = new Intent(this, typeof(MainActivity)); this.StartActivity(intent); }); message.Show(); } if (responseString == 2) { message.SetTitle("Opssss"); message.SetMessage("The Email address is exist, try another one..."); message.SetNegativeButton("OK", (c, ev) => { }); message.Show(); } if (responseString == 0) { message.SetTitle("Opssss"); message.SetMessage("The username is exist, try another one..."); message.SetNegativeButton("OK", (c, ev) => { }); message.Show(); } } catch { message.SetTitle("Opssss"); message.SetMessage("Some internal error, try again later.."); message.SetNegativeButton("OK", (c, ev) => { }); message.Show(); } } else { message.SetTitle("Opssss"); message.SetMessage("Invalide Email address.."); message.SetNegativeButton("OK", (c, ev) => { }); message.Show(); } } else { message.SetTitle("Opssss"); message.SetMessage("The password doesn't match.."); message.SetNegativeButton("OK", (c, ev) => { }); message.Show(); } } else { message.SetTitle("Opssss"); message.SetMessage("Some value are missing.."); message.SetNegativeButton("OK", (c, ev) => { }); message.Show(); } }; }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Create your application here SetContentView(Resource.Layout.fightPage); imageOne = FindViewById <ImageView>(Resource.Id.versPic1); imageTwo = FindViewById <ImageView>(Resource.Id.versPic2); nameOne = FindViewById <TextView>(Resource.Id.versDescript1); nameTwo = FindViewById <TextView>(Resource.Id.versDescript2); btnAttack1 = FindViewById <Button>(Resource.Id.btnAttack1); btnAttack2 = FindViewById <Button>(Resource.Id.btnAttack2); btnAttack3 = FindViewById <Button>(Resource.Id.btnAttack3); btnAttack4 = FindViewById <Button>(Resource.Id.btnAttack4); hpOne = FindViewById <TextView>(Resource.Id.hpOne); hpTwo = FindViewById <TextView>(Resource.Id.hpTwo); pokemonFight = JsonConvert.DeserializeObject <Pokemon>(Intent.GetStringExtra("pokemonFight")); myDbInstance = new DBHelper(this); myAlert = new Android.App.AlertDialog.Builder(this); pokemonBot = myDbInstance.RandPokemonForFight(); //Pokemon Player imageOne.SetImageResource(pokemonFight.image); nameOne.Text = pokemonFight.name; btnAttack1.Text = pokemonFight.abilityOne; btnAttack2.Text = pokemonFight.abilityTwo; btnAttack3.Text = pokemonFight.abilityThree; btnAttack4.Text = pokemonFight.abilityFour; hpOne.Text = pokemonFight.hp + " HP"; //PokemonBot imageTwo.SetImageResource(pokemonBot.image); nameTwo.Text = pokemonBot.name; hpTwo.Text = pokemonBot.hp + " HP"; btnAttack1.Click += delegate { pokemonBot.attack(pokemonFight.abilityOneAttack); hpTwo.Text = pokemonBot.checkHealthPoints().ToString() + " HP"; pokemonFight.attack(randomAttack()); hpOne.Text = pokemonFight.checkHealthPoints().ToString() + " HP"; checkWinner(); }; btnAttack2.Click += delegate { pokemonBot.attack(pokemonFight.abilityTwoAttack); hpTwo.Text = pokemonBot.checkHealthPoints().ToString() + " HP"; pokemonFight.attack(randomAttack()); hpOne.Text = pokemonFight.checkHealthPoints().ToString() + " HP"; checkWinner(); }; btnAttack3.Click += delegate { pokemonBot.attack(pokemonFight.abilityThreeAttack); hpTwo.Text = pokemonBot.checkHealthPoints().ToString() + " HP"; pokemonFight.attack(randomAttack()); hpOne.Text = pokemonFight.checkHealthPoints().ToString() + " HP"; checkWinner(); }; btnAttack4.Click += delegate { pokemonBot.attack(pokemonFight.abilityFourAttack); hpTwo.Text = pokemonBot.checkHealthPoints().ToString() + " HP"; pokemonFight.attack(randomAttack()); hpOne.Text = pokemonFight.checkHealthPoints().ToString() + " HP"; checkWinner(); }; }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.signup); // Create your application here myLogin = FindViewById <Button>(Resource.Id.btnLogin); mySignup = FindViewById <Button>(Resource.Id.btnSignup); btnSignup = FindViewById <Button>(Resource.Id.button3); // signup txtName = FindViewById <EditText>(Resource.Id.editText); //name txtEmail = FindViewById <EditText>(Resource.Id.editText2); //email txtPassword = FindViewById <EditText>(Resource.Id.editText3); //password alert = new Android.App.AlertDialog.Builder(this); // database myDB = new DBHelperClass(this); // alertbox myLogin.Click += delegate { // Already login button //Intent loginScreen = new Intent(this, typeof(login)); // on success loading login page // StartActivity(loginScreen); StartActivity(typeof(login)); OverridePendingTransition(Resource.Animation.fade_in, Resource.Animation.fade_out); }; btnSignup.Click += delegate { alert.SetTitle("Aleph | Error !"); if (txtName.Text.Trim().Equals("") || txtName.Text.Length < 0 || txtEmail.Text.Trim().Equals("") || txtEmail.Text.Length < 0 || txtPassword.Text.Trim().Equals("") || txtPassword.Text.Length < 0) { alert.SetMessage("Please fill all fields"); alert.SetPositiveButton("OK", alertOKButton); Dialog myDialog = alert.Create(); myDialog.Show(); } else if (!re.IsMatch(txtEmail.Text.Trim())) { alert.SetMessage("Please enter valid Email address"); alert.SetPositiveButton("OK", alertOKButton); Dialog myDialog = alert.Create(); myDialog.Show(); } else { Boolean f = myDB.insertValue(txtName.Text.Trim(), txtEmail.Text.Trim(), txtPassword.Text.Trim()); if (f) { txtName.Text = ""; txtEmail.Text = ""; txtPassword.Text = ""; alert.SetMessage("Registration successfull!"); } else { alert.SetMessage("User already exist!"); } alert.SetTitle("Aleph | Information"); alert.SetPositiveButton("OK", redirectToLogin); Dialog myDialog = alert.Create(); myDialog.Show(); } }; }
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.Inflate(Resource.Layout.create_layout2, null); db = new DbHelper(); geolocation = geo.GetGeoLocation(Activity); HasOptionsMenu = true; isRecording = false; prefs = PreferenceManager.GetDefaultSharedPreferences(Activity); licenceId = prefs.GetString("LicenceId", ""); tempId = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + licenceId; _dateSelectButton = view.FindViewById <ImageView>(Resource.Id.imageView); timeSelectButton = view.FindViewById <ImageView>(Resource.Id.imageView2); max_number = view.FindViewById <EditText>(Resource.Id.maxnumberedit); task_name = view.FindViewById <EditText>(Resource.Id.ed1); task_comment = view.FindViewById <EditText>(Resource.Id.ed2); createbutton = view.FindViewById <Button>(Resource.Id.btn); Saveforlater = view.FindViewById <Button>(Resource.Id.saveforlater); Addtolist = view.FindViewById <Button>(Resource.Id.btn_addtolist); createbutton.Click += CreateButton_OnClick; _dateDisplay = view.FindViewById <TextView>(Resource.Id.textView1); timeDisplay = view.FindViewById <TextView>(Resource.Id.textView2); title = view.FindViewById <ImageView>(Resource.Id.imageView1); desc = view.FindViewById <ImageView>(Resource.Id.imageView3); camera = view.FindViewById <ImageButton>(Resource.Id.camera_btn); video = view.FindViewById <ImageButton>(Resource.Id.video_btn); microphone = view.FindViewById <ImageButton>(Resource.Id.micro_btn); cardView = view.FindViewById <CardView>(Resource.Id.cardView_addcomp); attachment_btn = view.FindViewById <ImageButton>(Resource.Id.attachment); cardviewref = view.FindViewById <CardView>(Resource.Id.cardView_addref); /// attachment_btn = view.FindViewById<ImageButton>(Resource.Id.attachment); cardviewref.Click += delegate { CreateRefAddFragment createRefAdd = new CreateRefAddFragment(); createRefAdd.Show(FragmentManager, "CreateRefAddFragment"); //FragmentTransaction ft = FragmentManager.BeginTransaction(); //ft.Replace(Resource.Id.container, createRefAdd); ////ft.Hide(FragmentManager.FindFragmentByTag("CreateTaskFrag")); ////ft.Add(Resource.Id.container, createRefAdd); //ft.AddToBackStack(null); //ft.SetTransition(FragmentTransaction.TransitFragmentOpen); //ft.Commit(); }; //attachment_btn.Click += delegate //{ // attachmentClick(); //}; cardView.Click += delegate { AddComplianceInCreate nextFrag = new AddComplianceInCreate(); nextFrag.Show(FragmentManager, "AddComplianceInCreate"); //FragmentTransaction ft = FragmentManager.BeginTransaction(); //ft.Replace(Resource.Id.container, nextFrag); ////ft.Hide(FragmentManager.FindFragmentByTag("CreateTaskFrag")); ////ft.Add(Resource.Id.container, nextFrag); //ft.AddToBackStack(null); //ft.SetTransition(FragmentTransaction.TransitFragmentOpen); //ft.Commit(); // fragment.BeginTransaction().Replace(Resource.Id.container, nextFrag).Commit(); //Bundle bundle = new Bundle(); ////bundle.PutString("task_id", id); //nextFrag.Arguments = bundle; }; //checkBox1 = view.FindViewById<RadioButton>(Resource.Id.mandatory); //checkBox2 = view.FindViewById<RadioButton>(Resource.Id.not); //spinnerextension = view.FindViewById<Spinner>(Resource.Id.spiner_format); //spinnertype = view.FindViewById<Spinner>(Resource.Id.spinner_type); // complianceGridview = view.FindViewById<ExpandableHeightGridView>(Resource.Id.grid_compliance); Gridview_1 = view.FindViewById <ExpandableHeightGridView>(Resource.Id.gridView1); Grid_attach = view.FindViewById <ExpandableHeightGridView>(Resource.Id.gridattachment); Gridview_2 = view.FindViewById <ExpandableHeightGridView>(Resource.Id.gridView2); Gridview_3 = view.FindViewById <ExpandableHeightGridView>(Resource.Id.gridView3); //checkBox1.Click += RadioButtonClick; //checkBox2.Click += RadioButtonClick; Saveforlater.Click += Saveforlater_Click; //max_num = max_number.Text; //max_numbers = Convert.ToInt32(max_num); //Addtolist.Click += delegate //{ // addtolistcompliance(); //}; // microphone.Click += delegate //{ // recording(); //}; _dateSelectButton.Click += (sender, e) => { DateSelect_OnClick(sender, e); }; //camera.Click += delegate //{ // //Click_Type = "Camera"; // //CheckForShapeData_Camera(); // BtnCamera_Click(); //}; //video.Click += delegate //{ // //Click_Type = "Video"; // //CheckForShapeData_Video(); // VideoClick(); //}; //_dateSelectButton.Click += DateSelect_OnClick; timeSelectButton.Click += TimeSelectOnClick; string rec = Android.Content.PM.PackageManager.FeatureMicrophone; if (rec != "android.hardware.microphone") { var alert = new Android.App.AlertDialog.Builder(title.Context); alert.SetTitle("You don't seem to have a microphone to record with"); alert.SetPositiveButton("OK", (sender, e) => { return; }); alert.Show(); } else { title.Click += delegate { isRecording = !isRecording; if (isRecording) { var voiceIntent = new Intent(RecognizerIntent.ActionRecognizeSpeech); voiceIntent.PutExtra(RecognizerIntent.ExtraLanguageModel, RecognizerIntent.LanguageModelFreeForm); voiceIntent.PutExtra(RecognizerIntent.ExtraPrompt, Android.App.Application.Context.GetString(Resource.String.messageSpeakNow)); voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputCompleteSilenceLengthMillis, 1500); voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputPossiblyCompleteSilenceLengthMillis, 1500); voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputMinimumLengthMillis, 15000); voiceIntent.PutExtra(RecognizerIntent.ExtraMaxResults, 1); voiceIntent.PutExtra(RecognizerIntent.ExtraLanguage, Java.Util.Locale.Default); StartActivityForResult(voiceIntent, VOICE); } }; desc.Click += delegate { isRecording = !isRecording; if (isRecording) { // create the intent and start the activity var voiceIntent = new Intent(RecognizerIntent.ActionRecognizeSpeech); voiceIntent.PutExtra(RecognizerIntent.ExtraLanguageModel, RecognizerIntent.LanguageModelFreeForm); // put a message on the modal dialog voiceIntent.PutExtra(RecognizerIntent.ExtraPrompt, Android.App.Application.Context.GetString(Resource.String.messageSpeakNow)); // if there is more then 1.5s of silence, consider the speech over voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputCompleteSilenceLengthMillis, 1500); voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputPossiblyCompleteSilenceLengthMillis, 1500); voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputMinimumLengthMillis, 15000); voiceIntent.PutExtra(RecognizerIntent.ExtraMaxResults, 1); // you can specify other languages recognised here, for example // voiceIntent.PutExtra(RecognizerIntent.ExtraLanguage, Java.Util.Locale.German); // if you wish it to recognise the default Locale language and German // if you do use another locale, regional dialects may not be recognised very well voiceIntent.PutExtra(RecognizerIntent.ExtraLanguage, Java.Util.Locale.Default); StartActivityForResult(voiceIntent, DESC); } }; } return(view); }
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.Inflate(Resource.Layout.create_ref_layout, null); db = new DbHelper(); geo = new Geolocation(); geolocation = geo.GetGeoLocation(Activity); HasOptionsMenu = true; isRecording = false; prefs = PreferenceManager.GetDefaultSharedPreferences(Activity); licenceId = prefs.GetString("LicenceId", ""); tempId = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + licenceId; camera = view.FindViewById <ImageButton>(Resource.Id.camera_btn); video = view.FindViewById <ImageButton>(Resource.Id.video_btn); microphone = view.FindViewById <ImageButton>(Resource.Id.micro_btn); Gridview_1 = view.FindViewById <ExpandableHeightGridView>(Resource.Id.grid); Grid_attach = view.FindViewById <ExpandableHeightGridView>(Resource.Id.gridattachment); Gridview_2 = view.FindViewById <ExpandableHeightGridView>(Resource.Id.gridView2); Gridview_3 = view.FindViewById <ExpandableHeightGridView>(Resource.Id.gridView3); attachment_btn = view.FindViewById <ImageButton>(Resource.Id.attachment); // Gridview_1 = view.FindViewById<ExpandableHeightGridView>(Resource.Id.gridView1); //Grid_attach = view.FindViewById<ExpandableHeightGridView>(Resource.Id.gridattachment); //Gridview_2 = view.FindViewById<ExpandableHeightGridView>(Resource.Id.gridView2); //Gridview_3 = view.FindViewById<ExpandableHeightGridView>(Resource.Id.gridView3); //title = view.FindViewById<ImageView>(Resource.Id.imageView1); // listmapping = new List<TaskFileMapping_Model>(); desc = view.FindViewById <ImageView>(Resource.Id.imageView3); if (image_list.Count > 0) { adapter_1 = new GridImageAdapterCreatetask(Activity, image_list); Gridview_1.Adapter = adapter_1; Gridview_1.setExpanded(true); Gridview_1.ChoiceMode = (ChoiceMode)AbsListViewChoiceMode.MultipleModal; Gridview_1.SetMultiChoiceModeListener(new MultiChoiceModeListener1(Activity)); } if (video_list.Count > 0) { adapter_2 = new GridVideoAdapterCreateTask(Activity, video_list); Gridview_2.Adapter = adapter_2; Gridview_2.setExpanded(true); Gridview_2.ChoiceMode = (ChoiceMode)AbsListViewChoiceMode.MultipleModal; Gridview_2.SetMultiChoiceModeListener(new MultiChoiceModeListener2(Activity)); } if (audio_list.Count > 0) { adapter_3 = new GridAudioCreateTask(Activity, audio_list); Gridview_3.Adapter = adapter_3; Gridview_3.setExpanded(true); Gridview_3.ChoiceMode = (ChoiceMode)AbsListViewChoiceMode.MultipleModal; Gridview_3.SetMultiChoiceModeListener(new MultiChoiceModeListener3(Activity)); } if (listmapping.Count > 0) { forCreate = new GridAttachmentForCreate(Activity, listmapping); Grid_attach.Adapter = forCreate; Grid_attach.setExpanded(true); } attachment_btn.Click += delegate { attachmentClick(); }; camera.Click += delegate { BtnCamera_Click(); }; video.Click += delegate { VideoClick(); }; microphone.Click += delegate { recording(); }; string rec = Android.Content.PM.PackageManager.FeatureMicrophone; if (rec != "android.hardware.microphone") { // no microphone, no recording. Disable the button and output an alert var alert = new Android.App.AlertDialog.Builder(title.Context); alert.SetTitle("You don't seem to have a microphone to record with"); alert.SetPositiveButton("OK", (sender, e) => { task_name.Text = "No microphone present"; title.Enabled = false; task_comment.Text = "No microphone present"; desc.Enabled = false; return; }); alert.Show(); } else { //title.Click += delegate //{ // // change the text on the button // isRecording = !isRecording; // if (isRecording) // { // // create the intent and start the activity // var voiceIntent = new Intent(RecognizerIntent.ActionRecognizeSpeech); // voiceIntent.PutExtra(RecognizerIntent.ExtraLanguageModel, RecognizerIntent.LanguageModelFreeForm); // // put a message on the modal dialog // voiceIntent.PutExtra(RecognizerIntent.ExtraPrompt, Android.App.Application.Context.GetString(Resource.String.messageSpeakNow)); // // if there is more then 1.5s of silence, consider the speech over // voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputCompleteSilenceLengthMillis, 1500); // voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputPossiblyCompleteSilenceLengthMillis, 1500); // voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputMinimumLengthMillis, 15000); // voiceIntent.PutExtra(RecognizerIntent.ExtraMaxResults, 1); // voiceIntent.PutExtra(RecognizerIntent.ExtraLanguage, Java.Util.Locale.Default); // StartActivityForResult(voiceIntent, VOICE); // } // }; //desc.Click += delegate //{ // isRecording = !isRecording; // if (isRecording) // { // // create the intent and start the activity // var voiceIntent = new Intent(RecognizerIntent.ActionRecognizeSpeech); // voiceIntent.PutExtra(RecognizerIntent.ExtraLanguageModel, RecognizerIntent.LanguageModelFreeForm); // // put a message on the modal dialog // voiceIntent.PutExtra(RecognizerIntent.ExtraPrompt, Android.App.Application.Context.GetString(Resource.String.messageSpeakNow)); // // if there is more then 1.5s of silence, consider the speech over // voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputCompleteSilenceLengthMillis, 1500); // voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputPossiblyCompleteSilenceLengthMillis, 1500); // voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputMinimumLengthMillis, 15000); // voiceIntent.PutExtra(RecognizerIntent.ExtraMaxResults, 1); // // you can specify other languages recognised here, for example // // voiceIntent.PutExtra(RecognizerIntent.ExtraLanguage, Java.Util.Locale.German); // // if you wish it to recognise the default Locale language and German // // if you do use another locale, regional dialects may not be recognised very well // voiceIntent.PutExtra(RecognizerIntent.ExtraLanguage, Java.Util.Locale.Default); // StartActivityForResult(voiceIntent, DESC); // } //}; } return(view); }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); // Get our button from the layout resource, // and attach an event to it EditText userName = FindViewById <EditText>(Resource.Id.uname); EditText userPword = FindViewById <EditText>(Resource.Id.pword); TextView forgetPword = FindViewById <TextView>(Resource.Id.forgetPword); Button logIn = FindViewById <Button>(Resource.Id.loginBtn); Button logGoogle = FindViewById <Button>(Resource.Id.logGoogle); Button logFacebook = FindViewById <Button>(Resource.Id.logFacebook); TextView signUp = FindViewById <TextView>(Resource.Id.signUp); logIn.Click += async(s, e) => { Person p = new Person(); string uName = userName.Text; string pWord = userPword.Text; var response = await RunGetAsync(uName); p.id = response.id; p.name = response.name; p.password = response.password; p.email = response.email; string orig = pWord; byte[] hashBytes = Convert.FromBase64String(p.password); byte[] salt = new byte[16]; Array.Copy(hashBytes, 0, salt, 0, 16); var pbkdf2 = new Rfc2898DeriveBytes(orig, salt, 10000); byte[] hash = pbkdf2.GetBytes(20); bool ok = true; for (int i = 0; i < 20; i++) { if (hashBytes[i + 16] != hash[i]) { ok = false; } } Console.WriteLine(ok); if (ok == true) { Intent intent = new Intent(this, typeof(LoggedInActivity)); this.StartActivity(intent); } else { Android.App.AlertDialog.Builder message = new Android.App.AlertDialog.Builder(this); message.SetTitle("Opssss"); message.SetMessage("The password incorrect!"); message.SetNegativeButton("OK", (c, ev) => { }); message.Show(); } }; signUp.Click += delegate { Intent intent = new Intent(this, typeof(SignUpActivity)); this.StartActivity(intent); }; forgetPword.Click += delegate { Intent intent = new Intent(this, typeof(ResetPasswordActivity)); this.StartActivity(intent); }; }
private void recording() { View view = LayoutInflater.Inflate(Resource.Layout.audio_recorder, null); Android.App.AlertDialog builder = new Android.App.AlertDialog.Builder(Activity).Create(); builder.SetView(view); builder.Window.SetLayout(600, 600); builder.SetCanceledOnTouchOutside(false); recordbtn = view.FindViewById <Button>(Resource.Id.recordbtn); stopbtn = view.FindViewById <ImageView>(Resource.Id.stopbtn); playbtn = view.FindViewById <ImageView>(Resource.Id.playbtn); Timer = view.FindViewById <TextView>(Resource.Id.timerbtn); seekBar = view.FindViewById <SeekBar>(Resource.Id.seek_bar); Done_Btn = view.FindViewById <Button>(Resource.Id.donebtn); Done_Btn.Click += delegate { TaskFileMapping_Model attachmentModel = new TaskFileMapping_Model(); long size3 = fileaudioPath.Length() / 1024 * 1024; string audiosize = size3.ToString(); attachmentModel.Path = AudioSavePathInDevice; attachmentModel.FileType = "Audio"; attachmentModel.FileName = audioname; attachmentModel.localtaskId = task_id_to_send; // attachmentModel.file_format = Utility.audiotype; attachmentModel.FileSize = audiosize; // attachmentModel.GeoLocation = geolocation; // attachmentModel.max_numbers = audio_max.ToString(); // db.InsertCreateAttachData(attachmentModel); // comp_AttachmentModels.Add(attachmentModel); listmapping.Add(attachmentModel); //imagelist.AddRange(comp_AttachmentModels.Where(p => p.Attachment_Type == "Image" )); // audio_list = db.GetCreateAttachmentData("Audio", licenceidmodel[0].taskid.ToString()); for (int i = 0; i < listmapping.Count; i++) { if (listmapping[i].FileType.Equals("Audio")) { audio_list.Add(listmapping[i]); } } adapter_3 = new GridAudioCreateTask(Activity, audio_list); Gridview_3.Adapter = adapter_3; Gridview_3.setExpanded(true); Gridview_3.ChoiceMode = (ChoiceMode)AbsListViewChoiceMode.MultipleModal; Gridview_3.SetMultiChoiceModeListener(new MultiChoiceModeListener3(Activity)); audioCount++; builder.Dismiss(); }; recordbtn.Click += delegate { MediaRecorderReady(); try { timer = new Timer(); timer.Interval = 1000; // 1 second timer.Elapsed += Timer_Elapsed; timer.Start(); mediaRecorder.Prepare(); mediaRecorder.Start(); } catch (Exception e) { // TODO Auto-generated catch block //e.printStackTrace(); } Toast.MakeText(Activity, "Recording started", ToastLength.Long).Show(); }; stopbtn.Click += delegate { try { mediaRecorder.Stop(); Timer.Text = "00:00:00"; timer.Stop(); timer = null; } catch (Exception ex) { } //stoprecorder(); //btn2.Enabled=false; //buttonPlayLastRecordAudio.setEnabled(true); //buttonStart.setEnabled(true); //buttonStopPlayingRecording.setEnabled(false); Toast.MakeText(Activity, "Recording completed", ToastLength.Long).Show(); }; //pausebtn.Click += delegate //{ // //OnPause(); // mediaRecorder.Pause(); // timer.Dispose(); //}; playbtn.Click += delegate { mediaPlayer = new MediaPlayer(); mediaPlayer.SetDataSource(AudioSavePathInDevice); mediaPlayer.Prepare(); mediaPlayer.Start(); //mediaPlayer = MediaPlayer.Create(this, Resource.Raw.AudioSavePathInDevice); seekBar.Max = mediaPlayer.Duration; run(); }; //resumebtn.Click += delegate // { // mediaRecorder.Resume(); // timer.Start(); // }; //savebtn.Click += delegate // { // Java.IO.File path = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures); // audiofile = new Java.IO.File(path, "TaskApp"); // if (!audiofile.Exists()) // { // audiofile.Mkdirs(); // } // audioname = Utility.fileName1(); // fileImagePath = new Java.IO.File(audiofile, string.Format(audioname, Guid.NewGuid())); // AudioSavePathInDevice = fileImagePath.AbsolutePath; // mediaRecorder.SetOutputFile(AudioSavePathInDevice); // builder.Dismiss(); // }; builder.Show(); }
protected override void OnCreate(Bundle savedInstanceState) { string mode = "chs"; //CHS or ENG or CXG long currentTime; int fastClickCounter = 0; long lastClickTime = 0; int fastClickCounter4Chouxiang = 0; long lastClickTime4Chouxiang = 0; base.OnCreate(savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState); SetContentView(Resource.Layout.activity_main); #region Widget Button btn_generate = FindViewById <Button>(Resource.Id.generate); EditText et_theme = FindViewById <EditText>(Resource.Id.theme); EditText et_output = FindViewById <EditText>(Resource.Id.output); Button btn_switch = FindViewById <Button>(Resource.Id.btnswitch); #endregion Chouxiang chouxiang = new Chouxiang(); ShitEnglish shitEnglish = new ShitEnglish(); et_theme.Text = Shit.theme; btn_generate.Click += (sender, e) => { currentTime = DateTime.Now.Ticks; if (fastClickCounter == 0) { fastClickCounter += 1; lastClickTime = currentTime; } else { if (currentTime - lastClickTime <= 10000000) { fastClickCounter += 1; lastClickTime = currentTime; } else { fastClickCounter = 0; } } if (fastClickCounter == 10) { Toast.MakeText(Application.Context, "BullshitGenerator by menzi11\nBullshitGenerator.Android by Kevin\nEnglish algorithm by JIUYANGZH\nMIT License\nKevin ♥ Jiangyu & .NET", ToastLength.Long).Show(); fastClickCounter = 0; //Replace counter } switch (mode.ToLower()) { case "chs": et_output.Text = Shit.GenerateArticle(et_theme.Text); break; case "eng": et_output.Text = shitEnglish.Generate(et_theme.Text).Replace(" .\n", "").Replace(" .\n", ""); break; case "cxg": et_output.Text = chouxiang.ChangeChouxiang(Shit.GenerateArticle(et_theme.Text)); //TODO: Do some chouxiang break; } }; btn_generate.LongClick += (sender, e) => { var alertDialog = new Android.App.AlertDialog.Builder(this).Create(); alertDialog.SetTitle(Resources.GetString(Resource.String.info)); alertDialog.SetMessage(Resources.GetString(Resource.String.copy_to_clipboard)); alertDialog.SetButton(Resources.GetString(Resource.String.ok), async(s, a) => { await Clipboard.SetTextAsync(et_output.Text); }); alertDialog.SetButton2(Resources.GetString(Resource.String.cancle), (s, a) => { }); alertDialog.Show(); }; btn_switch.Click += (sender, e) => { currentTime = DateTime.Now.Ticks; if (fastClickCounter4Chouxiang == 0) { fastClickCounter4Chouxiang += 1; lastClickTime4Chouxiang = currentTime; } else { if (currentTime - lastClickTime4Chouxiang <= 10000000) { fastClickCounter4Chouxiang += 1; lastClickTime4Chouxiang = currentTime; } else { fastClickCounter4Chouxiang = 0; } } if (fastClickCounter4Chouxiang == 5) { mode = "cxg"; btn_switch.SetTextColor(Android.Content.Res.ColorStateList.ValueOf(Color.Red)); fastClickCounter4Chouxiang = 0; var alertDialog = new Android.App.AlertDialog.Builder(this).Create(); alertDialog.SetTitle(Resources.GetString(Resource.String.info)); alertDialog.SetMessage(Resources.GetString(Resource.String.cxg_mode_on)); alertDialog.SetButton(Resources.GetString(Resource.String.ok), (s, a) => { }); alertDialog.Show(); } else { switch (mode.ToLower()) { case "chs": case "cxg": if (et_theme.Text == "一天掉多少根头发") { et_theme.Text = shitEnglish.theme; } mode = "eng"; btn_switch.Text = Resources.GetString(Resource.String.switch_chs); break; case "eng": mode = "chs"; if (et_theme.Text == shitEnglish.theme) { et_theme.Text = Shit.theme; } btn_switch.Text = Resources.GetString(Resource.String.switch_eng); break; default: throw new IndexOutOfRangeException(); } btn_switch.SetTextColor(Android.Content.Res.ColorStateList.ValueOf(Color.Black)); } }; }
protected override void OnCreate(Bundle savedInstanceState) { CrossCurrentActivity.Current.Activity = this; base.OnCreate(savedInstanceState); startServiceIntent = new Intent(this, typeof(TriTrackService)); user_id = Intent.GetIntExtra("user_id", 0); SetContentView(Resource.Layout.Map); daToolbar = FindViewById <SupportToolbar>(Resource.Id.toolbar); SetSupportActionBar(daToolbar); daLeftDrawer = FindViewById <ListView>(Resource.Id.left_drawer); daDrawerLayout = FindViewById <DrawerLayout>(Resource.Id.drawer_layout); drawerOptions = new List <string>(); drawerOptions.Add("Home"); drawerOptions.Add("History"); drawerOptions.Add("Log Out"); drawerOptionsAdapter = new ArrayAdapter <string>(this, Android.Resource.Layout.SimpleListItem1, drawerOptions); daLeftDrawer.Adapter = drawerOptionsAdapter; daLeftDrawer.ItemClick += DaLeftDrawer_ItemClick; daDrawerToggle = new MyActionBarDrawerToggle( this, daDrawerLayout, Resource.String.openDrawer, Resource.String.closeDrawer); SetSupportActionBar(daToolbar); daDrawerLayout.AddDrawerListener(daDrawerToggle); SupportActionBar.SetHomeButtonEnabled(true); SupportActionBar.SetDisplayHomeAsUpEnabled(true); daDrawerToggle.SyncState(); MapFragment mapFragment = (MapFragment)FragmentManager.FindFragmentById(Resource.Id.the_fucking_map); mapFragment.GetMapAsync(this); switchB = FindViewById <Button>(Resource.Id.switch_button); switchB.Enabled = false; distanceText = FindViewById <TextView>(Resource.Id.distance); WorkOutMode = FindViewById <Switch>(Resource.Id.type); //latlonglist = FindViewById<TextView>(Resource.Id.LATLONG); getPos(); switchB.Click += delegate { if (WorkoutInProgress == false) { if (WorkOutMode.Checked == false) { workoutMode = "BIKE"; } else { workoutMode = "RUN"; } getPos(); switchB.SetBackgroundColor(Android.Graphics.Color.Red); daMap.Clear(); polyline = new PolylineOptions().InvokeWidth(20).InvokeColor(Color.Red.ToArgb()); sec = 0; min = 0; hour = 0; distance = 0; timer = new Timer(); timer.Interval = 1000; timer.Elapsed += Timer_Elapsed; timer.Start(); TimerText = FindViewById <TextView>(Resource.Id.timer_text); TimerText.Text = ("0:00:00"); WorkoutInProgress = true; start.SetPosition(new LatLng(position.Latitude, position.Longitude)); start.SetTitle("Start"); daMap.AddMarker(start); polyline.Add(new LatLng(position.Latitude, position.Longitude)); StartListening(); //LatLng latlng = new LatLng(position.Latitude, position.Longitude); //CameraUpdate camera = CameraUpdateFactory.NewLatLngZoom(latlng, 15); //daMap.MoveCamera(camera); switchB.Text = "FINISH WORKOUT"; } else if (WorkoutInProgress == true) { // THIS GETS A STRING OF THE POLYLINE //MAYBE STORE THIS A BLOB IN THE SQL DATABASE String.Join(":", polyline.Points); switchB.SetBackgroundColor(Android.Graphics.Color.ParseColor("#219653")); switchB.Enabled = false; switchB.Text = "START NEW WORKOUT"; WorkoutInProgress = false; timer.Stop(); finish.SetPosition(new LatLng(position.Latitude, position.Longitude)); finish.SetTitle("Finish"); daMap.AddMarker(finish); StopListening(); Android.App.AlertDialog.Builder diaglog = new Android.App.AlertDialog.Builder(this); Android.App.AlertDialog alert = diaglog.Create(); alert.SetCanceledOnTouchOutside(false); alert.SetCancelable(false); alert.SetTitle("Good Work"); alert.SetMessage("Your workout is complete, would you like to record it?"); alert.SetButton("Yes", (c, ev) => { switchB.Enabled = true; SubmitWorkoutToDatabase(); switchB.Text = "START NEW WORKOUT"; //TODO: SEND WORKOUT INFO TO THE DATABASE! alert.Dismiss(); //TODO: save polyine data to new table in the database. }); alert.SetButton2("No", (c, ev) => { switchB.Enabled = true; daMap.Clear(); alert.Dismiss(); sec = 0; min = 0; hour = 0; distance = 0; TimerText.Text = ("0:00:00"); switchB.Text = "START NEW WORKOUT"; }); alert.Show(); } }; }
/// <summary> /// 打印测试 /// </summary> /// <param name="activity"></param> public BluetoothPrinter(Android.App.Activity activity) { this.activity = activity; //获得本地的蓝牙适配器 localAdapter = Android.Bluetooth.BluetoothAdapter.DefaultAdapter; //打开蓝牙设备 if (!localAdapter.IsEnabled) { Android.Content.Intent enableIntent = new Android.Content.Intent(Android.Bluetooth.BluetoothAdapter.ActionRequestEnable); activity.StartActivityForResult(enableIntent, 1); } //静默打开 if (!localAdapter.IsEnabled) { localAdapter.Enable(); } if (!localAdapter.IsEnabled)//用户拒绝打开或系统限制权限 { Android.Widget.Toast.MakeText(activity, "蓝牙未打开", Android.Widget.ToastLength.Short).Show(); return; } //获得已配对的设备列表 bondedDevices = new List<Android.Bluetooth.BluetoothDevice>(localAdapter.BondedDevices); if (bondedDevices.Count <= 0) { Android.Widget.Toast.MakeText(activity, "未找到已配对的蓝牙设备", Android.Widget.ToastLength.Short).Show(); return; } string[] items = new string[bondedDevices.Count]; //查看本地已设置的printer名称 string ls_localPrinterName = baseclass.MyConfig.of_GetMySysSet("printer", "name"); if (!string.IsNullOrEmpty(ls_localPrinterName)) { for (int j = 0; j < bondedDevices.Count; j++) { if(ls_localPrinterName== bondedDevices[j].Name) { as_BluetoothName = ls_localPrinterName; System.Threading.Thread thr2 = new System.Threading.Thread(new System.Threading.ThreadStart(Printer)); thr2.Start(activity); return; } } } //弹窗选择 for (int i = 0; i < bondedDevices.Count; i++) { items[i] = bondedDevices[i].Name; } Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(activity); builder.SetTitle("请选择打印设备:"); builder.SetItems(items, new System.EventHandler<Android.Content.DialogClickEventArgs>(items_click)); builder.SetNegativeButton("取消", delegate { return; }); builder.Show(); }
void ShowGeocodingErrorAlert() { // as long as this activity is not yet destroyed, show an alert indicating the gecooding error if (!IsDestroyed) { //set alert for executing the task var alert = new Android.App.AlertDialog.Builder(this); alert.SetTitle("Geocoding Error"); alert.SetMessage("An error occurred while converting the street address to GPS coordinates."); alert.SetPositiveButton("OK", (senderAlert, args) => { // an empty delegate body, because we just want to close the dialog and not take any other action }); //run the alert in UI thread to display in the screen RunOnUiThread(() => { alert.Show(); }); } }