Regex with all special symbols - android

I need regex that will allow only Latin characters, digits and all other symbols(but not whitespace)
thanks!
UPDATE:
private boolean loginPassHasCorrectSymbols(String input){
if (input.matches("[A-Za-z0-9\!\"\#\$\%\&\'\(\)\*\+\,\-\.\/\:\;\<\>\=\?\#\[\]\{\}\\\^\_\`\~]+$")){
return true;
}
return false;
}

I hope I got them all.
"[A-Za-z0-9\!\"\#\$\%\&\'\(\)\*\+\,\-\.\/\:\;\<\>\=\?\#\[\]\{\}\\\\\^\_\`\~]+$"
Edit: I forgot that in Java, the regexes are also strings, so you need to actually escape each \ given in the string using another \. I hope I didn't miss any now.
"[A-Za-z0-9\\!\\\"\\#\\$\\%\\&\\'\\(\\)\\*\\+\\,\\-\\.\\/\\:\\;\\<\\>\\=\\?\\#\\[\\]\\{\\}\\\\\\^\\_\\`\\~]+$"

How about everything not a whitespace?
"^\S+$"

I did this and it works for me .
Either you can block whitespace by mentioning it on Edittext, or you can block on editetext.addtextChangeListner too by pragmatically .
1>
android:digits="0,1,2,3,4,5,6,7,8,9,*,qwertzuiopasdfghjklyxcvbnm,_,-"
2>
etNewPassword.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (etNewPassword.getText().toString().contains(" ")) {
etNewPassword.setText(etNewPassword.getText().toString().replace(" ", ""));
int iLength = etNewPassword.getText().toString().length();
etNewPassword.setSelection(iLength);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
Let me know if any concern.

For find any symbol except whitespace, you can use this code. I hope you find it useful
public static boolean hasAnySymbolExceptWhitespace(String string){
return Pattern.matches("(?=.*[^a-zA-Z0-9] ).*", string);
}

Smooth Kotlin solution which allows English letters with some default symbols. Cyrillic or any other language symbols won't be allowed.
//Allows english with usual symbols
private fun hasNonAllowedSymbols(input: String) : Boolean {
val regex = "[a-zA-Z0-9\\s-#,/~`'!#$%^&*()_+={}|;<>.?:\"\\[\\]\\\\]*"
val pattern = Pattern.compile(regex)
return !pattern.matcher(input).matches()
}

Related

Edit text should allow text if a. alphabet +number b. alphabet +special character c. alphabet only

I am trying to generate a regular expression in Android which can satisfy following conditions:
Edit text can accept:
Alphabet only
Combination of Alphabet and number
Combination of Alphabet and special character
Should not accept:
a. Only Number
b. Only Special character
I tried alot but still, i didn't get any meaningful link. Please try to save my day.
I tried with regular expression (?!^\d+$)^.+$") which only valid alphanumric requirement. I am looking for such regular expression which fullfil my requirement.
It's really simple bro... just clear EditText if the text inside it doesn't have an alphabet .. as you have said ...
Should not accept a. Only Number b. Only Special character
TextWatcher mTextWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
boolean atleastOneAlpha = s.toString().matches(".*[a-zA-Z]+.*");
if (!atleastOneAlpha) {
editText.setText("");
}
}
#Override
public void afterTextChanged(Editable s) {
}
};
mTargetEditText.addTextChangedListener(mTextWatcher);

Android insert emoji programmatically

