I need to change input mask dynamically. For example, if user inputs 13 digits then one mask, if 20 then another.
I am using redmadrobot:inputmask. Here is my code
ArrayList<String> affineFormats = new ArrayList<>();
affineFormats.add("[0000] [000] [000] [000]");
affineFormats.add("[0000] [0000] [0000] [0000] [0000]");
String format = "[0000] [000] [000] [000]";
MaskedTextChangedListener listener = new PolyMaskTextChangedListener(
format,
affineFormats,
true,
etCardNumber,
null,
new MaskedTextChangedListener.ValueListener() {
#Override
public void onTextChanged(boolean b, String s) {
//here some code
}
});
etCardNumber.addTextChangedListener(listener);
But when I enter the card number is used the last one added is formatted according to affineFormats. Please help me fix this problem.
From your code it looks like you are using a slightly outdated version of our library.
In v.4 we already have PolyMaskTextChangedListener merged with the MaskedTextChangedListener. We also introduced a handy utility called AffinityCalculationStrategy, which might actually help with your problem.
From our Wiki:
Affinity calculation strategy
Affinity is an integer number, which represents the similarity between the input and the current mask. Thus, the mask with the highest affinity is picked to format the output.
Affinity calculation strategy is a text field listener property allowing to alter the math behind the affinity calculation.
...
AffinityCalculationStrategy.EXTRACTED_VALUE_CAPACITY— this strategy comes in handy when the mask format radically changes depending on the extracted value length.
(and your digits are the extracted value)
Related
I'm using Vaadin 14 + Java and I want to display a textfield with monetary values including thousands separators while typing.
The separators get displayed if I load the object into my form and the textfield, but whenever I type a new value or change the existing value, the thousand-seperators doesn't show up / does not update until I saved the object to the database and got the object again.
I set the ValueChangeMode already EAGER, but I suppose the converter only gets applied when writing / loading from the database.
How can I insert/update thousand-separators on the fly while typing?
Example: When i type "1000000", I want the textfield to update to "1.000" after I typed the third zero, and to "10.000" after the next one, then "100.000" and finally "1.000.000" after the sixth and last zero.
Textfield:
money_tf = new TextField("Money in €");
money_tf.setSuffixComponent(new Span("€"));
money_tf.addThemeVariants(TextFieldVariant.LUMO_ALIGN_RIGHT);
money_tf.setValueChangeMode(ValueChangeMode.EAGER);
Binder
binder = new BeanValidationBinder<>(MyClass.class);
binder.forField(money_tf).withConverter(new PriceConverter()).bind("money");
my PriceConverter:
private static class PriceConverter extends StringToBigDecimalConverter {
public PriceConverter() {
super(BigDecimal.ZERO, "Cannot convert to decimal value.");
}
#Override
protected NumberFormat getFormat(Locale locale) {
final NumberFormat format = super.getFormat(locale);
format.setGroupingUsed(true); // enabled thousand separators
if (format instanceof DecimalFormat) {
// Always display currency with two decimals
format.setMaximumFractionDigits(2);
format.setMinimumFractionDigits(2);
}
return format;
}
}
I set the ValueChangeMode already EAGER, but I suppose the converter only gets applied when writing / loading from the database.
This works, but server round trip is involved. If you do not have set-up automatic commit of every change to backend, the database is not update on every letter, only when you call explicitly binder.writeBean(..) and commit the changes to database. In fast typing on slow networks the user experience may not be the best possible.
How can I insert/update thousand-separators on the fly while typing?
I understand your question as, can the conversion be done in the client side, i.e. Browser. And the answer is yes. For simple cases you can use textField.setPattern(regexp) where regexp is a String with regular expression pattern. For more complex scenarios it requires of course some JavaScript logic, but do not worry, there is TextField Formatter add-on in the Directory, that wraps Cleave JS library and gives you nice Java API for this purpose.
Alternatively you can use BigDecimalFieldField component of the framework, which also limits the input to certain number format. The value type of that field is not String, but BigDecimal.
I'm working on an application where I've to generate code like Google classroom. When a user creates a class I generate code using following functions
private String codeGenerator(){
StringBuilder stringBuilder=new StringBuilder();
String chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
int characterLength=chars.length();
for(int i=0;i<5;i++){
stringBuilder.append(chars.charAt((int)Math.floor(Math.random()*characterLength)));
}
return stringBuilder.toString();
}
As I have 62 different characters. I can generate total 5^62 code total which is quite large. I can generate this code in server or user device. So my question is which one is better approach? How likely a generated code will conflict with another code?
From a comment, it seems that you are generating group codes for your own application.
For the purposes and scale of your app, 5-character codes may be appropriate. But there are several points you should know:
Random number generators are not designed to generate unique numbers. You can generate a random code as you're doing now, but you should check that code for uniqueness (e.g., check it against a table that stores group codes already generated) before you treat that code as unique.
If users are expected to type in a group code, you should include a way to check whether a group code is valid, to avoid users accidentally joining a different group than intended. This is often done by adding a so-called "checksum digit" to the end of the group code. See also this answer.
It seems that you're trying to generate codes that should be hard to guess. In that case, Math.random() is far from suitable (as is java.util.Random) — especially because the group codes are so short. Use a secure random generator instead, such as java.security.SecureRandom (fortunately for you, its security issues were addressed in Android 4.4, which, as I can tell from a comment of yours, is the minimum Android version your application supports; see also this question). Also, if possible, make group codes longer, such as 8 or 12 characters long.
For more information, see Unique Random Identifiers.
Also, there is another concern. There is a serious security issue if the 5-character group code is the only thing that grants access to that group. Ideally, there should be other forms of authorization, such as allowing only logged-in users or certain logged-in users—
to access the group via that group code, or
to accept invitations to join the group via that group code (e.g., in Google Classroom, the PERMISSION_DENIED error code can be raised when a user tries to accept an invitation to join a class).
The only way to avoid duplicates in your scheme is to keep a copy of the ones that you have already generated, and avoid "generating" anything that would result in a duplicate. Since 5^62 is a lot, you could simply store them on a table if using a database; or on a hashset if everything is in-memory and there is only one instance of the application (remember to save the list of generated IDs to disk every time you create a new one, and to re-read it at startup).
The chances of a collision are low: you would need to generate around 5^(62/2) = 5^31 ~= 4.6E21 really-random identifiers for a collision to be more likely than not (see birthday paradox) - and it would take a lot of space to store and check all those identifiers for duplicates to detect that this was the case. But such is the price of security.
Que: A sack contains a blue ball and a red ball. I draw one ball from the sack. What are the chances it is a red ball?
Ans: 1/2
Que: I have a collection of 5^62 unique codes. I choose one code from the collection. What are the chances that it is "ABCDE"?
Ans: 1/(5^62)
NOTE: Random number generators are not actually random.
Well, in case you need a unique generator, what about the following. This is definitely not a random, but it's definitely unique for one instance.
public final class UniqueCodeGenerator implements Supplier<String> {
private int code;
#Override
public synchronized String get() {
return String.format("%05d", code++);
}
public static void main(String... args) {
Supplier<String> generator = new UniqueCodeGenerator();
for (int i = 0; i < 10; i++)
System.out.println(generator.get());
}
}
I am new to Java and using the JIRA MISC Custom Fields add-on and require some logic assistance to solve math functions between two drop down fields.
Field one is "User Cost"
This field contains four string selections with the user price posted at the end of the string.
sam costs .21
mitch costs .419
Lance costs 2.66
xmen costs 13.338
Field two is "Usage"
This field contains two string selections:
24 hours (unless maintenance)
12 Hours (7a-7p)
The argument should be invoked into a new field called "Total User Cost." This field would automatically display the correct price for user and usage amount.
The equation blueprint would be as follows:
Cost*31(calendar days)*usage(12 || 24)
I would want my form to update based on user input selection of these two fields and other variables in my equation.
This is what I have so far:
[
Thank you in advance for any feedback!
If I understand correctly, you first need to initialize issue to something. (It looks red in your images like that variable doesn't exist)
Then, you can do something like this
double costSam = 0.21;
String userSam = issue.get("customfield_10620");
Then, if you are needing to convert or otherwise do some math on userSam, then you need this
double samTotal = costSam * Double.parseDouble(userSam);
Some flaws with your code
You have to define types for your values like String or double.
If you have String x = "hello" on one line, then x = 0.4 on the next, that won't work because of incompatible types
If you did have compatible types on consecutive lines, then the first line is pointless unless using the value from the first, as the second line overwrites the value of the first one
I need to compare two phone numbers to determine if they're from the same sender/receiver. The user may send a message to a contact, and that contact may reply.
The reply usually comes in
+[country-code][area-code-if-any][and-then-the-actual-number] format. For example,
+94 71 2593276 for a Sri Lankan phone number.
And when the user sends a message, he will usually enter in the format (for the above example) 0712593276 (assume he's also in Sri Lanka).
So what I need is, I need to check if these two numbers are the same. This app will be used internationally. So I can't just replace the first 2 digits with a 0 (then it will be a problem for countries like the US). Is there any way to do this in Java or Android-specifically?
Thanks.
Android has nice PhoneNumberUtils, and i guess your looking for :
public static boolean compare (String a, String b)
look in :
http://developer.android.com/reference/android/telephony/PhoneNumberUtils.html
using it should look like this :
String phone1
String phone2
if (PhoneNumberUtils.compare(phone1, phone2)) {
//they are the same do whatever you want!
}
android.telephony.PhoneNumberUtils class provides almost all necessary functions to deal with phone numbers and standards.
For your case, the solution is PhoneNumberUtils.compare(Context context, String number1, String number2) or else PhoneNumberUtils.compare(String number1, String number2).The former one checks a resource to determine whether to use a strict or loose comparison algorithm, thus the better choice in most cases.
PhoneNumberUtils.compare("0712593276", "+94712593276") // always true
PhoneNumberUtils.compare("0712593276", "+44712593276") // always true
// true or false depends on the context
PhoneNumberUtils.compare(context, "0712593276", "+94712593276")
Take a look at the official documentation. And the source code.
How about checking if the number is a substring of the receiver's number?
For instance, let's say my Brazilian number is 888-777-666 and yours is 111-222-333.
To call you, from here, I need to dial additional numbers to make international calls. Let's say I need to add 9999 + your_number, resulting in 9999111222333.
If RawNumber.substring(your_number) returns true I can say that I'm calling you.
just apply your logic to remove () and -
and follow PhoneNumberUtils
I'm a beginner in Java, and NetBeans. I'm trying to make a simple program where you introduce 2 numbers and their sum gets divided by two. However, I'm using JFormattedTExtFields and I don't know how to customize the allowed input in them. Basically I'm trying to find out how to:
Only allow numbers to be entered in JFormmatedTextField;
Only allow a certain amount of numbers;
You could use a NumberFormat and specify the maximum number of integer digits with setMaximumIntegerDigits.
Here's a nice article.
Basically you can do something like:
NumberFormat f = NumberFormat.getNumberInstance();
f.setMaximumIntegerDigits(maxDigitsAmount);
JFormattedTextField field = new JFormattedTextField(f);
The Format should guarantee that the inserted String satisfy the format. Anyway even if a number is supplied, the textfield will store it as a String. So if you need your original Integer you need to rebuild it like suggested #noise:
Integer i = Integer.toString(field.getText());