Android custom input validation for numbers - c#

So I'm working in Xamarin to make a C# android app for school and at some point the user needs to type in an IBAN number.
I want to check if the input equals 4 times 4 numbers with a dash between them (e.g. 1234-1234-1234-1234),
sadly I have no idea how to do this and I haven't found anything that could help me, so far.
This is my activity where I need to check if the input of "mTxtIBAN" equals the IBAN number.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace LoginSystem
{
[Activity (Label = "SubDetailsBankActivity")]
public class SubDetailsBankActivity : Activity
{
private Button mBtnContinue;
private EditText mTxtIBAN;
private EditText mTxtBIC;
private TextView mIBANWarning;
private TextView mBICWarning;
protected override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
SetContentView (Resource.Layout.SubBankDetails);
// Create your application here
string email = Intent.GetStringExtra ("Email") ?? "Data not available";
string firstName = Intent.GetStringExtra ("FirstName") ?? "Data not available";
string lastName = Intent.GetStringExtra ("LastName") ?? "Data not available";
string streetNumber = Intent.GetStringExtra ("StreetNumber") ?? "Data not available";
string cityCode = Intent.GetStringExtra ("CityCode") ?? "Data not available";
string country = Intent.GetStringExtra ("Country") ?? "Data not available";
mBtnContinue = FindViewById<Button> (Resource.Id.btnContinue);
mTxtIBAN = FindViewById<EditText> (Resource.Id.IBAN);
mTxtBIC = FindViewById<EditText> (Resource.Id.BIC);
mIBANWarning = FindViewById<TextView> (Resource.Id.IBANtext);
mBICWarning = FindViewById<TextView> (Resource.Id.BICtext);
mBtnContinue.Click += (object sender, System.EventArgs e) =>
{
if (mTxtIBAN.Text.Length != 0 && mTxtBIC.Text.Length != 0) {
var newSub = new Intent(this, typeof(SubDetailsComplete));
newSub.PutExtra ("Email", email);
newSub.PutExtra ("FirstName", firstName);
newSub.PutExtra ("LastName", lastName);
newSub.PutExtra ("StreetNumber", streetNumber);
newSub.PutExtra ("CityCode",cityCode);
newSub.PutExtra ("Country", country);
newSub.PutExtra ("IBAN", mTxtIBAN.Text);
newSub.PutExtra ("BIC", mTxtBIC.Text);
StartActivity (newSub);
}
if (mTxtIBAN.Text.Length == 0){
mIBANWarning.Text = "Fill in your IBAN number!";
}
if (mTxtBIC.Text.Length == 0){
mBICWarning.Text = "Fill in your BIC number!";
}
};
}
}
}
Any help would be much appreciated.
Thank you in advance and have a nice day.