I'm trying to implement emojis in a way that I automatically replace things like ":)" with their emoji equivalent. And I'm not really sure how to do that, I found a table of emoji UTF codes, but I'm not sure on how I'm supposed to programmatically put them into a EditText :/
inputField=(EditText)temp.findViewById(R.id.inputField);
inputField.addTextChangedListener(new TextWatcher() {
boolean justChanged=false;
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(justChanged) {
justChanged=false;
return;
}
Log.d(s.toString(), s.toString());
if(s.toString().contains(":)")) {
justChanged=true;
inputField.setText(s.toString().replace(":)", "UTF CODE HERE?"));
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
The simplest way is to achieve this is to encode your source code as UTF-8, and paste your desired emoji into the code. You will then need to pass -encoding UTF-8 to javac. The emoji will then be converted to its Unicode point on compilation.
E.g.
inputField.setText(s.toString().replace(":)", "😁"));
Alternatively, you can use UTF-16 Unicode point literals within Java strings, using the \uXXXX notation. From a suitable Unicode reference site, such as, http://www.fileformat.info/info/unicode/block/emoticons/list.htm, you can get the UTF-16 type encoding or the complete Java escape sequence.
E.g.
inputField.setText(s.toString().replace(":)", "\uD83D\uDE00"));

Saving a BigDecimal value to json

new to the site and Android programming so I hope someone can help me out. I am trying to self teach and would consider myself a bit of a noob. Right now I'm more of a consumer of this site, but hopefully can become a contributor.
I have created an EditText within a Fragment where I want to capture a dollar amount / currency value. I am trying to use a BigDecimal but am having a hard time implementing. I have a Class named Transaction where I defined getters and setters as well as my JSON object. For example my getters and setters are implemented:
public BigDecimal getAmount() {
return mAmount;
}
public void setAmount(BigDecimal amount) {
mAmount = amount;
}
and my JSON to Save and Retrieve looks like:
json.put(JSON_AMOUNT, mAmount);
if (json.has(JSON_AMOUNT)) {
mAmount = BigDecimal.valueOf(json.getDouble(JSON_AMOUNT));
}
In my OnCreateView of my fragment, my EditText looks like:
mAmountField = (EditText)v.findViewById(R.id.transaction_amount);
mAmountField.setText((CharSequence) mTransaction.getAmount());
mAmountField.addTextChangedListener(new TextWatcher() {
DecimalFormat dec = new DecimalFormat("0.00");
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!s.toString().matches("\\$(d{1,3}(\\,\\d{3})*|(\\d+))(\\.\\d{2})?$")) {
String userInput = "" + s.toString().replaceAll("[^\\d]", "");
if (userInput.length() > 0) {
Float in = Float.parseFloat(userInput);
float percent = in/100;
mAmountField.setText("$" + dec.format(percent));
mAmountField.setSelection(mAmountField.getText().length());
}
mTransaction.setAmount(BigDecimal.valueOf());
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void afterTextChanged(Editable s) {
}
});
What I can't figure out is how to save the value entered for mAmountField to my JSON Object. With Strings I just use (For Example):
public void onTextChanged(CharSequence s, int start, int before, int count) {
mTransaction.setDetails(s.toString());
}
But I can't figure out the correct syntax for a BigDecimal. Any help or insight would be greatly appreciated. Thanks in advance!
If you want to save BigDecimal as string to JsonObject you need to use the toString()
json.put(JSON_AMOUNT, mAmount.toString());
and then when you want to get the value back
BigDecimal mAmount= new BigDecimal(json.optString(JSON_AMOUNT,"0"));
ps. you can use getString() instead optString() but I recommend optString() because you can set the default value is the key is not exist.
Another suggestion is using Gson library to convert between json and value, you will can serialize whole object and deserialize it back.

Removing TextChangedListener then re-adding it

So I've been trying to implement the TextWatcher for Android and ran into a few problems with the TextChangedListener being called multiple times or going into an infinite loop as I want to convert the text in the EditText widget into a currency formatted string.
What I did to work around this was create my own custom TextWatcher and then in the afterTextChanged event did something like the following
public class CurrencyTextWatcher implements TextWatcher {
private EditText et;
public CurrencyTextWatcher(EditText editText) {
et = editText;
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void afterTextChanged(Editable s) {
et.removeTextChangedListener(this);
et.setText(myCurrencyString);
et.addTextChangedListener(this);
}
}
So my question is, is there a better way of doing this? I want to have the one EditText Widget to hold where the edits go and the resulting formatted string.
Also is there actually any other issues that comes about removing and then adding a TextChangedListener like this?
Thanks in advance
Everytime you will update (by eg calling set text) your editText the afterTextChanged will be called, so I think you should refrain from calling setText every time you are in afterTextChanged and only call it when something is really changing.
sth like this
if ( !myCurrencyString.equals(et.getText()))
{
et.setText(myCurrencyString);
}
How about following.
private void resetAddTagField() {
if (edtView != null && textWatcherListener != null) {
edtView.removeTextChangedListener(textWatcherListener);
edtView.setText(DEFAULT_TEXT);
edtView.addTextChangedListener(textWatcherListener);
}
}
What I learn: Do not underestimate power of TextWatcher :D :D

Validating edittext in Android

I'm new to android & I'm trying to write an application for a project.
I need to check whether the user has entered 7 numbers followed by one alphabet in edittext.
Example: 0000000x
How should I do that? TIA! :)
Probably the best approach would be to use a TextWatcher passed into the addTextChangedListener() method of the EditText. Here is an example use:
editText.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable e) {
String textFromEditView = e.toString();
validateText(textFromEditView);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//nothing needed here...
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//nothing needed here...
}
});
I will leave the implementation of the validateText(String) method as an exercise for the reader, but I imagine it should be easy enough. I would either use:
A simple Regular Expression.
Or since this case is easy enough, checking that the length of the string is 8, and reviewing each character. There is a simple utility class to inspect the characteristics of characters. Character.isDigit(char) and Character.isLetter(char)
OnKeyListener listens to every key stroke in the view. you can use that to check whether the user has entered what he is supposed.
eg : if the no of char entered is 7 then
check if it follows the reqd expression format.
There is a Class called Pattern in Android in that you can give Regular Expression to match your Requirements try this follwoing code i think it may work
Pattern p = Pattern.compile( "{7}" );
Matcher m = p.matcher(String.valueOf(edittext));
This will be true only if 7 characters are there in the Text box and then you can use some menthods like "Character.isDigit(char) and Character.isLetter(char)"

Categories

Resources