I have multiple value in single string, but I want to send in every string value on new line. I have written the following code, but it's not working.
String text ="Address" + strpropertyAddress +"\n"+ "Price" + strPrice;
This is my service method where i pass the string.
sendPropertyApi(text, sendto);
I have checked every where, and it is exactly same. Basically the string data should be sent in on a new line, but it's sent in on a single line.
Assuming(Because of Android tag) you are setting this text in textView or editText, for that I think you have to escape \. So use \\n instead. Try following:
String text ="Address" + strpropertyAddress +"\\n"+ "Price" + strPrice;
Or it is always better to use default line separator like following:
String text ="Address" + strpropertyAddress +System.getProperty("line.separator")+ "Price" + strPrice;
I am fetching number from contact book and sending it to server. i get number like this (+91)942 80-60 135 but i want result like this +9428060135.+ must be first character of string number.
Given your example you want to replace the prefix with a single + character. You also want to remove other non-numeric characters from the number string. Here's how you can do that:
String number = "(+91)942 80-60 135";
number = "+" + number.replaceAll("\\(\\+\\d+\\)|[^\\d]", "");
The regex matches any prefix (left paren followed by a + followed by one or more digits, followed by a right paren) or any non digit character, and removes them. This is concatenated to a leading + as required. This code will also handle + characters within the number string, e.g. +9428060135+++ and +(+91)9428060135+++.
If you simply wanted to remove any character that is not a digit nor a +, the code would be:
String number = "(+91)942 80-60 135";
number = number.replaceAll("[^\\d+]", "");
but be aware that this will retain the digits in the prefix, which is not the same as your example.
You can use String.replace(oldChar, newChar). Use the code below
String phone = "(+91)942 80-60 135"; // fetched string
String trimmedPhone = phone.replace("(","").replace(")","").replace("-","").trim();
I hope it will work for you.
check this. Pass your string to this function or use as per code goes
String inputString = "(+91)942 80-60 135";
public void removeSpecialCharacter(String inputString) {
String replaced = inputString.replaceAll("[(\\-)]", "");
String finalString = replaced.replaceAll(" ", "");
Log.e("String Output", " " + replaced + " " + second);
}
I want use register in my application and i should send password and verifyCode with SMS to users phones.
But i should read verifyCode from message and set automatically number into verifyCode EditText.
My message format :
Hi, welcome to our service.
your password 12345
your verifyCode 54321
How can i do it? Please help me <3
Assuming that the number of digits are fixed in password and verify codes (Generally they are same as default values), We can extract digits from the string and then find substring which has verify code. This assumption is for simplicity.
String numberOnly= str.replaceAll("[^0-9]", "");
String verifyCode = numberOnly.substring(6);
Here String verifyCode = numberOnly.substring(6); is getting last 5 digits of the string which is your verification code. You can also write numberOnly.substring(6,10); to avoid confusions.
But this is prone to errors like StringIndexOutOfBoundsException, So whenever you want to get substring which is starting from index i till the end of the string, always write numberOnly.substring(i).
There are a lot ways to do this. You can use some complicated regex or use a simple spilt method.
Try this,
String str = "Hi, welcome to our service.\n"
+ "\n"
+ "your password \n"
+ "12345\n"
+ "\n"
+ "your verifyCode \n"
+ "54321";
// Solution #1
String[] parts = str.split("\n");
System.out.println(parts[3]);
System.out.println(parts[6]);
// Solution #2
String PAT = "(password|verifyCode)\\s+(\\d+)";
Pattern pats = Pattern.compile(PAT);
Matcher m = pats.matcher(str);
while (m.find()) {
String grp = m.group(2);
System.out.println(grp);
}
sumTextView.setText(Integer.toString(a) + " + " + Integer.toString(b));
This Line show warning you see in pic..
Use String.format();
sumTextView.setText(String.format("%1$d + %2$d", a, b));
With this you can format a string correctly with multiple variables, no matter whether they are strings or integers. This example takes the value of variable a and replaces the placeholder %1$d with it. Same goes for the other variable.
take an string copy whole line in it, then show string in setText
String str = (Integer.toString(a) + " + " + Integer.toString(a));
sumTextView.setText(str);
1. The First String Says that do not concate string with setText property.
String txt = String.valueOf(a) + " + " + String.valueOf(b);
sumTextView.setText(str);
2. Second warning says that your program have possibility to crash or genearte an exception in case if value of a or b is null or not an integer.
So check condition if(a!=null and b!=null) then display text in if condition.
I am setting text using setText() by following way.
prodNameView.setText("" + name);
prodOriginalPriceView.setText("" + String.format(getString(R.string.string_product_rate_with_ruppe_sign), "" + new BigDecimal(price).setScale(2, RoundingMode.UP)));
In that First one is simple use and Second one is setting text with formatting text.
Android Studio is so much interesting, I used Menu Analyze -> Code Cleanup and i got suggestion on above two lines like.
Do not concatenate text displayed with setText. Use resource string
with placeholders. less... (Ctrl+F1)
When calling TextView#setText:
Never call Number#toString() to format numbers; it will not handle fraction separators and locale-specific digits properly. Consider
using String#format with proper format specifications (%d or %f)
instead.
Do not pass a string literal (e.g. "Hello") to display text. Hardcoded text can not be properly translated to other languages.
Consider using Android resource strings instead.
Do not build messages by concatenating text chunks. Such messages can not be properly translated.
What I can do for this? Anyone can help explain what the thing is and what should I do?
Resource has the get overloaded version of getString which takes a varargs of type Object: getString(int, java.lang.Object...). If you setup correctly your string in strings.xml, with the correct place holders, you can use this version to retrieve the formatted version of your final String. E.g.
<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
using getString(R.string.welcome_message, "Test", 0);
android will return a String with
"Hello Test! you have 0 new messages"
About setText("" + name);
Your first Example, prodNameView.setText("" + name); doesn't make any sense to me. The TextView is able to handle null values. If name is null, no text will be drawn.
Don't get confused with %1$s and %2$d in the accepted answer.Here is a few extra information.
The format specifiers can be of the following syntax:
%[argument_index$]format_specifier
The optional argument_index is specified as a number ending with a “$” after the “%” and selects the specified argument in the argument list. The first argument is referenced by "1$", the second by "2$", etc.
The required format specifier is a character indicating how the argument should be formatted. The set of valid conversions for a given argument depends on the argument's data type.
Example
We will create the following formatted string where the gray parts are inserted programmatically.
Hello Test! you have 0 new messages
Your string resource:
< string name="welcome_messages">Hello, %1$s! You have %2$d new
messages< /string >
Do the string substitution as given below:
getString(R.string.welcome_message, "Test", 0);
Note:
%1$s will be substituted by the string "Test"
%2$d will be substituted by the string "0"
I ran into the same lint error message and solved it this way.
Initially my code was:
private void displayQuantity(int quantity) {
TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
quantityTextView.setText("" + quantity);
}
I got the following error
Do not concatenate text displayed with setText. Use resource string with placeholders.
So, I added this to strings.xml
<string name="blank">%d</string>
Which is my initial "" + a placeholder for my number(quantity).
Note: My quantity variable was previously defined and is what I wanted to append to the string. My code as a result was
private void displayQuantity(int quantity) {
TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
quantityTextView.setText(getString(R.string.blank, quantity));
}
After this, my error went away. The behavior in the app did not change and my quantity continued to display as I wanted it to now without a lint error.
Do not concatenate text inside your setText() method, Concatenate what ever you want in a String and put that String value inside your setText() method.
ex: correct way
int min = 120;
int sec = 200;
int hrs = 2;
String minutes = String.format("%02d", mins);
String seconds = String.format("%02d", secs);
String newTime = hrs+":"+minutes+":"+seconds;
text.setText(minutes);
Do not concatenate inside setText() like
text.setText(hrs+":"+String.format("%02d", mins)+":"+String.format("%02d", secs));
You should check this thread and use a placeholder like his one (not tested)
<string name="string_product_rate_with_ruppe_sign">Price : %1$d</string>
String text = String.format(getString(R.string.string_product_rate_with_ruppe_sign),new BigDecimal(price).setScale(2, RoundingMode.UP));
prodOriginalPriceView.setText(text);
Don't Mad, It's too Simple.
String firstname = firstname.getText().toString();
String result = "hi "+ firstname +" Welcome Here";
mytextview.setText(result);
the problem is because you are appending "" at the beginning of every string.
lint will scan arguments being passed to setText and will generate warnings, in your case following warning is relevant:
Do not build messages by
concatenating text chunks. Such messages can not be properly
translated.
as you are concatenating every string with "".
remove this concatenation as the arguments you are passing are already text. Also, you can use .toString() if at all required anywhere else instead of concatenating your string with ""
I fixed it by using String.format
befor :
textViewAddress.setText("Address"+address+"\n"+"nCountry"+"\n"+"City"+"city"+"\n"+"State"+"state")
after :
textViewAddress.setText(
String.format("Address:%s\nCountry:%s\nCity:%s\nState:%s", address, country, city, state));
You can use this , it works for me
title.setText(MessageFormat.format("{0} {1}", itemList.get(position).getOppName(), itemList.get(position).getBatchNum()));
If you don't need to support i18n, you can disable this lint check in Android Studio
File -> Settings -> Editor -> Inspections -> Android -> Lint -> TextView Internationalization(uncheck this)
prodNameView.setText("" + name); //this produce lint error
val nameStr="" + name;//workaround for quick warning fix require rebuild
prodNameView.setText(nameStr);
I know I am super late for answering this but I think you can store the data in a varible first then you can provide the variable name. eg:-
// Java syntax
String a = ("" + name);
String b = "" + String.format(getString(R.string.string_product_rate_with_ruppe_sign);
String c = "" + new BigDecimal(price).setScale(2, RoundingMode.UP));
prodNameView.setText(a);
prodOriginalPriceView.setText(b, c);
if it is textView you can use like that : myTextView.text = ("Hello World")
in editText you can use myTextView.setText("Hello World")