Remove string from string - android

String startTag = "<sessionid>";
String endTag = "</sessionid>";
if (startTag.equalsIgnoreCase("<sessionid>") &&
endTag.equalsIgnoreCase("</sessionid>"))
{
int startLocation = strResponse.indexOf(startTag);
int endLocation = strResponse.indexOf(endTag);
Log.i("StartLocation", ""+startLocation);
Log.i("EndLocation", ""+endLocation);
String session_id = strResponse.substring(startLocation, endLocation);
ConstantData.session_id =session_id;
Log.i("SessionId", ""+session_id);
}
I am getting session_id = <sessionid>32423jhoijhoijh; so I want to remove <sessionid>. Any help will be appreciated.

int startLocation = strResponse.indexOf(startTag) + string length of startTag

Just remove the first 11 letters or characters from the String:
String startTag = "<sessionid>";
String endTag = "</sessionid>";
if (startTag.equalsIgnoreCase("<sessionid>") &&
endTag.equalsIgnoreCase("</sessionid>"))
{
int startLocation = strResponse.indexOf(startTag);
int endLocation = strResponse.indexOf(endTag);
Log.i("StartLocation", ""+startLocation);
Log.i("EndLocation", ""+endLocation);
String session_id = strResponse.substring(startLocation, endLocation);
session_id = session_id.substring(11, session_id.length());
ConstantData.session_id =session_id;
Log.i("SessionId", ""+session_id);
}

Take the length of "<sessionid>" as your startIndex instead of indexOf.

One might try regular expressions too;
String str = "<sessionid>ABCDEFGH</sessionid>";
str = str.replaceFirst("<sessionid>(\\S+)</sessionid>", "$1");

Related

How can I convert numbers to currency format in android

