Validations using regular Expressions - android

Can someone point me on using Regular Expressions in android (Patterns and Matchers to be specific)
String pass_pattern = "^([A-Za-z0-9][A-Za-z0-9]{4,10})$";
b1= (Button)findViewById(R.id.button1);
et1= (EditText)findViewById(R.id.editText1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
chek = et1.getText().toString();
if(chek.equals(""))
{
Toast.makeText(getApplicationContext(), "Enter password",1000).show();
}
if(chek.matches(pass_pattern))
{
Toast.makeText(getApplicationContext(), "Valid pAssword",1000).show();
}else {Toast.makeText(getApplicationContext(), "InvalidpAssword",1000).show();}
}
});
this is my code currently, i wanna check if the user has entered atleast one small letter and atleast one capital letter and a number and the length should be 4-10 char's.
If i do this via .matches() it only compares only one of the condition in the above said string.

Try this:
String pass_pattern = "^(?=.*\\d)(?=.*[A-Z])(?=.*[a-z])[^\\W_]{4,10}$";

You could do it without using regexp:
boolean lowerCase = false;
boolean upperCase = false;
boolean digit = false;
int length = password.length();
for (char c : password.toCharArray()) {
if (Character.isUpperCase(c))
upperCase = true;
if (Character.isLowerCase(c))
lowerCase = true;
if (Character.isDigit(c))
digit = true;
if (lowerCase && upperCase && digit)
break;
}

Related

User Input of int won't be null

I made a code where user put value between some range and my code generate random number for them. Randomization working properly but when fields are blank my app is crash how should I fix it.
randNum.java
Button generateNum = findViewById(R.id.generate_number);
generateNum.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText et = findViewById(R.id.fromNum);
String sTextFromET = et.getText().toString();
int fNum = Integer.valueOf(sTextFromET);
EditText et1 = findViewById(R.id.toNum);
String sTextFromET1 = et1.getText().toString();
int sNum = Integer.valueOf(sTextFromET1);
TextView ans = findViewById(R.id.ans);
// if(sNum == null || fNum == null){
//
// ans.setText(getString(R.string.enterNumError));
//
// }
// else
if(sNum < fNum){
ans.setText(getString(R.string.max_min_error));
}else {
final int random = new Random().nextInt((sNum - fNum) + 1) + fNum;
String ras = Integer.toString(random);
ans.setText(ras);
}
}
});
I try to use null but it is not working.
You need to put validation first on button click. (For checking if user has entered nothing or just spaces in any of edittexts).
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
strNum1 = edtl.getText().toString().trim();
strNum2 = edt2.getText().toString().trim();
if (strNum1.length() == 0)
{
showAlert("Please enter Num 1");
}
else if (strNum2.length() == 0)
{
showAlert("Please enter Num 2");
}
else
{
int numvalue1 = Integer.parseInt(strNum1);
int numvalue2 = Integer.parseInt(strNum2);
generateNum (numvalue1, numvalue2); //Call your function for generation of random number here
//do your stuff here
}
}
});
Hope this helps you understand the validation of forms for empty input fields.
P.S: I would recommend you put inputType attribute for your EditTexts if you have not added it already in xml file like:
android:inputType="number"
So you can avoid exception at Integer.parseInt if user enters any alphabet or symbol.
You need to handle NumberFormatException thrown by Integer.valueOf() function
try {
EditText et = findViewById(R.id.fromNum);
String sTextFromET = et.getText().toString();
int fNum = Integer.valueOf(sTextFromET);
EditText et1 = findViewById(R.id.toNum);
String sTextFromET1 = et1.getText().toString();
int sNum = Integer.valueOf(sTextFromET1);
TextView ans = findViewById(R.id.ans);
if(sNum < fNum){
ans.setText(getString(R.string.max_min_error));
}else {
final int random = new Random().nextInt((sNum - fNum) + 1) + fNum;
String ras = Integer.toString(random);
ans.setText(ras);
}
}catch(NumberFormatException e){
Toast.makeText(this, "Invalid Input", Toast.LENGTH_SHORT).show();
}

Toast not working,App stops when toast is to be displayed