You can check it this way:
Regex rgx = new Regex(#"^\d{4}?-\d{4}?-\d{4}?-\d{4}?$");
if (rgx.IsMatch(mTxtIBAN.Text))
{
// valid IBAN
}

Related

How to change text to speech language in Xamarin.Android C#

I wanted to make a text to speech application for a project and I used this as a reference: https://github.com/xamarin/monodroid-samples/tree/main/PlatformFeatures/TextToSpeech
However, whenever i open the app it always opens up the google tts service and I cannot change the language, and the spinner does not show any languages only "Default" is there a way to make this program not open up google tts service each time and making the language options available on the spinner? thanks so much!
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.Support.V7.App;
using Android.Speech.Tts;
using Java.Util;
using Android.Graphics;
namespace DND_Connect
{
[Activity(Label = "Deaf")]
public class DeafPage : Activity, TextToSpeech.IOnInitListener
{
TextToSpeech textToSpeech;
Context context;
private readonly int MyCheckCode = 101, NeedLang = 103;
Java.Util.Locale lang;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.deaf);
var btnSayIt = FindViewById<Button>(Resource.Id.buttonSpeak);
var editWhatToSay = FindViewById<EditText>(Resource.Id.edtSpch);
var spinLanguages = FindViewById<Spinner>(Resource.Id.spnLng);
var txtSpeedVal = FindViewById<TextView>(Resource.Id.txtSpeed);
var txtPitchVal = FindViewById<TextView>(Resource.Id.txtPitch);
var seekSpeed = FindViewById<SeekBar>(Resource.Id.skSpeed);
var seekPitch = FindViewById<SeekBar>(Resource.Id.skPitch);
var txtView = FindViewById<TextView>(Resource.Id.deaftitle);
var txtView1 = FindViewById<TextView>(Resource.Id.deafdesc);
Typeface tf = Typeface.CreateFromAsset(Assets, "Roboto-Condensed.ttf");
txtView.SetTypeface(tf, Android.Graphics.TypefaceStyle.Normal);
txtView1.SetTypeface(tf, Android.Graphics.TypefaceStyle.Normal);
seekSpeed.Progress = seekPitch.Progress = 127;
txtSpeedVal.Text = txtPitchVal.Text = "0.5";
context = btnSayIt.Context;
textToSpeech = new TextToSpeech(this, this, "com.google.android.tts");
var langAvailable = new List<string> { "Default" };
var localesAvailable = Java.Util.Locale.GetAvailableLocales().ToList();
foreach (var locale in localesAvailable)
{
LanguageAvailableResult res = textToSpeech.IsLanguageAvailable(locale);
switch (res)
{
case LanguageAvailableResult.Available:
langAvailable.Add(locale.DisplayLanguage);
break;
case LanguageAvailableResult.CountryAvailable:
langAvailable.Add(locale.DisplayLanguage);
break;
case LanguageAvailableResult.CountryVarAvailable:
langAvailable.Add(locale.DisplayLanguage);
break;
}
}
langAvailable = langAvailable.OrderBy(t => t).Distinct().ToList();
var adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleSpinnerDropDownItem, langAvailable);
spinLanguages.Adapter = adapter;
lang = Java.Util.Locale.Default;
textToSpeech.SetLanguage(lang);
textToSpeech.SetPitch(.5f);
textToSpeech.SetSpeechRate(.5f);
btnSayIt.Click += delegate
{
if (!string.IsNullOrEmpty(editWhatToSay.Text))
textToSpeech.Speak(editWhatToSay.Text, QueueMode.Flush, null);
};
seekPitch.StopTrackingTouch += (object sender, SeekBar.StopTrackingTouchEventArgs e) =>
{
var seek = sender as SeekBar;
var progress = seek.Progress / 255f;
textToSpeech.SetPitch(progress);
txtPitchVal.Text = progress.ToString("F2");
};
seekSpeed.StopTrackingTouch += (object sender, SeekBar.StopTrackingTouchEventArgs e) =>
{
var seek = sender as SeekBar;
var progress = seek.Progress / 255f;
textToSpeech.SetSpeechRate(progress);
txtSpeedVal.Text = progress.ToString("F2");
};
spinLanguages.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) =>
{
lang = Java.Util.Locale.GetAvailableLocales().FirstOrDefault(t => t.DisplayLanguage == langAvailable[(int)e.Id]);
var checkTTSIntent = new Intent();
checkTTSIntent.SetAction(TextToSpeech.Engine.ActionCheckTtsData);
StartActivityForResult(checkTTSIntent, NeedLang);
};
}
void TextToSpeech.IOnInitListener.OnInit(OperationResult status)
{
if (status == OperationResult.Error)
textToSpeech.SetLanguage(Java.Util.Locale.Default);
if (status == OperationResult.Success)
textToSpeech.SetLanguage(lang);
}
protected override void OnActivityResult(int req, Result res, Intent data)
{
if (req == NeedLang)
{
var installTTS = new Intent();
installTTS.SetAction(TextToSpeech.Engine.ActionInstallTtsData);
StartActivity(installTTS);
}
}
}
}
[assembly: Xamarin.Forms.Dependency(typeof(TextToSpeechImplementation))]
namespace ShopFloor_Automation.Droid.Implementations
{
public class TextToSpeechImplementation : Java.Lang.Object, ITextToSpeech, TextToSpeech.IOnInitListener
{
TextToSpeech speaker;
string toSpeak;
public TextToSpeechImplementation() { }
public void OnInit([GeneratedEnum] OperationResult status)
{
if (status.Equals(OperationResult.Success))
{
var p = new Dictionary<string, string>();
speaker.Speak(toSpeak, QueueMode.Flush, p);
}
}
public void Speak(string text)
{
var ctx = Forms.Context; // useful for many Android SDK features
toSpeak = text;
if (speaker == null)
{
speaker = new TextToSpeech(ctx, this);
}
else
{
var p = new Dictionary<string, string>();
speaker.Speak(toSpeak, QueueMode.Flush, p);
}
}
}
}