I want to show my numbers in money format and separate digits like the example below:
1000 -----> 1,000
10000 -----> 10,000
100000 -----> 100,000
1000000 -----> 1,000,000
Thanks
Another approach :
NumberFormat format = NumberFormat.getCurrencyInstance();
format.setMaximumFractionDigits(0);
format.setCurrency(Currency.getInstance("EUR"));
format.format(1000000);
This way, it's displaying 1 000 000 € or 1,000,000 €, depending on device currency's display settings
You need to use a number formatter, like so:
NumberFormat formatter = new DecimalFormat("#,###");
double myNumber = 1000000;
String formattedNumber = formatter.format(myNumber);
//formattedNumber is equal to 1,000,000
Hope this helps!
double number = 1000000000.0;
String COUNTRY = "US";
String LANGUAGE = "en";
String str = NumberFormat.getCurrencyInstance(new Locale(LANGUAGE, COUNTRY)).format(number);
//str = $1,000,000,000.00
Currency formatter.
public static String currencyFormat(String amount) {
DecimalFormat formatter = new DecimalFormat("###,###,##0.00");
return formatter.format(Double.parseDouble(amount));
}
Use this:
int number = 1000000000;
String str = NumberFormat.getNumberInstance(Locale.US).format(number);
//str = 1,000,000,000
This Method gives you the exact output which you need:
public String currencyFormatter(String num) {
double m = Double.parseDouble(num);
DecimalFormat formatter = new DecimalFormat("###,###,###");
return formatter.format(m);
}
Try the following solution:
NumberFormat format = NumberFormat.getCurrencyInstance();
((TextView)findViewById(R.id.text_result)).setText(format.format(result));
The class will return a formatter for the device default currency.
You can refer to this link for more information:
https://developer.android.com/reference/java/text/NumberFormat.html
Here's a kotlin Extension that converts a Double to a Currency(Nigerian Naira)
fun Double.toRidePrice():String{
val format: NumberFormat = NumberFormat.getCurrencyInstance()
format.maximumFractionDigits = 0
format.currency = Currency.getInstance("NGN")
return format.format(this.roundToInt())
}
Use a Formatter class
For eg:
String s = (String.format("%,d", 1000000)).replace(',', ' ');
Look into:
http://developer.android.com/reference/java/util/Formatter.html
The way that I do this in our app is this:
amount.addTextChangedListener(new CurrencyTextWatcher(amount));
And the CurrencyTextWatcher is this:
public class CurrencyTextWatcher implements TextWatcher {
private EditText ed;
private String lastText;
private boolean bDel = false;
private boolean bInsert = false;
private int pos;
public CurrencyTextWatcher(EditText ed) {
this.ed = ed;
}
public static String getStringWithSeparator(long value) {
DecimalFormat formatter = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US);
String f = formatter.format(value);
return f;
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
bDel = false;
bInsert = false;
if (before == 1 && count == 0) {
bDel = true;
pos = start;
} else if (before == 0 && count == 1) {
bInsert = true;
pos = start;
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
lastText = s.toString();
}
#Override
public void afterTextChanged(Editable s) {
ed.removeTextChangedListener(this);
StringBuilder sb = new StringBuilder();
String text = s.toString();
for (int i = 0; i < text.length(); i++) {
if ((text.charAt(i) >= 0x30 && text.charAt(i) <= 0x39) || text.charAt(i) == '.' || text.charAt(i) == ',')
sb.append(text.charAt(i));
}
if (!sb.toString().equals(s.toString())) {
bDel = bInsert = false;
}
String newText = getFormattedString(sb.toString());
s.clear();
s.append(newText);
ed.addTextChangedListener(this);
if (bDel) {
int idx = pos;
if (lastText.length() - 1 > newText.length())
idx--; // if one , is removed
if (idx < 0)
idx = 0;
ed.setSelection(idx);
} else if (bInsert) {
int idx = pos + 1;
if (lastText.length() + 1 < newText.length())
idx++; // if one , is added
if (idx > newText.length())
idx = newText.length();
ed.setSelection(idx);
}
}
private String getFormattedString(String text) {
String res = "";
try {
String temp = text.replace(",", "");
long part1;
String part2 = "";
int dotIndex = temp.indexOf(".");
if (dotIndex >= 0) {
part1 = Long.parseLong(temp.substring(0, dotIndex));
if (dotIndex + 1 <= temp.length()) {
part2 = temp.substring(dotIndex + 1).trim().replace(".", "").replace(",", "");
}
} else
part1 = Long.parseLong(temp);
res = getStringWithSeparator(part1);
if (part2.length() > 0)
res += "." + part2;
else if (dotIndex >= 0)
res += ".";
} catch (Exception ex) {
ex.printStackTrace();
}
return res;
}
Now if you add this watcher to your EditText, as soon as user enter his number, the watcher decides whether it needs separator or not.
i used this code for my project and it works:
EditText edt_account_amount = findViewById(R.id.edt_account_amount);
edt_account_amount.addTextChangedListener(new DigitFormatWatcher(edt_account_amount));
and defined class:
public class NDigitCardFormatWatcher implements TextWatcher {
EditText et_filed;
String processed = "";
public NDigitCardFormatWatcher(EditText et_filed) {
this.et_filed = et_filed;
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable editable) {
String initial = editable.toString();
if (et_filed == null) return;
if (initial.isEmpty()) return;
String cleanString = initial.replace(",", "");
NumberFormat formatter = new DecimalFormat("#,###");
double myNumber = new Double(cleanString);
processed = formatter.format(myNumber);
//Remove the listener
et_filed.removeTextChangedListener(this);
//Assign processed text
et_filed.setText(processed);
try {
et_filed.setSelection(processed.length());
} catch (Exception e) {
// TODO: handle exception
}
//Give back the listener
et_filed.addTextChangedListener(this);
}
}
Updated 2022 answer
Try this snippet. It formats a number in string complete with the currency & setting fractional digits.
Upvote if this helped you! :)
/**
* Formats amount in string to human-readable amount (separated with commas
* & prepends currency symbol)
*
* #param amount The amount to format in String
* #return The formatted amount complete with separators & currency symbol added
*/
public static String formatCurrency(String amount) {
String formattedAmount = amount;
try {
if (amount == null || amount.isEmpty())
throw new Exception("Amount is null/empty");
Double amountInDouble = Double.parseDouble(amount);
NumberFormat numberFormat = NumberFormat.getCurrencyInstance(new Locale("en", "IN"));
numberFormat.setMaximumFractionDigits(2);
numberFormat.setMinimumFractionDigits(2);
formattedAmount = numberFormat.format(amountInDouble);
} catch (Exception exception) {
exception.printStackTrace();
return formattedAmount;
}
return formattedAmount;
}
private val currencyFormatter = NumberFormat.getCurrencyInstance(LOCALE_AUS).configure()
private fun NumberFormat.configure() = apply {
maximumFractionDigits = 2
minimumFractionDigits = 2
}
fun Number.asCurrency(): String {
return currencyFormatter.format(this)
}
And then just use as
val x = 100000.234
x.asCurrency()
If you have the value stored in a String like me, which was coming from the server like "$20000.00".
You can do something like this in Kotlin (JetpackCompose):
#Composable
fun PrizeAmount(
modifier: Modifier = Modifier,
prize: String,
)
{
val currencyFormat = NumberFormat.getCurrencyInstance(Locale("en", "US"))
val text = currencyFormat.format(prize.substringAfter("$").toDouble())
...
}
Output: "$20,000.00"
NumberFormat.getCurrencyInstance(Locale("ES", "es")).format(number)
here is a kotlin version to Format Currency, here i'm getting an argument from another fragment from an input Field then it will be set in the textView in the main Fragment
fun formatArgumentCurrency(argument : String, textView: TextView) {
val valueText = requireArguments().get(argument).toString()
val dec = DecimalFormat("#,###.##")
val number = java.lang.Double.valueOf(valueText)
val value = dec.format(number)
val currency = Currency.getInstance("USD")
val symbol = currency.symbol
textView.text = String.format("$symbol$value","%.2f" )
}
You can easily achieve this with this small simple library.
https://github.com/jpvs0101/Currencyfy
Just pass any number, then it will return formatted string, just like that.
currencyfy (500000.78); // $ 500,000.78 //default
currencyfy (500000.78, false); // $ 500,001 // hide fraction (will round off automatically!)
currencyfy (500000.78, false, false); // 500,001 // hide fraction & currency symbol
currencyfy (new Locale("en", "in"), 500000.78); // ₹ 5,00,000.78 // custom locale
It compatible with all versions of Android including older versions!

