'How to make Textview will only show the last 4 digits numbers
My Textview is getting the data from SQLite, but I want to make Textview to show as follows:
************1234, instead of 1234123412341234.
Solution 1:[1]
public static String padLeading*(String data, int requiredLength){
StringBuffer sb = new StringBuffer();
if(data .length() > 4){
data .substring(data .length() - 4)
}
int numLeading* = requiredLength - data.length();
for (int i=0; i < numLeading*; i++){
sb.append("*");
}
sb.append(data);
return sb.toString();
}
Advantage of this method is that you could vary the number of * as required. Or to make it simpler could determine the last four characters of the string, pass it in and take:
if(data .length() > 4){
data .substring(data .length() - 4)
}
out of this method.
Solution 2:[2]
Kotlin solution
acNumber.replace("\\w(?=\\w{4})".toRegex(),"*")
Solution 3:[3]
String string = "1234567890";
if(string .length() > 4){
string .substring(string .length() - 4)
}
tv.setText(string);
output: 7890
Solution 4:[4]
You can hard code "*" in the beginning and extract last 4 digits of credit card num from sqlite and display on text view.
String lastFourDigits = extractLastFourDigits(); //I assume you get this
myTextView.setText("**** **** **** "+lastFourDigits);
Solution 5:[5]
You want to use a TransformationMethod You can use the source of PasswordTransformationMethod as a guide so you don't lose the original string.
Solution 6:[6]
Here you go. Clean and reusable:
/**
* Applies the specified mask to the card number.
*
* @param cardNumber The card number in plain format
* @param mask The number mask pattern. Use # to include a digit from the
* card number at that position, use x to skip the digit at that position
*
* @return The masked card number
*/
public static String maskCardNumber(String cardNumber, String mask) {
// format the number
int index = 0;
StringBuilder maskedNumber = new StringBuilder();
for (int i = 0; i < mask.length(); i++) {
char c = mask.charAt(i);
if (c == '#') {
maskedNumber.append(cardNumber.charAt(index));
index++;
} else if (c == 'x') {
maskedNumber.append(c);
index++;
} else {
maskedNumber.append(c);
}
}
// return the masked number
return maskedNumber.toString();
}
Sample Calls:
System.out.println(maskCardNumber("1234123412341234", "xxxx-xxxx-xxxx-####"));
> xxxx-xxxx-xxxx-1234
System.out.println(maskCardNumber("1234123412341234", "##xx-xxxx-xxxx-xx##"));
> 12xx-xxxx-xxxx-xx34
Solution 7:[7]
stringData.replaceRange(0, stringData.length - 2, "*")
I hope it will work
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user8537453 |
| Solution 2 | Vikash Parajuli |
| Solution 3 | Yoni |
| Solution 4 | Aalap Patel |
| Solution 5 | Ge3ng |
| Solution 6 | AbhinayMe |
| Solution 7 |
