private async void TryLoginAsync(object sender, EventArgs e) { ProgressDialog progress; progress = new Android.App.ProgressDialog(this); progress.Indeterminate = true; progress.SetProgressStyle(Android.App.ProgressDialogStyle.Spinner); progress.SetMessage("Logging In... Please wait..."); progress.SetCancelable(false); progress.Show(); EditText username = (EditText)FindViewById(Resource.Id.username); EditText password = (EditText)FindViewById(Resource.Id.passwordInput); string user = username.Text.Trim(); string passwordInput = password.Text; if (!await DBHelper.DoesUserExist(user)) { progress.Hide(); Toast.MakeText(ApplicationContext, "Invalid Login", ToastLength.Short).Show(); } else { Users u = await DBHelper.GetUser(user); if (PasswordStorage.VerifyPassword(passwordInput, u.Password)) { edit.PutString("UserID", u.ID); edit.PutString("UserName", u.Username); edit.PutString("LoggedIn", "true"); edit.PutString("Password", passwordInput); edit.Commit(); Toast.MakeText(ApplicationContext, "Success", ToastLength.Short).Show(); if (await DBHelper.IsUserProfileCreated(u.ID)) { //go to main menu UserProfiles up = await DBHelper.GetUsersProfile(u.ID); edit.PutString("FirstName", up.Firstname); edit.PutString("LastName", up.Lastname); edit.Commit(); progress.Hide(); StartActivity(typeof(MainProfileActivity)); } else { progress.Hide(); StartActivity(typeof(SetUpProfileActivity)); } } else { progress.Hide(); Toast.MakeText(ApplicationContext, "Invalid Login", ToastLength.Short).Show(); } } }
private async void TrySave() { ProgressDialog progress; progress = new Android.App.ProgressDialog(this); progress.Indeterminate = true; progress.SetProgressStyle(Android.App.ProgressDialogStyle.Spinner); progress.SetMessage("Logging In... Please wait..."); progress.SetCancelable(false); progress.Show(); CurrentPlatform.Init(); EditText firstName = (EditText)FindViewById(Resource.Id.firstName); EditText lastName = (EditText)FindViewById(Resource.Id.lastName); EditText email = (EditText)FindViewById(Resource.Id.email); EditText phoneNo = (EditText)FindViewById(Resource.Id.phoneNo); Spinner gender = (Spinner)FindViewById(Resource.Id.gender); Spinner county = (Spinner)FindViewById(Resource.Id.county); UserProfiles newUserInfo = new UserProfiles { UsersID = pref.GetString("UserID", "NULL"), Firstname = firstName.Text, Lastname = lastName.Text, Email = email.Text, PhoneNo = phoneNo.Text, Gender = gender.SelectedItem.ToString(), County = county.SelectedItem.ToString() }; MobileService.GetTable <UserProfiles>().InsertAsync(newUserInfo); progress.Hide(); Toast.MakeText(ApplicationContext, "User " + pref.GetString("UserName", "NULL") + " info created!", ToastLength.Short).Show(); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.Login); EditText storeUsernameText = FindViewById <EditText>(Resource.Id.editTextUserName); EditText storePasswordText = FindViewById <EditText>(Resource.Id.textViewPassword); Button btnLoginStore = FindViewById <Button>(Resource.Id.btnLogin); btnLoginStore.Click += async(sender, e) => { progress = new Android.App.ProgressDialog(this); progress.Indeterminate = true; progress.SetProgressStyle(Android.App.ProgressDialogStyle.Spinner); progress.SetMessage("Loading... Please wait..."); progress.SetCancelable(false); progress.Show(); try { LoginEntity loginEntity = new LoginEntity { AuthToken = "", UserNameOREmail = storeUsernameText.Text, PasswordHash = storePasswordText.Text }; JsonValue json = await HttpRequestHelper <LoginEntity> .POSTreq(ServiceTypes.Login, loginEntity); ParseJSON(json); progress.Hide(); } catch (Exception ex) { progress.Dismiss(); } }; }
protected async override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.instructorChapterListToolBar); progress = new Android.App.ProgressDialog(this); progress.Indeterminate = true; progress.SetProgressStyle(Android.App.ProgressDialogStyle.Spinner); progress.SetTitle("Please Wait"); progress.SetMessage("Getting Course Details"); progress.SetCancelable(false); progress.Show(); string inst_id = Intent.GetStringExtra("instructor_id") ?? "Data not available"; language_id = Intent.GetStringExtra("language_id") ?? "Data not available"; inst_name = Intent.GetStringExtra("instructor_name") ?? "Name Not Available"; try { Console.WriteLine("instructor_name : " + inst_name); await Task.Run(() => ChapterList(inst_id, language_id)); await Task.Run(() => CourseInfoFetcher(language_id)); progress.Hide(); //InitData(); FindViews(); chapterListInstructorName.Text = inst_name; } catch (Exception ChapterListError) { Console.WriteLine("ChapterListError : " + ChapterListError); throw; } }
private async Task ConnectToRelay() { bool connected = false; var waitIndicator = new ProgressDialog(this) { Indeterminate = true }; waitIndicator.SetCancelable(false); waitIndicator.SetMessage("Connecting..."); waitIndicator.Show(); try { var prefs = PreferenceManager.GetDefaultSharedPreferences(this); connected = await _remote.Connect(prefs.GetString("RelayServerUrl", ""), prefs.GetString("RemoteGroup", ""), prefs.GetString("HubName", "")); } catch (Exception) { } finally { waitIndicator.Hide(); } Toast.MakeText(this, connected ? "Connected!" : "Unable to connect", ToastLength.Short).Show(); }
protected async override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.ChapterDetailsLayout); string chapt_id = Intent.GetStringExtra("chapter_id") ?? "Data not available"; //string instructor_name = Intent.GetStringExtra("instructor_name") ?? "Name Not Available"; //instructorName.Text = instructor_name; progress = new Android.App.ProgressDialog(this); progress.Indeterminate = true; progress.SetProgressStyle(Android.App.ProgressDialogStyle.Spinner); progress.SetTitle("Please Wait"); progress.SetMessage("Getting Course Details"); progress.SetCancelable(false); progress.Show(); await Task.Run(() => ChapterDetailsFetcher(chapt_id)); progress.Hide(); FindViews(); instructorName.Text = Convert.ToString(instructorChapterList.inst_name); briefDescription.Text = briefDesc; mainContent.Text = chapterContent; toolbarChapterNumber.Text = chapterNumber; toolbarChapterName.Text = chapterName; }
private async void TryRegister(object sender, EventArgs e) { ProgressDialog progress; progress = new Android.App.ProgressDialog(this); progress.Indeterminate = true; progress.SetProgressStyle(Android.App.ProgressDialogStyle.Spinner); progress.SetMessage("Registering... Please wait..."); progress.SetCancelable(false); progress.Show(); EditText username = (EditText)FindViewById(Resource.Id.usernameReg); EditText password = (EditText)FindViewById(Resource.Id.passwordInput1); EditText confirmPassword = (EditText)FindViewById(Resource.Id.passwordInput2); if (password.Text == confirmPassword.Text) { string hashedPassword = PasswordStorage.CreateHash(password.Text); string userName = username.Text.Trim(); //CurrentPlatform.Init(); Users newUser = new Users { Username = userName, Password = hashedPassword }; List <Users> allUsers = await MobileService.GetTable <Users>().ToListAsync(); Users u = allUsers.FirstOrDefault(x => x.Username == newUser.Username); if (u == null) { DBHelper.InsertNewUser(newUser); //MobileService.GetTable<Users>().InsertAsync(newUser); progress.Hide(); Toast.MakeText(ApplicationContext, "User " + newUser.Username + " created! You can now log in!", ToastLength.Short).Show(); StartActivity(typeof(MainActivity)); } else { progress.Hide(); Toast.MakeText(ApplicationContext, "User " + u.Username + " already exists!", ToastLength.Short).Show(); } } else { progress.Hide(); string message = "Passwords don't match."; Toast.MakeText(ApplicationContext, message, ToastLength.Short).Show(); } }
public ChangeStatusPopup (Activity _activity) : base (_activity) { this._activity = _activity; progress = ProgressDialog.Show (_activity, "", "", true); progress.SetContentView(new ProgressBar(_activity)); progress.Hide (); popupNotice = new PopupNoticeInfomation (_activity); }
/// <summary> /// Hides the progress dialog /// </summary> public void Hide() { if (_currentDialog != null) { _currentDialog.Hide(); _currentDialog = null; } }
protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); //RequestWindowFeature (WindowFeatures.NoTitle); progressDialogParent = ProgressDialog.Show (this, "", "", true); progressDialogParent.SetContentView(new ProgressBar(this)); progressDialogParent.Hide (); LayoutInflater.Factory = new TextFactoryManager(); }
public void Show(Context context, string content) { var dialog = new ProgressDialog(context); dialog.SetMessage(content); dialog.SetCancelable(false); dialog.Show(); System.Threading.Thread.Sleep (2000); dialog.Hide (); }
protected async override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.courseDetailToolBar); courseCode = Intent.GetStringExtra("courseCode") ?? "Data not available"; //Defines the settings for progress bar progress = new Android.App.ProgressDialog(this); progress.Indeterminate = true; progress.SetProgressStyle(Android.App.ProgressDialogStyle.Spinner); progress.SetTitle("Please Wait"); progress.SetMessage("Getting Course Details"); progress.SetCancelable(false); progress.Show(); try { await Task.Run(() => CourseListFetcher(courseCode)); await Task.Run(() => InstructorListFetcher(courseCode)); progress.Hide(); //listSample.Add("Getting Instructors"); InitData(); FindViews(); //foreach (var item in listSample) //{ // Console.WriteLine("ListSample : " + item); //} //foreach (var item in userID) //{ // Console.WriteLine("UserIDs : " + item); //} } catch (System.Exception something) { progress.Hide(); Console.WriteLine("Something : " + something); throw; } }
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 updateUIButton = FindViewById<Button> (Resource.Id.StartBackgroundTaskUpdateUI); updateUIButton.Click += delegate { // show the loading overlay on the UI thread progress = ProgressDialog.Show(this, "Loading", "Please Wait...", true); // spin up a new thread to do some long running work using StartNew Task.Factory.StartNew ( // tasks allow you to use the lambda syntax to pass work () => { Console.WriteLine ( "Hello from taskA." ); LongRunningProcess(4); } // ContinueWith allows you to specify an action that runs after the previous thread // completes // // By using TaskScheduler.FromCurrentSyncrhonizationContext, we can make sure that // this task now runs on the original calling thread, in this case the UI thread // so that any UI updates are safe. in this example, we want to hide our overlay, // but we don't want to update the UI from a background thread. ).ContinueWith ( t => { if (progress != null) progress.Hide(); Console.WriteLine ( "Finished, hiding our loading overlay from the UI thread." ); }, TaskScheduler.FromCurrentSynchronizationContext() ); // Output a message from the original thread. note that this executes before // the background thread has finished. Console.WriteLine("Hello from the calling thread."); }; // the simplest way to start background tasks is to use create a Task, assign // some work to it, and call start. noupdateUIButton = FindViewById<Button> (Resource.Id.StartBackgroundTaskNoUpdate); noupdateUIButton.Click += delegate { var TaskA = new Task ( () => { LongRunningProcess (5); } ); var TaskB = new Task ( () => { LongRunningProcess (4); } ); TaskA.Start (); TaskB.Start (); }; }
protected override async void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.CrueltyTypes); _loadingDialog = DialogManager.ShowLoadingDialog(this, "Retrieving Cruelty Types"); _crueltySpotCategoriesList = FindViewById<ListView>(Resource.Id.CrueltyTypes); _crueltySpotCategoriesList.ItemClick += (sender, e) => { var crueltySpotCategory = _crueltySpotCategories[e.Position]; //var intent = new Intent(this, typeof(ReportCrueltyFragment)); var intent = new Intent(this, typeof(IntroActivity)); intent.PutExtra("tab", "report"); var crueltyType = new CrueltyType(); crueltyType.Id = crueltySpotCategory.ObjectId; crueltyType.Name = crueltySpotCategory.Name; CrueltyReport _crueltyReport = ((AfaApplication)ApplicationContext).CrueltyReport; _crueltyReport.CrueltyType = crueltyType; StartActivity(intent); }; var crueltySpotCategoriesService = new CrueltySpotCategoriesService(); var crueltySpotCategories = await crueltySpotCategoriesService.GetAllAsync(); RunOnUiThread(() => { _crueltySpotCategories = crueltySpotCategories; _crueltySpotCategoriesList.Adapter = new CrueltyTypesAdapter(this, _crueltySpotCategories); _loadingDialog.Hide(); }); /*SetContentView (Resource.Layout.Test); var textView = FindViewById<TextView> (Resource.Id.textView1); var query = new ParseQuery<CrueltySpotCategory> (); var result = await query.FindAsync (); var output = ""; foreach (var crueltySpotCategory in result) { output += "Name: " + crueltySpotCategory.Name; output += "\n"; output += "Description: " + crueltySpotCategory.Description; output += "\n"; output += "Icon: " + crueltySpotCategory.IconName; output += "\n"; } RunOnUiThread (() => { textView.Text = output; });*/ }
private void ShowProgressDialog(ProgressDialog progressDialog, string message, bool show) { if (show) { progressDialog.Indeterminate = true; progressDialog.SetProgressStyle(ProgressDialogStyle.Spinner); progressDialog.SetMessage(message); progressDialog.SetCancelable(false); progressDialog.Show(); } else progressDialog.Hide(); }
public async void button_Click(object sender, EventArgs e) { MSCognitiveServices cognitiveServices = new MSCognitiveServices(); MyClass c = new MyClass(); string path = string.Empty; string albumPath = string.Empty; Stream data = await c.LoadPhoto(path, albumPath); progress = new Android.App.ProgressDialog(this); progress.SetProgressStyle(Android.App.ProgressDialogStyle.Spinner); progress.SetMessage("Loading... Please wait..."); progress.SetCancelable(false); progress.Show(); MemoryStream faceStream = new MemoryStream(); data.CopyTo(faceStream); data.Seek(0, SeekOrigin.Begin); MemoryStream emotionStream = new MemoryStream(); data.CopyTo(emotionStream); data.Seek(0, SeekOrigin.Begin); faceStream.Seek(0, SeekOrigin.Begin); emotionStream.Seek(0, SeekOrigin.Begin); Dictionary <string, string> faceProperties = await cognitiveServices.GetFaceProperties(faceStream); Dictionary <string, float> emotionProperties = await cognitiveServices.GetEmotionProperties(emotionStream); var et_faceText = FindViewById <TextView>(Resource.Id.et_faceText); et_faceText.Text = string.Format("Gender: {0} Age: {1}", faceProperties["Gender"], faceProperties["Age"]); var et_emotionText = FindViewById <TextView>(Resource.Id.et_emotionText); var et_emotionText_1 = FindViewById <TextView>(Resource.Id.et_emotionText_1); var et_emotionText_2 = FindViewById <TextView>(Resource.Id.et_emotionText_2); var et_emotionText_3 = FindViewById <TextView>(Resource.Id.et_emotionText_3); et_emotionText.Text = string.Format("Anger: {0}% Contempt:{1}% ", emotionProperties["Anger"], emotionProperties["Contempt"]); et_emotionText_1.Text = string.Format("Fear: {0}% Happiness:{1}% ", emotionProperties["Fear"], emotionProperties["Happiness"]); et_emotionText_2.Text = string.Format("Sadness: {0}% Surprise:{1}%", emotionProperties["Sadness"], emotionProperties["Surprise"]); et_emotionText_3.Text = string.Format("Disgust:{0}% Neutral:{1}%", emotionProperties["Disgust"], emotionProperties["Neutral"]); var imageView = FindViewById <ImageView>(Resource.Id.myImageView); using (var stream = data) { var bitmap = BitmapFactory.DecodeStream(stream); imageView.SetImageBitmap(bitmap); // do stuff with bitmap } progress.Hide(); faceStream.Close(); emotionStream.Close(); }
/// <summary>Handles connecting to the server and starting a game.</summary> void onConnecToServer() { EditText serverText = FindViewById<EditText>(Resource.Id.ServerText); EditText userText = FindViewById<EditText>(Resource.Id.UserText); EditText oppText = FindViewById<EditText> (Resource.Id.OpponentText); serverAddr= serverText.Text; uname = userText.Text; sockInstance = new SocketSingleton (serverAddr, 8080); SocketSingleton.initSingleton (); // On "Connect" button click, try to connect to a server. progress = ProgressDialog.Show(this, "Loading", "Please Wait...", true); if (progress != null) progress.Hide(); if(!sockInstance.isConnected()){ setError("Couldn't connect"); }else{ setError("Connected"); Intent intent = new Intent(this,typeof(ChessActivity)); ChessActions.socket = sockInstance; ChessActivity.username = userText.Text; ChessActivity.opponent = oppText.Text; ChessActivity.actions = new ChessActions (ChessActivity.username, ChessActivity.opponent); ChessActivity.actions.login (); string read = SocketSingleton.getInstance().getIn().ReadLine(); if (read == "TRUE"){ if (ChessActivity.actions.joinGame()) { ChessActivity.myTurn = false; ChessActivity.newGame = false; StartActivity(intent); } else { if(ChessActivity.actions.newGame ()) { ChessActivity.myTurn = true; ChessActivity.newGame = true; StartActivity(intent); } else setError("Username already in use for a game."); } } else { setError("Could not use username to login."); } } }
public BackgroundJob(MonitoredActivity activity, Action job, ProgressDialog progressDialog, Handler handler) { this.activity = activity; this.progressDialog = progressDialog; this.job = job; this.handler = handler; activity.Destroying += (sender, e) => { // We get here only when the onDestroyed being called before // the cleanupRunner. So, run it now and remove it from the queue cleanUp(); handler.RemoveCallbacks(cleanUp); }; activity.Stopping += (sender, e) =>progressDialog.Hide(); activity.Starting += (sender, e) => progressDialog.Show(); }
public void btnLoginOnClick(Object sender, EventArgs e, String uname, String passwd) { //Wenn die Logik zugreift und Navision/Windows den Login genehmigt, gehe weiter zur ActOverview Activity.RunOnUiThread(() => { progress = ProgressDialog.Show(Activity, "Processing...", "Trying to connect and logging into Server", true); service._Service.AuthenticationCompleted += delegate { progress.Hide(); }; }); try { if (service.proofUser(uname, passwd)) { //Übertrage erarbeitete Daten an die GUI Activity.RunOnUiThread(() => { user = uname; pwd = passwd; progress.Dismiss(); }); } else { Activity.RunOnUiThread(() => { progress.Hide(); Toast.MakeText(Activity, "Invalid Credentials", ToastLength.Short).Show(); }); } } catch (Exception err) { Activity.RunOnUiThread(() => { progress.Hide(); Toast.MakeText(Activity, err.Message, ToastLength.Short).Show(); }); } }
private async Task Initialize() { if (Initialized) return; Initialized = true; // create binding manager Bindings = new BindingManager(this); //ErrorText = FindViewById<TextView>(Resource.Id.ErrorText); var saveButton = FindViewById<Button>(Resource.Id.SaveButton); saveButton.Click += SaveButton_Click; var cancelButton = FindViewById<Button>(Resource.Id.CancelButton); cancelButton.Click += CancelButton_Click; var deleteButton = FindViewById<Button>(Resource.Id.DeleteButton); deleteButton.Click += DeleteButton_Click; var dialog = new ProgressDialog(this); dialog.SetMessage(Resources.GetString(Resource.String.Loading)); dialog.SetCancelable(false); dialog.Show(); try { var customerEdit = await Library.CustomerEdit.GetCustomerEditAsync(1); InitializeBindings(customerEdit); } catch (Exception ex) { var alert = new AlertDialog.Builder(this); alert.SetMessage(string.Format(Resources.GetString(Resource.String.Error), ex.Message)); alert.Show(); } finally { dialog.Hide(); } }
public void btnLoginOnClick(Object sender, EventArgs e, String uname, String pwd) { //Wenn die Logik zugreift und Navision/Windows den Login genehmigt, gehe weiter zur ActOverview RunOnUiThread(() => { progress = ProgressDialog.Show(this, "Processing...", "Trying to connect and logging into Server", true); service._Service.AuthenticationCompleted += delegate { progress.Hide(); }; }); try{ if (service.proofUser(tfLogin.Text,tfPwd.Text)){ //Übertrage erarbeitete Daten an die GUI RunOnUiThread(() => { var overview = new Intent(this, typeof(Dashboard)); overview.PutExtra("username", this.tfLogin.Text); overview.PutExtra("password", this.tfPwd.Text); //Starte die neue Oberfläche StartActivity(overview); progress.Dismiss(); }); } else{ RunOnUiThread(() => { progress.Hide(); Toast.MakeText(this,"Invalid Credentials",ToastLength.Short).Show(); }); } } catch(Exception err){ RunOnUiThread(() => { progress.Hide(); Toast.MakeText(this, err.Message, ToastLength.Short).Show(); }); } }
protected async override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.CrueltySpot); //_loadingDialog = LoadingDialogManager.ShowLoadingDialog(this); _loadingDialog = DialogManager.ShowLoadingDialog(this, "Retrieving Cruelty Spot Details"); // Event Handlers IssueButton.Click += (sender, args) => SetViewState(CrueltySpotViewState.TheIssue); TakeActionButton.Click += (sender, args) => SetViewState(CrueltySpotViewState.TakeAction); var crueltySpotId = Intent.GetStringExtra(AppConstants.CrueltySpotIdKey); var crueltySpotsService = new CrueltySpotsService(); _crueltySpot = await crueltySpotsService.GetByIdAsync(crueltySpotId, true); RunOnUiThread(() => { var formattedAddress = String.Format("{0}\n{1}", _crueltySpot.Address, _crueltySpot.CityStateAndZip); FindViewById<TextView>(Resource.Id.Name).Text = _crueltySpot.Name; FindViewById<TextView>(Resource.Id.Address).Text = formattedAddress; var resourceId = ResourceHelper.GetDrawableResourceId(this, _crueltySpot.CrueltySpotCategory.IconName, ResourceSize.Medium); FindViewById<ImageView>(Resource.Id.CrueltyTypeImage).SetImageResource(resourceId); SetViewState(CrueltySpotViewState.TakeAction); _loadingDialog.Hide(); var showSuccessAddedAlert = Intent.GetBooleanExtra(AppConstants.ShowCrueltySpotAddedSuccessfullyKey, false); if (showSuccessAddedAlert) { DialogManager.ShowAlertDialog(this, "Thanks!", "...for reporting animal cruelty here. This location is now on the map so others can take action!", true); } FindViewById<TextView>(Resource.Id.issueName).Text = _crueltySpot.CrueltySpotCategory.Name; FindViewById<TextView>(Resource.Id.issueDescription).Text = _crueltySpot.CrueltySpotCategory.Description; }); }
private async void FetchBookingData() { progressDialog = new ProgressDialog(this); await FetchWorkshopBookingData(); await FetchSessionBookingData(); progressDialog.Hide(); // Set up the views _Landing = new LandingFragment(sessionBookingData, workshopBookingData, studentData); _Future = new FutureBookingsFragment(sessionBookingData, workshopBookingData, studentData); _Past = new PastBookingsFragment(sessionBookingData, workshopBookingData, studentData); // Set up the landing page SetView(Resource.Id.fragmentContainer, _Landing, false); string helloUser = GetString(Resource.String.hello) + " " + studentData.attributes.studentID + "!"; TextView helloUserText = FindViewById<TextView>(Resource.Id.textHelloUser); helloUserText.Text = helloUser; }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.RegisterActivity); Toolbar toolbar = (Toolbar)FindViewById(Resource.Id.toolbar); SetSupportActionBar(toolbar); ImageView emailImage = (ImageView)FindViewById(Resource.Id.imageview_email); ImageView usernameImage = (ImageView)FindViewById(Resource.Id.imageview_username); ImageView passwordImage = (ImageView)FindViewById(Resource.Id.imageview_password); ImageView confirmPasswordImage = (ImageView)FindViewById(Resource.Id.imageview_confirmpassword); EditText emailfield = (EditText)FindViewById(Resource.Id.editText_email); emailfield.AfterTextChanged += (sender, e) => { if (StringUtils.IsValidEmail(emailfield.Text)) { emailImage.Visibility = ViewStates.Visible; emailImage.Tag = 1; emailImage.SetImageResource(Resource.Drawable.check);//check } else { emailImage.Visibility = ViewStates.Visible; emailImage.Tag = 0; emailImage.SetImageResource(Resource.Drawable.x);//x } }; EditText usernamefield = (EditText)FindViewById(Resource.Id.editText_username); usernamefield.AfterTextChanged += (sender, e) => { if (StringUtils.IsValidUsername(usernamefield.Text)) { usernameImage.Visibility = ViewStates.Visible; usernameImage.Tag = 1; usernameImage.SetImageResource(Resource.Drawable.check);//check } else { usernameImage.Visibility = ViewStates.Visible; usernameImage.Tag = 0; usernameImage.SetImageResource(Resource.Drawable.x);//x } }; EditText passwordfield = (EditText)FindViewById(Resource.Id.editText_password); passwordfield.AfterTextChanged += (sender, e) => { if (StringUtils.IsValidPassword(passwordfield.Text)) { passwordImage.Visibility = ViewStates.Visible; passwordImage.Tag = 1; passwordImage.SetImageResource(Resource.Drawable.check);//check } else { passwordImage.Visibility = ViewStates.Visible; passwordImage.Tag = 0; passwordImage.SetImageResource(Resource.Drawable.x);//x } }; EditText confirmpasswordfield = (EditText)FindViewById(Resource.Id.editText_confirmpassword); confirmpasswordfield.AfterTextChanged += (sender, e) => { if (StringUtils.IsValidPassword(confirmpasswordfield.Text) && confirmpasswordfield.Text == passwordfield.Text) { confirmPasswordImage.Visibility = ViewStates.Visible; confirmPasswordImage.Tag = 1; confirmPasswordImage.SetImageResource(Resource.Drawable.check);//check } else { confirmPasswordImage.Visibility = ViewStates.Visible; confirmPasswordImage.Tag = 0; confirmPasswordImage.SetImageResource(Resource.Drawable.x);//x } }; Button registerButton = (Button)FindViewById(Resource.Id.button_register); registerButton.Click += async (sender, e) => { if (emailImage.Tag.ToString() != "1" || usernameImage.Tag.ToString() != "1" || passwordImage.Tag.ToString() != "1" || confirmPasswordImage.Tag.ToString() != "1") { return; } string username = StringUtils.TrimWhiteSpaceAndNewLine(usernamefield.Text); string password = StringUtils.TrimWhiteSpaceAndNewLine(passwordfield.Text); string email = StringUtils.TrimWhiteSpaceAndNewLine(emailfield.Text); ProgressDialog progress = new ProgressDialog(this); progress.Indeterminate = true; progress.SetProgressStyle(ProgressDialogStyle.Spinner); progress.SetMessage(Strings.signing_in); progress.SetCancelable(false); progress.Show(); try { bool result = await TenServices.Register(username, password, email); progress.Hide(); if (!result) { Android.Support.V7.App.AlertDialog.Builder alert = new Android.Support.V7.App.AlertDialog.Builder(this); alert.SetTitle(Strings.invalid_login); alert.SetMessage(Strings.invalid_login); alert.SetPositiveButton(Strings.ok, (senderAlert, args) => { }); RunOnUiThread(() => { alert.Show(); }); return; } ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(this); ISharedPreferencesEditor editor = prefs.Edit(); editor.PutString("username", username); editor.PutString("password", password); editor.Apply(); StartActivity(typeof(TabHostActivity)); SetResult(Result.Ok); Finish(); } catch (RESTError error) { progress.Hide(); if (error.StatusCode == 400 || error.StatusCode == -1) { Android.Support.V7.App.AlertDialog.Builder alert = new Android.Support.V7.App.AlertDialog.Builder(this); alert.SetTitle(Strings.invalid_login); alert.SetMessage(error.Message); alert.SetPositiveButton(Strings.ok, (senderAlert, args) => { }); RunOnUiThread(() => { alert.Show(); }); } } }; FindViewById(Resource.Id.parentView).Click += (sender, e) => { ViewUtils.HideKeyboard(this, emailfield); ViewUtils.HideKeyboard(this, usernamefield); ViewUtils.HideKeyboard(this, passwordfield); ViewUtils.HideKeyboard(this, confirmpasswordfield); }; }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.CreateResponsesLayout); var responses = FindViewById<LinearLayout>(Resource.Id.ResponsesLinearLayout); var questionTitle = FindViewById<TextView>(Resource.Id.QuestionText); var createPollButton = FindViewById<Button>(Resource.Id.CreateResponsesCreatePollButton); var response1 = FindViewById<EditText>(Resource.Id.Response1); var response2 = FindViewById<EditText>(Resource.Id.Response2); var response3 = FindViewById<EditText>(Resource.Id.Response3); var response4 = FindViewById<EditText>(Resource.Id.Response4); var question = Intent.GetStringExtra("Question"); var numberOfResponses = Intent.GetIntExtra("NumberOfResponses", 2); questionTitle.Text = question; createPollButton.Click += async (sender, e) => { // starts progress spinner when inserting poll into database var progressDialog = new ProgressDialog(this); progressDialog.Show(); string choices = ""; string votes = ""; // enters in the correct number of votes for each response and choices if (numberOfResponses == 2) { choices = response1.Text + "," + response2.Text; votes = "0,0"; } if (numberOfResponses == 3) { choices = response1.Text + "," + response2.Text + "," + response3.Text; votes = "0,0,0"; } if (numberOfResponses == 4) { choices = response1.Text + "," + response2.Text + "," + response3.Text + "," + response4.Text; votes = "0,0,0,0"; } try { // trys to insert new Poll into database if it succeeds the activity finishes await VotingService.MobileService.GetTable<Poll>().InsertAsync(new Poll { Question = questionTitle.Text, Choices = choices, Votes = votes, }); } catch (Exception exc) { // shows an error dialog if submitting the Poll fails var errorDialog = new AlertDialog.Builder(this).SetTitle("Oops!").SetMessage("Something went wrong " + exc.ToString()).SetPositiveButton("Okay", (sender1, e1) => { }).Create(); errorDialog.Show(); } // stops progress spinner when done progressDialog.Hide(); Finish(); }; // displays the correct number of response fields based on the number chosen in previous activity switch (numberOfResponses) { case 2: { response1.Visibility = ViewStates.Visible; response2.Visibility = ViewStates.Visible; break; } case 3: { response1.Visibility = ViewStates.Visible; response2.Visibility = ViewStates.Visible; response3.Visibility = ViewStates.Visible; break; } case 4: { response1.Visibility = ViewStates.Visible; response2.Visibility = ViewStates.Visible; response3.Visibility = ViewStates.Visible; response4.Visibility = ViewStates.Visible; break; } } }
private void OnCompleteAsnycSubmit(Task<List<string>> task, ProgressDialog dialog) { RunOnUiThread( () => { dialog.Hide(); if (task.IsFaulted) { var errorDialog = new AlertDialog.Builder(this); errorDialog.SetTitle("Error"); errorDialog.SetMessage(task.Exception.InnerExceptions.First().Message); errorDialog.Create() .Show(); } else if (task.IsCompleted) { var question = task.Result[0]; var answer = task.Result[1]; var resultIntent = new Intent(this, typeof(ResultScreen)); resultIntent.PutExtra(ResultScreen.QuestionKey, question); resultIntent.PutExtra(ResultScreen.AnswerKey, answer); StartActivity(resultIntent); } }); }
protected async override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); //drawerLayout = FindViewById<DrawerLayout>(Resource.Id.drawer_layout); //LayoutInflater inflater = (LayoutInflater)this.GetSystemService(Context.LayoutInflaterService); //View contentView = inflater.Inflate(Resource.Layout.Product, null, false); //drawerLayout.AddView(contentView); SetContentView(Resource.Layout.Product); RecieptDTO user = JsonConvert.DeserializeObject <RecieptDTO>(Intent.GetStringExtra("RecieptData")); //var extras = Intent.GetParcelableExtra("RecieptData") ?? String.Empty; string textRecieptName = user.Name; textRecieptID = user.RecieptID.ToString(); TextView txtRecieptName = FindViewById <TextView>(Resource.Id.recieptTxt); TextView txtProductName = FindViewById <TextView>(Resource.Id.editProductName); TextView txtProductQuantity = FindViewById <TextView>(Resource.Id.editProductQuantity); txtRecieptName.Text = textRecieptName; SessionHelper sessionHelper = new SessionHelper(this); string Username = sessionHelper.GetSessionKey(SessionKeys.SESSION_USERNAME_KEY); string UserID = sessionHelper.GetSessionKey(SessionKeys.SESSION_USERID_KEY); string AuthToken = sessionHelper.GetSessionKey(SessionKeys.SESSION_TOKEN_KEY); ImageButton btnAddProduct = FindViewById <ImageButton>(Resource.Id.btnAddProduct); JsonValue jsonProduct = await HttpRequestHelper <ProductEntity> .GetRequest(ServiceTypes.GetProducts, "/" + AuthToken + "/" + textRecieptID); ParseRecieptJSON(jsonProduct); Button btnSendReceipt = FindViewById <Button>(Resource.Id.btnSendReceipt); btnSendReceipt.Click += BtnSendReceipt_Click; btnAddProduct.Click += async(sender, e) => { progress = new Android.App.ProgressDialog(this); progress.Indeterminate = true; progress.SetProgressStyle(Android.App.ProgressDialogStyle.Spinner); progress.SetMessage("Adding product... Please wait..."); progress.SetCancelable(false); progress.Show(); try { ProductDTO productDTO = new ProductDTO(); productDTO.AddedOn = DateTime.Now.ToString(); productDTO.Name = txtProductName.Text; productDTO.Quantity = txtProductQuantity.Text; productDTO.RecieptID = Convert.ToInt32(textRecieptID); ProductEntity productEntity = new ProductEntity { AuthToken = AuthToken, productInfo = productDTO }; JsonValue json = await HttpRequestHelper <ProductEntity> .POSTreq(ServiceTypes.AddProduct, productEntity); ParseJSON(json); JsonValue jsonProduct1 = await HttpRequestHelper <ProductEntity> .GetRequest(ServiceTypes.GetProducts, "/" + AuthToken + "/" + textRecieptID); ParseRecieptJSON(jsonProduct1); progress.Hide(); } catch (Exception ex) { } }; }
protected override void OnCreate(Bundle savedInstanceState) { _context = this; //first check if there are permsions to access files ext bool checks = true; #region << Check For Permisions >> // Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) || ActivityCompat.CheckSelfPermission(this, Manifest.Permission.AccessWifiState) || Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this, Manifest.Permission.Internet) if (Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this, Manifest.Permission.Internet) != (int)Permission.Granted) { if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.Internet)) { ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.Internet, Manifest.Permission.Internet }, 1); // })).Show(); } while (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.Internet) != (int)Permission.Granted) { Thread.Sleep(100); } } if (Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessWifiState) != (int)Permission.Granted) { if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.AccessWifiState)) { ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.AccessWifiState, Manifest.Permission.AccessWifiState }, 1); // })).Show(); } while (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.AccessWifiState) != (int)Permission.Granted) { Thread.Sleep(100); } } if (Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessNetworkState) != (int)Permission.Granted) { if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.AccessNetworkState)) { ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.AccessNetworkState, Manifest.Permission.AccessNetworkState }, 1); // })).Show(); } while (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.AccessNetworkState) != (int)Permission.Granted) { Thread.Sleep(100); } } if (Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) != (int)Permission.Granted) { // Camera permission has not been granted RequestReadWirtePermission(); while (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) != (int)Permission.Granted) { Thread.Sleep(100); } } #endregion << Check For Permisions >> base.OnCreate(savedInstanceState); //request the app to be full screen RequestWindowFeature(WindowFeatures.NoTitle); this.Window.ClearFlags(Android.Views.WindowManagerFlags.Fullscreen); //to hide Rebex.Licensing.Key = "==AnKxIZnJ2NXyRRk/MrXLh5vsLbImP/JhMGERReY23qIk=="; SetContentView(Resource.Layout.installer); refreshui(); retrieveset(); LoadPkg.Click += async delegate { try { String[] types = new String[] { ".pkg" }; FileData fileData = await CrossFilePicker.Current.PickFile(types); if (fileData == null) { return; // user canceled file picking } //com.android.externalstorage.documents System.Console.WriteLine("File name " + fileData.FileName); new Thread(new ThreadStart(delegate { RunOnUiThread(() => { progress = new ProgressDialog(this); progress.Indeterminate = true; progress.SetProgressStyle(Android.App.ProgressDialogStyle.Spinner); progress.SetMessage("Loading... Getting Path..."); progress.SetCancelable(false); progress.Show(); }); FindFileByName(fileData.FileName); System.Console.WriteLine("Found File, Path= " + PKGLocation); RunOnUiThread(() => { progress.Hide(); try { var pkgfile = PS4_Tools.PKG.SceneRelated.Read_PKG(PKGLocation); ImageView pbPkg = FindViewById <ImageView>(Resource.Id.PKGIcon); pbPkg.SetImageBitmap(BytesToBitmap(pkgfile.Icon)); TextView lblPackageInfo = FindViewById <TextView>(Resource.Id.txtPKGInfo); lblPackageInfo.Text = pkgfile.PS4_Title + "\n" + pkgfile.PKG_Type.ToString() + "\n" + pkgfile.Param.TitleID; } catch (Exception ex) { MessageBox.Show("Invaild Package! or Path\n\n Location: " + PKGLocation); // MessageBox.Show("Exception choosing file: " + ex.ToString() + " " + PKGLocation); } }); })).Start(); } catch (Exception ex) { MessageBox.Show("Invaild Package! or Path\n\n Location: " + PKGLocation); // MessageBox.Show("Exception choosing file: " + ex.ToString() + " " + PKGLocation); } }; set.Click += async delegate { try { PKGLocation = manpath.Text; var pkgfile = PS4_Tools.PKG.SceneRelated.Read_PKG(PKGLocation); ImageView pbPkg = FindViewById <ImageView>(Resource.Id.PKGIcon); pbPkg.SetImageBitmap(BytesToBitmap(pkgfile.Icon)); TextView lblPackageInfo = FindViewById <TextView>(Resource.Id.txtPKGInfo); lblPackageInfo.Text = pkgfile.PS4_Title + "\n" + pkgfile.PKG_Type.ToString() + "\n" + pkgfile.Param.TitleID; } catch (Exception ex) { MessageBox.Show("Invaild Package! or Path\n\n Location: " + PKGLocation); // MessageBox.Show("Exception choosing file: " + ex.ToString() + " " + PKGLocation); } }; SendPayloadBtn.Click += delegate { new Thread(new ThreadStart(delegate { using (Ftp client = new Ftp()) { Rebex.Licensing.Key = "==AnKxIZnJ2NXyRRk/MrXLh5vsLbImP/JhMGERReY23qIk=="; try { // TextView IPAddressTextBox = FindViewById<TextView>(Resource.Id.IPAddressTextBox); if (IPAddressTextBox.Text == "") { RunOnUiThread(() => { MessageBox.Show("Enter an IP Address"); }); return; } saveset(); // string paths = GetPathToImage("sa"); // connect and login to the FTP client.Connect(IPAddressTextBox.Text); //TextView FTPPassword = FindViewById<TextView>(Resource.Id.FTPPassword); //TextView FTPUsername = FindViewById<TextView>(Resource.Id.FTPUsername); if (FTPPassword.Text == "" && FTPUsername.Text == "") { client.Login("anonymous", "DONT-LOOK@MYCODE"); } else { client.Login(FTPUsername.Text, FTPPassword.Text); } client.Traversing += Traversing; client.TransferProgressChanged += TransferProgressChanged; client.DeleteProgressChanged += DeleteProgressChanged; client.ProblemDetected += ProblemDetected; if (!client.DirectoryExists(@"/user/app/")) { client.CreateDirectory(@"/user/app/"); } if (client.FileExists(@"/user/app/temp.pkg")) { client.Delete(@"/user/app/temp.pkg", TraversalMode.NonRecursive); } client.ChangeDirectory(@"/user/app/"); client.PutFile(PKGLocation, "temp.pkg"); try { client.SendCommand("installpkg"); } catch (Exception ex) { SetTex("installpkg Failed\n Are you sure your using Inifinx?"); } SetTex("Package Sent"); } catch (Exception ex) { RunOnUiThread(() => { MessageBox.Show(ex.Message); }); } RunOnUiThread(() => { Toast.MakeText(Application.Context, "Package Sent!", ToastLength.Short).Show(); }); client.Disconnect(); } })).Start(); }; /* } * else * { * SendPayloadBtn.Visibility = ViewStates.Invisible; * LoadPkg.Visibility = ViewStates.Invisible; * }*/ }
private void ShowProgressDialog(ProgressDialog progressDialog, bool show) { if (show) { progressDialog.Indeterminate = true; progressDialog.SetProgressStyle(ProgressDialogStyle.Spinner); progressDialog.SetMessage("Logging in. Please wait..."); progressDialog.SetCancelable(false); progressDialog.Show(); } else progressDialog.Hide(); }
/// <summary> /// Pulls today's featured wikipedia article /// </summary> private async void LoadWikiInfo() { ProgressDialog dialog = new ProgressDialog(this); dialog.SetTitle("Please Wait..."); dialog.SetMessage("Downloading today's content!"); dialog.SetCancelable(false); dialog.Show(); wiki = await AndroidUtils.GetTodaysWiki(this); if (wikiImage != null && wiki.imageURL != null) { if (!File.Exists(wiki.imageURL)) { // Force update, file has been deleted somehow wiki = await ServerData.FetchWikiData(AndroidUtils.DecodeHTML); } wikiImage.SetImageURI(Android.Net.Uri.FromFile(new Java.IO.File(wiki.imageURL))); wikiImage.Visibility = ViewStates.Visible; } else if(wikiImage != null) { wikiImage.Visibility = ViewStates.Gone; } string[] sentences = wiki.content.Split(new[] {". "}, StringSplitOptions.RemoveEmptyEntries); string finalText = ""; int charTarget = 400; foreach (string sentence in sentences) { if (finalText.Length < charTarget && finalText.Length + sentence.Length < 570) { finalText += sentence + ". "; } else { break; } } wikiText.Text = finalText; // If it's longer than expected, reduce the text size! if (finalText.Length > 520) { if ((Resources.Configuration.ScreenLayout & Android.Content.Res.ScreenLayout.SizeMask) <= Android.Content.Res.ScreenLayout.SizeNormal) { wikiText.SetTextSize(Android.Util.ComplexUnitType.Sp, 15); } else { wikiText.SetTextSize(Android.Util.ComplexUnitType.Sp, 19); } } SwitchMode(ServerData.TaskType.Loudness); dialog.Hide(); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Create your application here try { SetContentView(Resource.Layout.Login_Content); ActionBar.Hide(); //Create Database db = new Database(); db.createDatabaseInfo(); //Load Data LoadData(); var progress = new Android.App.ProgressDialog(this); progress.Indeterminate = true; progress.SetProgressStyle(Android.App.ProgressDialogStyle.Spinner); progress.SetMessage("Loading ..."); progress.SetCancelable(true); progress.Hide(); var done = FindViewById <Button>(Resource.Id.done); var namer = FindViewById <EditText>(Resource.Id.namer); var signup = FindViewById <Button>(Resource.Id.signup); var back = FindViewById <ImageButton>(Resource.Id.back); var passworder = FindViewById <EditText>(Resource.Id.passworder); if (namer.Text.Length == 0 || passworder.Text.Length == 0) { done.SetBackgroundResource(Resource.Drawable.signInButtonLight); } namer.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) => { if (namer.Text.Length > 0) { done.SetBackgroundResource(Resource.Drawable.signInButton); } else { done.SetBackgroundResource(Resource.Drawable.signInButtonLight); } }; back.Click += delegate { var intent = new Intent(this, typeof(IntroActivity)); var bundle1 = new Bundle(); intent.PutExtras(bundle1); this.StartActivity(intent); }; signup.Click += delegate { var intent = new Intent(this, typeof(edit_profile_activity)); var bundle1 = new Bundle(); bundle1.PutString("comefrom", "login"); intent.PutExtras(bundle1); this.StartActivity(intent); }; done.Click += async delegate { progress.Show(); try { string password = passworder.Text; //password = password.Trim(); string name = namer.Text; //name = name.Trim(); /* * ASCIIEncoding encoding = new ASCIIEncoding(); * //string postData = "username" + user + "&password" + password; * * * string info = "{\"name\""+":" + '"'+name+'"'+"}"; * byte[] data = Encoding.ASCII.GetBytes(info); * * WebRequest request = WebRequest.Create("http://51.140.38.46:8080/edit_profile_login"); * request.Method = "POST"; * request.ContentType = "application/x-www-form-urlencoded"; * request.ContentLength = data.Length; * * using (Stream stream = request.GetRequestStream()) * { * stream.Write(data, 0, data.Length); * } * * string responseContent = null; * * using (WebResponse response = request.GetResponse()) * { * using (Stream stream = response.GetResponseStream()) * { * using (StreamReader sr99 = new StreamReader(stream)) * { * responseContent = sr99.ReadToEnd(); * * Toast resp = Toast.MakeText(this, responseContent, ToastLength.Long); * resp.Show(); * * * } * } * } * * if (responseContent == "Welcome back") * { * * * var intent = new Intent(this, typeof(Profile)); * * var bundle1 = new Bundle(); * bundle1.PutString("namerText", name); * intent.PutExtras(bundle1); * this.StartActivity(intent); * * }/* * else { progress.Hide(); }; * * }*/ try { string test = listSource[0].Name; if (name == listSource[0].Name & password == listSource[0].Password) { try { Toast resp = Toast.MakeText(this, "Welcome Back", ToastLength.Short); resp.Show(); var intent = new Intent(this, typeof(ProgramHome)); progress.Hide(); this.StartActivity(intent); } catch (Exception e) { System.Exception myException = e; Toast error = Toast.MakeText(this, e.Message, ToastLength.Short); error.Show(); } } else { try { Toast resp = Toast.MakeText(this, "Username: "******", Password: "******"Create an Account", ToastLength.Short); resp.Show(); progress.Hide(); } /* * else if (name != listSource[0].Name) * { * Toast resp = Toast.MakeText(this, "Unknown Username", ToastLength.Short); * resp.Show(); * } * else if (password != listSource[0].Password) * { * Toast resp = Toast.MakeText(this, "Unknown Password", ToastLength.Short); * resp.Show(); * }*/ } catch (Exception e) { System.Exception myException = e; Toast error = Toast.MakeText(this, e.Message, ToastLength.Short); error.Show(); } }; } catch (Exception e) { System.Exception myException = e; Toast error = Toast.MakeText(this, e.Message, ToastLength.Short); error.Show(); } }
private async void SaveButton_Click(object sender, EventArgs ea) { var dialog = new ProgressDialog(this); dialog.SetMessage(Resources.GetString(Resource.String.Saving)); dialog.SetCancelable(false); dialog.Show(); try { Bindings.UpdateSourceForLastView(); this.Model.ApplyEdit(); var returnModel = await this.Model.SaveAsync(); InitializeBindings(returnModel); } catch (Exception ex) { var alert = new AlertDialog.Builder(this); alert.SetMessage(string.Format(Resources.GetString(Resource.String.Error), ex.Message)); alert.Show(); } finally { dialog.Hide(); } }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.CurrentPollLayout); var viewChartButton = FindViewById<Button>(Resource.Id.ViewChartButton); var submitResponsesButton = FindViewById<Button>(Resource.Id.SubmitResponsesButton); var question = FindViewById<TextView>(Resource.Id.CurrentPollQuestion); var choice1Text = FindViewById<TextView>(Resource.Id.Choice1); var choice2Text = FindViewById<TextView>(Resource.Id.Choice2); var choice3Text = FindViewById<TextView>(Resource.Id.Choice3); var choice4Text = FindViewById<TextView>(Resource.Id.Choice4); var choice1Edit = FindViewById<EditText>(Resource.Id.Choice1EditText); var choice2Edit = FindViewById<EditText>(Resource.Id.Choice2EditText); var choice3Edit = FindViewById<EditText>(Resource.Id.Choice3EditText); var choice4Edit = FindViewById<EditText>(Resource.Id.Choice4EditText); // splits the poll votes into corresponding numbers to be displayed based off of the number of choices string[] split = VotingService.Poll.Votes.Split(','); switch (split.Length) { case 2: { choice1Edit.Text = split[0]; choice2Edit.Text = split[1]; choice3Edit.Visibility = ViewStates.Gone; choice4Edit.Visibility = ViewStates.Gone; break; } case 3: { choice1Edit.Text = split[0]; choice2Edit.Text = split[1]; choice3Edit.Text = split[2]; choice4Edit.Visibility = ViewStates.Gone; break; } case 4: { choice1Edit.Text = split[0]; choice2Edit.Text = split[1]; choice3Edit.Text = split[2]; choice4Edit.Text = split[3]; break; } } // splits the choices of the poll into the corresponding text choices split = VotingService.Poll.Choices.Split(','); switch (split.Length) { case 2: { choice1Text.Text = split[0]; choice2Text.Text = split[1]; choice3Text.Visibility = ViewStates.Gone; choice4Text.Visibility = ViewStates.Gone; break; } case 3: { choice1Text.Text = split[0]; choice2Text.Text = split[1]; choice3Text.Text = split[2]; choice4Text.Visibility = ViewStates.Gone; break; } case 4: { choice1Text.Text = split[0]; choice2Text.Text = split[1]; choice3Text.Text = split[2]; choice4Text.Text = split[3]; break; } } // takes you to view a bar graph of the number of votes per choice viewChartButton.Click += (sender, e) => { var viewChartIntent = new Intent(this, typeof(ViewChartActivity)); StartActivity(viewChartIntent); }; // submits the number of votes to the server submitResponsesButton.Click += async (sender, e) => { switch (split.Length) { case 2: { VotingService.Poll.Votes = choice1Edit.Text + "," + choice2Edit.Text; break; } case 3: { VotingService.Poll.Votes = choice1Edit.Text + "," + choice2Edit.Text + "," + choice3Edit.Text; break; } case 4: { VotingService.Poll.Votes = choice1Edit.Text + "," + choice2Edit.Text + "," + choice3Edit.Text + "," + choice4Edit.Text; break; } } // shows spinner while it trys updating ther database var progressDialog = new ProgressDialog(this); progressDialog.Show(); try { // updating the number of votes in the database await VotingService.MobileService.GetTable<Poll>().UpdateAsync(VotingService.Poll); } catch (Exception exc) { // shows an error if it fails var errorDialog = new AlertDialog.Builder(this).SetTitle("Oops!").SetMessage("Something went wrong " + exc.ToString()).SetPositiveButton("Okay", (sender1, e1) => { }).Create(); errorDialog.Show(); } // hides spinner when done progressDialog.Hide(); }; }