Navigation- PopAsync() does not seem to work

I am creating a login form using Xamarin which accepts email, password fields.
After the user enters his details and clicks on login button, no alert box is displayed. It comes out of the app. Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlTypes;
using Xamarin.Forms;
using SQLite;
using System.IO;
namespace LoginPage.Views
{
public class AddDetails : ContentPage
{
private Entry _emailEntry;
private Entry _passwordEntry;
private Button _saveButton;
string _dbPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "myDB.db3");
public AddDetails()
{
this.Title = "Add Details";
StackLayout stackLayout = new StackLayout();
_emailEntry = new Entry();
_emailEntry.Keyboard = Keyboard.Text;
_emailEntry.Placeholder = "Email";
stackLayout.Children.Add(_emailEntry);
_passwordEntry = new Entry();
_passwordEntry.Keyboard = Keyboard.Text;
_passwordEntry.Placeholder = "Password";
stackLayout.Children.Add(_passwordEntry);
_saveButton = new Button();
_saveButton.Text = "Login User";
_saveButton.Clicked += _saveButton_Clicked;
stackLayout.Children.Add(_saveButton);
Content = stackLayout;
}
private async void _saveButton_Clicked(object Sender, EventArgs e)
{
var db = new SQLiteConnection(_dbPath);
db.CreateTable<User>();
var maxPk = db.Table<User>().OrderByDescending(c => c.Id).FirstOrDefault();
User user = new User()
{
Id = (maxPk == null ? 1 : Convert.ToInt32(maxPk.Id) +1),
Email = _emailEntry.Text,
Password = _passwordEntry.Text
};
db.Insert(user);
await DisplayAlert(null, user.Email + "Saved", "Ok");
await Navigation.PopAsync();
}
}
}
Login screen gets displayed, but no alert box which should say Email saved. Also, it comes out of the app abruptly
Have you set
MainPage = new NavigationPage (new Page1Xaml ());
Please follow this link
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/navigation/

C# WFA login not working using .Split() and reading from .txt

I am creating a login screen for the coursework of a quiz game that I have been assigned to make. I am making this quiz in C# (windows form application).
Here is the code before I go any further:
entersing System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace frmSplashScreen
{
public partial class frmLogin : Form
{
public frmLogin()
{
InitializeComponent();
StartPosition = FormStartPosition.CenterScreen;
}
int signUpPressed = 0;
private void button1_Click(object sender, EventArgs e)
{
string[] userdetails = File.ReadAllLines(AppDomain.CurrentDomain.BaseDirectory + "UserDetails.txt");
foreach (string user in userdetails)
{
string[] splitDetails = user.Split(':');
Login.username = splitDetails[0];
Login.password = splitDetails[1];
label1.Text = Login.username;
label2.Text = Login.password;
if ((txtUsername.Text == Login.username) && (txtPassword.Text == Login.password))
{
MessageBox.Show("Welcome " + Login.username);
this.Hide();
frmMainMenu menu = new frmMainMenu();
menu.Show();
break;
}
else
{
if ((txtUsername.Text == Login.username) && (txtPassword.Text != Login.password))
{
MessageBox.Show("Password incorrect");
txtPassword.Text = "";
}
else
{
MessageBox.Show("Username incorrect");
txtUsername.Text = "";
txtPassword.Text = "";
}
break; //Remove this break it's not needed
}
}
}
}
}
Also here is the .txt file that it is reading the login details from:
Ryan:password
Username:password
My problem is that when I click the login button(button1), it is only reading the first line of UserDetails.txt, when I type Ryan and password into the text boxes, it works fine. However, when I type Username and password into the text boxes it comes up with the error message "Username incorrect" in a Message Box.
Also, 'Login' is a class that stores the variables for username and password
Any help would be greatly appreciated.
Thanks.
Every branch in your foreach loop ends with a break;, you never get to the second entry. Move the second break to the "Password incorrect", and allow the loop to continue if the Username does not match, maybe another one does. Check after the loop if a match has been found. (This might be easier when replacing break; with return username; in a new method CheckAndGetUser().)

SharedPreferences value does not stick