Android: How to set substrings in lowercase in my string?

I want to set all my hashtags in lowercase in a string:
"Hello I'm a men #Athlete et I'm going to do sport #NeverGiveUp"
Should become:
"Hello I'm a men #athlete et I'm going to
do sport #nevergiveup"
if your problem is how to convert all to simple letters hope this helps
String myString = "HashTag";
String myNewSimpleLetterString = myString.substring(0,5).toLowerCase(); //subString will get the characters from 0 - 5
Try this code
Just pass your string to this method this method returns formatted String
public static String changeFormat(String beforeFormatStr) {
String[] arrStr = beforeFormatStr.split(" ");
String afterFormatStr = "";
int wordPos = 0;
for (String word : arrStr) {
String changeStr = word;
if (word.contains("#")) {
changeStr = word.toLowerCase();
}
if (wordPos == 0) {
afterFormatStr += changeStr;
} else {
afterFormatStr += " " + changeStr;
}
wordPos++;
}
return afterFormatStr;
}
You can use Regular expression for finding and replacing hashtags to lowercase. Like :
String line = "Hello I'm a men #Athlete et I'm going to do sport #NeverGiveUp";
String regEx = "\\S*#(?:\\[[^\\]]+\\]|\\S+)"; //Regular expression for matching hashtag
StringBuffer sb = new StringBuffer();
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(line);
while (m.find())
{
// Avoids throwing a NullPointerException in the case that you
// Don't have a replacement defined in the map for the match
String repString = m.group();
if (repString != null)
repString = repString.toLowerCase();
m.appendReplacement(sb, repString);
}
m.appendTail(sb);
String replacedHashtag = sb.toString();
Hash is not a string, so you have to use Regx matcher and Pattern to achieve this.
List<String> obtained_hashwords = new ArrayList<>();
String text_data = "Hello I'm a men #Athlete et I'm going to do sport #NeverGiveUp and I want to format this string";
Pattern pattern = Pattern.compile("#\\w+");
Matcher matcher = pattern.matcher(text_data);
while (matcher.find())
{
obtained_hashwords.add(matcher.group());
Log.d("Hash word",matcher.group());
}
for (String obtained_hashword:obtained_hashwords)
{
String no_hash = obtained_hashword.replace("#","");
String lower_case_word = "#"+no_hash.toLowerCase();
text_data = text_data.replace(obtained_hashword,lower_case_word);
}
Log.d("changed line",text_data);

Truncate word at end of string in Textview not char from last