I have created a small application to check whether the password entered by user is valid or not. it is being able to check , but its not displaying the toast and as soon as i click the button , it shows "Unfortunately , your app has stopped working". I am using my device for deployment. Please help me find out , why the toast is not working. I have used a command which sets the value of variable a,b,c in the edit text field , to check whether it is coming correct. And yes it was coming correct. So the problem lies in the toast as per i think.
public class second extends AppCompatActivity {
public EditText fname ;
public EditText lname ;
public EditText email ;
public EditText pass ;
public EditText blood;
public EditText cpass;
public EditText add ;
public EditText mob ;
public Toast t ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
fname = (EditText) findViewById(R.id.fname);
lname = (EditText) findViewById(R.id.lname);
email = (EditText) findViewById(R.id.email);
pass = (EditText) findViewById(R.id.pass);
add = (EditText) findViewById(R.id.add);
cpass = (EditText) findViewById(R.id.cpass);
mob = (EditText) findViewById(R.id.mob);
blood = (EditText) findViewById(R.id.blood);
Button sign = (Button) findViewById(R.id.sign);
sign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String sfname = fname.getText().toString();
String spass = pass.getText().toString();
String scpass = cpass.getText().toString();
validate(spass, scpass);
}
});
}
public void validate(String spass ,String scpass){
int a =0;
int b =0;
int c =0;
t = new Toast(this);
int len = spass.length();
for(int i =0;i<len;i++){
char d = spass.charAt(i);
if(d>=48 && d<=57){
a++;
}
if(d>=65 && d<=90){
b++;
}
if(d>=33 && d<=47){
c++;
}
}
email.setText(a+" "+b+" "+c);
if(a==0 || b==0 || c==0){
t.makeText(this, "Password should contain atleast one special character , one capital letter and one number", Toast.LENGTH_LONG);
t.show();
} else {
if(spass.equals(scpass)){
t.makeText(this,"login succesful",Toast.LENGTH_SHORT);
t.show();
} else {
t.makeText(this,"passwords dont match",Toast.LENGTH_SHORT).show();
}
}
}
}
try this
Toast toast = Toast.makeText(context, text, duration);
toast.show()
or
Toast.makeText(context, text, duration).show();
From the Docs, it says
Toast (Context context) Construct an empty Toast object. You must call
setView(View) before you can call show().
So when you create Toast object from its constructor, it is considered that you are trying to create Custom Toast
If you are not creating any, then use like:
public Toast t; // Global variable
Now inside your validate method:
t = Toast.makeText(this, "Password should contain atleast one special character , one capital letter and one number", Toast.LENGTH_LONG);
t.show();
I have made some changes to you method , try using this one .
You can find more details on https://stackoverflow.com/a/21963343
public void validate(String spass ,String scpass){
int a =0;
int b =0;
int c =0;
// Toast t = new Toast(this);
int len = spass.length();
for(int i =0;i<len;i++){
char d = spass.charAt(i);
if(d>=48 && d<=57){
a++;
}
if(d>=65 && d<=90){
b++;
}
if(d>=33 && d<=47){
c++;
}
}
email.setText(a+" "+b+" "+c);
if(a==0 || b==0 || c==0){
/*
* updated
* */
Toast.makeText(this, "Password should contain atleast one special character , one capital letter and one number", Toast.LENGTH_LONG).show();
} else {
if(spass.equals(scpass)){
/*Updated*/
Toast.makeText(this,"login succesful",Toast.LENGTH_SHORT).show();
} else {
/*Updated*/
Toast.makeText(this,"passwords dont match",Toast.LENGTH_SHORT).show();
}
}
}

Bengali calculator Android studio

I am trying to build a Bengali calculator. Here is the layout of English calculator :
By editing layout I can easily replace English digits with Bengali digits. But when it comes to the calculation i am unable to do it. Like i want it to calculate in Bengali too. e.g it will perform in Bengali like this (২+২=৪) instead of (2+2=4). I have tried the replacing method but it didn't work.
Bengali digits(০ ১ ২ ৩ ৪ ৫ ৬ ৭ ৮ ৯)
English digits(1 2 3 4 5 6 7 8 9)
Thank you for your time.
public class MainActivity extends AppCompatActivity {
private TextView screen;
private String str2, result, str, sign;
private double a, b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
screen = (TextView) findViewById(R.id.textview);
str = "";
}
public void onclick(View v) {
Button button = (Button) v;
str += button.getText().toString();
screen.setText(str);
a = Double.parseDouble(str);
}
public void onclicksign(View v) {
Button button = (Button) v;
sign = button.getText().toString();
screen.setText(sign);
str = "";
}
public void calculate(View v) {
Button button = (Button) v;
str2 = screen.getText().toString();
b = Double.parseDouble(str2);
if (sign.equals("+")) {
result = a + b + "";
} else if (sign.equals("-")) {
result = a - b + "";
} else if (sign.equals("*")) {
result = a * b + "";
} else if (sign.equals("/")) {
result = a / b + "";
} else {
screen.setText("?????? ???");
}
{
screen.setText(result);
}
}
}
Your code tries to extract numerical values from the text on buttons.
You should write custom Double parser which parses Bengali number text to numerical value.
Also you should write a method which converts numerical double value to Bengali number text. You have to use this method while setting screen text.
public class MainActivity extends AppCompatActivity {
private TextView screen;
private String str2, result, str, sign;
private double a, b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
screen = (TextView) findViewById(R.id.textview);
str = "";
}
public void onclick(View v) {
Button button = (Button) v;
str += button.getText().toString();
screen.setText(str);
a = BengaliUtils.toDouble(str);
}
public void onclicksign(View v) {
Button button = (Button) v;
sign = button.getText().toString();
screen.setText(sign);
str = "";
}
public void calculate(View v) {
Button button = (Button) v;
str2 = screen.getText().toString();
b = BengaliUtils.toDouble(str2);
if (sign.equals("+")) {
result = a + b + "";
} else if (sign.equals("-")) {
result = a - b + "";
} else if (sign.equals("*")) {
result = a * b + "";
} else if (sign.equals("/")) {
result = a / b + "";
} else {
screen.setText("?????? ???");
}
{
screen.setText(BengaliUtils.toString(result));
}
}
}
class BengaliUtils {
static String toString(double value) {
//TODO implement logic
// You can convert value to regular number text, and then replace each char with the Bengali version. The performance could be improved with better logic.
return text;
}
static double toDouble(String text) {
//TODO implement logic
//You can do that, first replace each Bengali char with normal number char. The use Double.parse on new text. The performance could be improved with better logic.
return value;
}
}
#Override
public void onClick(View view) {
String num = editText.getText().toString();
//split the num
char[] charArray = num.toCharArray();
StringBuilder stringBuilder = new StringBuilder(charArray.length);
// loop and convert using switch case
for (int i=0; i<charArray.length; i++ ){
char character = charArray[i];
switch (character){
case '.':
stringBuilder.append(".");
break;
case '0':
stringBuilder.append("০");
break;
case '1':
stringBuilder.append("১");
break;
}
}
//Final result..
textView.setText(stringBuilder);
}
Try above code...
Here is the output
NOTE
I am taking English numbers from EditText on Button click. You will
have to change that in your code.
Currently, switch can handle 0,1,.(decimal) only. You can easily
add cases for other numbers too.
Please Check this answer too. Convert String to another locale in java