I am trying to save a string to SharedPerferences like this:
Write
var prefs = Application.Context.GetSharedPreferences ("Janssen", FileCreationMode.WorldReadable);
var prefEditor = prefs.Edit ();
prefEditor.PutString ("SecurityToken", SecurityCode.Text);
prefEditor.Commit ();
Read
var prefs = Application.Context.GetSharedPreferences ("Janssen", FileCreationMode.WorldReadable);
var SecurityToken = prefs.GetString ("SecurityToken", null);
I am new to Android coming from iOS. I am trying to emulate NSUserDefaults in iOS. I am reading the SharedPreferences in a new activity, maybe that is what causes the problem? I am not sure. I also have no idea what to set as default value.
Are you re-deploying between writing your SharedPreferences and reading them? This often wipes the SharedPreferences.
I have just tested them and they work fine between two Activities:
WritePrefsAcitivity.cs
using Android.App;
using Android.Content;
using Android.Widget;
using Android.OS;
namespace Derrrp
{
[Activity (Label = "Derrrp", MainLauncher = true)]
public class WritePrefsActivity : Activity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Write);
var prefs = Application.Context.GetSharedPreferences("MySharedPrefs", FileCreationMode.Private);
var prefsEditor = prefs.Edit();
var ed = FindViewById<EditText>(Resource.Id.editText1);
ed.AfterTextChanged += (sender, e) => {
prefsEditor.PutString("MyPref", e.Editable.ToString());
prefsEditor.Commit();
};
Button button = FindViewById<Button> (Resource.Id.myButton);
button.Click += delegate {
var intent = new Intent(this, typeof(ReadPrefsActivity));
StartActivity(intent);
};
}
}
}
ReadPrefsActivity.cs
using Android.App;
using Android.Content;
using Android.OS;
using Android.Widget;
namespace Derrrp
{
[Activity (Label = "ReadPrefsActivity")]
public class ReadPrefsActivity : Activity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView(Resource.Layout.Read);
var tv = FindViewById<TextView>(Resource.Id.myTextView);
var button = FindViewById<Button>(Resource.Id.myButton);
var prefs = Application.Context.GetSharedPreferences("MySharedPrefs", FileCreationMode.Private);
button.Click += (sender, e) => {
tv.Text = prefs.GetString("MyPref", "");
};
}
}
}
The defValue can be set to anything you want. This is the value that will be chosen if the preference you are trying to get is empty.
NOTE: If you are using it to store some secret information it is advised to use FileCreationMode.Private and even use something that makes it only readable by the application, such as encryption.
I am not sure what is the error you have, but below is an example i used before for saving a string using shared preferences.
I used to set default value to "", so that while reading, if the value was not saved before, it will set the variable to empty string. You can read the shared preferences in any new activity , shared preferences is per application not activity ..
example:
writing string:
String pass = "abcdefg";
SharedPreferences preferences = getSharedPreferences("pref", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("savedPass", pass);
editor.commit();
reading string:
SharedPreferences preferences = getSharedPreferences("pref", 0);
String mypassword = preferences.getString("savedPass", "");

Regular Expressions in C# kill program

I'm doing a program for a class, and when I run it and type something in the txtSSN control that's not valid, it freezes up and crashes. I can't figure it out because I have another very similar project that works just fine.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
namespace VitalStatistics
{
public partial class frmVitalStatistics : Form
{
#region Declarations
const String AppTitle = "Vital Statistics";
const float hoursOffset = 24.999F;
Regex ssnRegex;
#endregion
#region Constructors
public frmVitalStatistics()
{
InitializeComponent();
}
#endregion
#region Event Handlers
private void frmVitalStatistics_Load(object sender, EventArgs e)
{
// Initialize SSN input control
RegexOptions options = RegexOptions.IgnorePatternWhitespace;
string pattern = #"\A\d{3}-\d{3}-\d{4}\Z";
ssnRegex = new Regex(pattern, options);
// Init. Gender controls
optGender = Gender.Unassigned;
rbFemale.Tag = Gender.Male;
rbMale.Tag = Gender.Female;
// Init dtpBirth controls
dtpBirth.MinDate = DateTime.Today;
dtpBirth.MaxDate = DateTime.Today.AddHours(hoursOffset);
dtpBirth.Value = DateTime.Today;
}
private void btnSubmit_Click(object sender, EventArgs e)
{
string name = String.Empty;
string ssn = String.Empty;
int length = 0;
int weight = 0;
DateTime birthDate = DateTime.MinValue;
Gender gender = Gender.Unassigned;
//Gather inputs
if (GetName(ref name) &&
GetSSN(ref ssn) &&
GetLength(ref length) &&
GetWeight(ref weight) &&
GetGender(ref gender) &&
GetBirthDate(ref birthDate))
{
//submit & close
string format =
"Thank you for submitting your contact information. \n\n" +
"Name: {0}\n" +
"SSN: {1}\n" +
"Length: {2}\n" +
"Weight: {3}\n" +
"Gender: {4}\n" +
"Birth Date & Time: {5:D}\n";
string msg = String.Format(format, name, ssn, length, weight, gender, birthDate);
MessageBox.Show(msg,AppTitle);
Close();
}
}
private Gender optGender;
private void Gender_CheckedChanged(object sender, EventArgs e)
{
RadioButton rb = (RadioButton)sender;
optGender = (rb.Checked ? (Gender)rb.Tag : Gender.Unassigned);
}
#endregion
#region Implementation
bool GetName(ref string name)
{
if (String.IsNullOrWhiteSpace(txtName.Text))
{
txtName.SelectAll();
txtName.Focus();
ShowError("Please enter your name.\n Names cannot consist of whitespace.");
return false;
}
name = txtName.Text.Trim();
return true;
}
bool GetSSN(ref string ssn)
{
txtSSN.Text = txtSSN.Text.Trim();
Match match = ssnRegex.Match(txtSSN.Text);
if (!match.Success)
{
txtSSN.SelectAll();
txtSSN.Focus();
ShowError("Unrecognized format for SSN. Please enter in the following format: 000-000-0000.");
return false;
}
ssn = txtSSN.Text;
return true;
}
bool GetLength(ref int length)
{
int value;
try
{
if (String.IsNullOrWhiteSpace(txtLength.Text))
throw new ArgumentException("Field cannot be empty or contain spaces.");
value = int.Parse(txtLength.Text);
}
catch (Exception ex)
{
// Select text and set focus
txtLength.SelectAll();
txtLength.Focus();
// Set up error Message
string msg = String.Format("{0}", ex);
ShowError(ex.Message);
return false;
}
length = value;
return true;
}
bool GetWeight(ref int weight)
{
int value;
try
{
if (String.IsNullOrWhiteSpace(txtWeight.Text))
throw new ArgumentException("Field cannot be empty or contain spaces.");
value = int.Parse(txtLength.Text);
}
catch (Exception ex)
{
// Select text and set focus
txtWeight.SelectAll();
txtWeight.Focus();
// Set up error Message
string msg = String.Format("{0}", ex);
ShowError(ex.Message);
return false;
}
weight = value;
return true;
}
bool GetGender(ref Gender gender)
{
if (optGender == Gender.Unassigned)
{
ShowError("Select a Gender.");
return false;
}
gender = optGender;
return true;
}
bool GetBirthDate(ref DateTime birthDate)
{
birthDate = dtpBirth.Value;
return true;
}
void ShowError(string msg)
{
MessageBox.Show(msg, AppTitle, MessageBoxButtons.OK, MessageBoxIcon.None);
}
#endregion
}
}
Judging by the comments and the code it sounds as if you don't have the event handler frmVitalStatistics_Load connected to the load event of the form. This would cause a null pointer exception which would be consistent the error you are seeing.
As per my comments to the OP, if frmVitalStatistics_Load isn't running, it may not be hooked up right as an event handler.
I have been unable to reproduce the error you are seeing with the code you posted. There is likely something in your frmVitalStatistics.Designer.cs file that is different than what I came up with.
As others have said, it could be an event that is missing or perhaps an extra event hooked up that isn't needed.
These are the only events I have hooked up in the form.
this.rbMale.CheckedChanged += new System.EventHandler(this.Gender_CheckedChanged);
this.rbFemale.CheckedChanged += new System.EventHandler(this.Gender_CheckedChanged);
this.btnSubmit.Click += new System.EventHandler(this.btnSubmit_Click);
this.Load += new System.EventHandler(this.frmVitalStatistics_Load);
Check your frmVitalStatistics.Designer.cs and see if you have any others or if any of these are missing.
One question... Is it freezing AS you are typing or after you click Submit?

Categories