Truncate String At End using this code
CharSequence charSequence;
float avail = 8 * content.getMeasuredWidth();
charSequence = TextUtils.ellipsize(textString,textview.getPaint(),avail, TextUtils.TruncateAt.END);
this code giving me result like this truncating last word and showing dots
hello wor...
but i need truncate also last word at end like below
hello
set character length . simply
protected String genrateString(String source, int numberOfWords){
BreakIterator iterator = BreakIterator.getSentenceInstance(Locale.US);
iterator.setText(source);
int start = iterator.first();
StringBuffer sb = new StringBuffer();
for (int end = iterator.next();end != BreakIterator.DONE;start = end, end = iterator.next()) {
String newSentence =source.substring(start,end);
int currentWordCount = countWord(sb.toString());
int newWordCount = currentWordCount + countWord(newSentence);
if(newWordCount-numberOfWords >= 0.1*numberOfWords) {
if(currentWordCount<numberOfWords && numberOfWords-currentWordCount > newWordCount-numberOfWords)
sb.append(newSentence);
else
break;
}
else
sb.append(newSentence);
}
return sb.toString();
}

Check if next char in a string is a space

I would like to check if the current char is a blank space as i dont want to change that. So i would like to change all the letters like i do now, but keep the spaces.
e.g. "that man" with C = 2 should become "vjcv ocp".
thanks in advance :)
String initialString = yourString.getText().toString();
char[] chars = initialString.toCharArray();
for (int i = 1; i <= chars.length; i++) {
C = Integer.valueOf(ceasarNr);
chars[i-1] = characters.get((characters.indexOf(chars[i-1]) + C)%29);
}
String resultString = new String(chars);
krypteredeTekst.setText(resultString);
}
Just skip the iteration if the character is a space:
String initialString = yourString.getText().toString();
char[] chars = initialString.toCharArray();
for (int i = 1; i <= chars.length; i++) {
//Skip if it is space.
if chars[i-1] == ' ';
continue;
C = Integer.valueOf(ceasarNr);
chars[i-1] = characters.get((characters.indexOf(chars[i-1]) + C)%29);
}
String resultString = new String(chars);
krypteredeTekst.setText(resultString);
}
There is method for checking if char is blank space ->
String initialString = yourString.getText().toString();
char[] chars = initialString.toCharArray();
for (int i = 1; i <= chars.length; i++) {
C = Integer.valueOf(ceasarNr);
if(!Character.isWhitespace(chars.charAt(i-1)) {
chars[i-1] = characters.get((characters.indexOf(chars[i-1]) + C)%29);
}
}
String resultString = new String(chars);
krypteredeTekst.setText(resultString);

Android random string generator

I have a problem.
I want to draw a random String something like this aXcFg3s2.
What i doing bad ?
How change my random()
private String random;
private String charsEntered;
private EditText et;
private Button ok;
CaptchaInterface.OnCorrectListener mCorrectListener;
public void setOnCorrectListener(CaptchaInterface.OnCorrectListener listener) {
mCorrectListener = listener;
}
public TextCaptcha(Context context) {
super(context);
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
}
public static String random() {
Random generator = new Random();
String x = (String) (generator.nextInt(96) + 32);
return x;
}
public void onCreate(Bundle icicle) {
setContentView(R.layout.main);
random = random();
TextView display = (TextView) findViewById(R.id.textView1);
display.setText("Random Number: " + random); // Show the random number
et = (EditText) findViewById(R.id.etNumbers);
ok = (Button) findViewById(R.id.button1);
ok.setOnClickListener(this);
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
charsEntered = et.getText().toString();
} catch (NumberFormatException nfe) {
Toast.makeText(et.getContext(), "Bla bla bla",
Toast.LENGTH_LONG).show();
}
if (random == charsEntered) {
Toast.makeText(et.getContext(), "Good!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(et.getContext(), "Bad!", Toast.LENGTH_LONG).show();
}
}
the problem is that you've handled only a single character instead of using a loop.
you can create an array of characters which has all of the characters that you wish to allow to be in the random string , then in a loop take a random position from the array and add append it to a stringBuilder . in the end , convert the stringBuilder to a string.
EDIT:
here's the simple algorithm i've suggested:
private static final String ALLOWED_CHARACTERS ="0123456789qwertyuiopasdfghjklzxcvbnm";
private static String getRandomString(final int sizeOfRandomString)
{
final Random random=new Random();
final StringBuilder sb=new StringBuilder(sizeOfRandomString);
for(int i=0;i<sizeOfRandomString;++i)
sb.append(ALLOWED_CHARACTERS.charAt(random.nextInt(ALLOWED_CHARACTERS.length())));
return sb.toString();
}
and on Kotlin:
companion object {
private val ALLOWED_CHARACTERS = "0123456789qwertyuiopasdfghjklzxcvbnm"
}
private fun getRandomString(sizeOfRandomString: Int): String {
val random = Random()
val sb = StringBuilder(sizeOfRandomString)
for (i in 0 until sizeOfRandomString)
sb.append(ALLOWED_CHARACTERS[random.nextInt(ALLOWED_CHARACTERS.length)])
return sb.toString()
}
There are a few things wrong with your code.
You cannot cast from an int to a string. Cast it to a char instead. This however will only give you a single char so instead you could generate a random number for the length of your string. Then run a for loop to generate random chars. You can define a StringBuilder as well and add the chars to that, then get your random string using the toString() method
example:
public static String random() {
Random generator = new Random();
StringBuilder randomStringBuilder = new StringBuilder();
int randomLength = generator.nextInt(MAX_LENGTH);
char tempChar;
for (int i = 0; i < randomLength; i++){
tempChar = (char) (generator.nextInt(96) + 32);
randomStringBuilder.append(tempChar);
}
return randomStringBuilder.toString();
}
Also, you should use random.compareTo() rather than ==
You need to import UUID.
Here is the code
import java.util.UUID;
id = UUID.randomUUID().toString();
this is how i generate my random strings with desired characters and desired length
char[] chars1 = "ABCDEF012GHIJKL345MNOPQR678STUVWXYZ9".toCharArray();
StringBuilder sb1 = new StringBuilder();
Random random1 = new Random();
for (int i = 0; i < 6; i++)
{
char c1 = chars1[random1.nextInt(chars1.length)];
sb1.append(c1);
}
String random_string = sb1.toString();
This function run in kotlin ->
fun randomString(stringLength: Int): String {
val list = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray()
var randomS = ""
for (i in 1..stringLength) {
randomS += list[getRandomNumber(0, list.size - 1)]
}
return randomS
}
fun getRandomNumber(min: Int, max: Int): Int {
return Random().nextInt((max - min) + 1) + min
}
Or you can use my library
https://github.com/Aryan-mor/Utils-Library
You can simply use the following method to generate random String with 5 character and it will return arrayList of random String
public ArrayList<String> generateRandomString() {
ArrayList<String> list = new ArrayList<>();
Random rnd = new Random();
String str = "";
String randomLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String randomLetterSmall = "abcdefghijklmnopqrstuvwxyz";
for (int n = 0; n < 50; n++) {
str = String.valueOf(randomLetters.charAt(rnd.nextInt(randomLetters.length())));
str += String.valueOf(randomLetterSmall.charAt(rnd.nextInt(randomLetters.length())));
str += String.valueOf(randomLetterSmall.charAt(rnd.nextInt(randomLetters.length())));
str += String.valueOf(randomLetterSmall.charAt(rnd.nextInt(randomLetters.length())));
str += String.valueOf(randomLetterSmall.charAt(rnd.nextInt(randomLetters.length())));
//Copy above line to increase character of the String
list.add(str);
}
Collections.sort(list);
return list;
}
private fun getRandomHexString(numchars: Int): String? {
val r = Random()
val sb = StringBuffer()
while (sb.length < numchars) {
sb.append(Integer.toHexString(r.nextInt()))
}
return sb.toString().substring(0, numchars)
}
You cannot cast an int to a String. Try:
Random generator = new Random();
String x = String.valueOf (generator.nextInt(96) + 32);
final String[] Textlist = { "Text1", "Text2", "Text3"};
TextView yourTextView = (TextView)findViewById(R.id.yourTextView);
Random random = new Random();
String randomText = TextList[random.nextInt(TextList.length)];
yourTextView.setText(randomText);
Quick one liner using the org.apache.commons.lang3.RandomStringUtils package.
String randonString = RandomStringUtils.randomAlphanumeric(16);
Requires the library dependency in the gradle build file:
implementation 'org.apache.commons:commons-text:1.6'
You can simply convert current time (in millis) to string such as
import java.util.Calendar;
String newRandomId = String.valueOf(Calendar.getInstance().getTimeInMillis());
Or
String newRandomId = Calendar.getInstance().getTimeInMillis() + "";
//Eg: output: "1602791949543"

Categories

Resources