Append zeros to input edit text to get minLength

I have edit text with minLength=13. If user enters below 13 characters I want to append the zeros in front of the input to make this length to 13. Ex: user enter 123 -> 0000000000123.
Any approach?
This can be done with String.format, provided the input is an integer:
int input = 123;
int pad_width = 13;
String padded = String.format("%0"+pad_width+"d", input);
// padded is now "0000000000123"
Answers related to this on other questions:
https://stackoverflow.com/a/4051905/940217
https://stackoverflow.com/a/391978/940217
The easiest way would be to check the length of the user's input.
String input = 123;
StringBuilder finalString= new StringBuilder();
for (int i=0; i<13-input.length(); i++){
finalString.append("0")
}
finalString.append(input)
Yea this is pretty easy. Keep in mind this code is not tested:
// Declaration
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Declare edittext here
mEditText = // init code...
}
// Detect when user has pressed done
public void setKeyListener() {
mEditText.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (keyCode == KeyEvent.KEYCODE_ENTER) {
String s = mEditText.getText().toString();
s = appendZerosIfNecessary();
return true;
}
}
return false;
}
});
// Append if necessary
private String appendZerosIfNecessary(String s) {
int length = s.length;
if (s.length < 13) {
StringBuilder sb = new StringBuilder(s);
for (int i = length; i < 13; i++) {
sb.append('0');
}
return sb.toString();
}
return s;
}
Note this code is not tested, but you get the idea.
EDIT: just reread question you want 0's appended in the beginning.
In this case I would merge the other answer with this one and change appendZerosIfNecessary() to the following:
private String appendZerosIfNecessary(String s) {
StringBuilder finalString = new StringBuilder();
for (int i = 0; i < (13 - input.length()); i++){
finalString.append('0')
}
finalString.append(input)
}

Buttons text to string

I have an array of buttons which contains two elements.
I'd like to create a string from the text of the buttons.
The thing i am struggling with is the if statement. Basically, it is never firing the toast. Why?
String word2 = "ok";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button buttons[] = new Button[2];
buttons[0] = (Button) findViewById(R.id.btn);
buttons[1] = (Button) findViewById(R.id.btn2);
buttons[0].setText("o");
buttons[1].setText("k");
buttons[0].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String word = "";
for (int i = 0; i < 2; i++) {
word += buttons[i].getText().toString();
}
if (word == word2) {
Toast.makeText(getApplicationContext(), "Good",
Toast.LENGTH_LONG).show();
}
}
});
}
Change this:
if (word == word2) {
with this:
if(word.equals(word2)) {
You can't compare String with ==
Write Better Questions (basically questions)
Compare string with .equals() not ==.
Just use if(word.equals(word2) {
Why? The first one is content comparision, but the second one i just
a reference comparision so:
String a = new String("x");
String b = new String("x");
if(a==b){
System.out.println("It wont work");
}else if(a.equals(b)){
System.out.println("It will");
}
Dont ever use new String(), it was just for proof
I must write it.
Change line
for (int i = 0; i < 2; i++) {
into
for (int i = 0; i < buttons.length; i++) {
So your application will be easier to change

Categories

Resources