I am trying to concatenate two strings like the below Method.I Referred from dynamic String using String.xml?
String incorrect = getResources().getString(R.string.username_or_password_incorrect);
mErrorMsgId = String.format(getResources().getString(R.string.username_or_password_incorrectfull), incorrect);
it returns
error: incompatible types required: int found: String
EDIT
I need to replace the %1$s in the below string with this string R.string.username_or_password_incorrect
'<string name="username_or_password_incorrectfull">The username or password you entered is incorrect \- If you\'re a self hosted WordPress.org user, don\'t forget to tap %1$s and fill the URL field</string>'
How to solve this ?
I'm not sure it's possible. If it is, I'm not aware of it.
What you could do, is something like this;
Create 2 string, one that contains The username or password you entered is incorrect \- If you\'re a self hosted WordPress.org user, don\'t forget to tap and another one with and fill the URL field
and then contcatenate it with the 'incorrect' variable.
String a = getResources().getString(R.string.username_or_password_incorrectfull);
String b = getResources().getString(R.string.username_or_password_incorrectfull2);
String mErrorMsgId = a + incorrect + b;
Note: A better approch would be to use the StringBuilder class to concatenate different variables types, but for the sake of example, this should do.
This is very confusing, why would have mErrorMsgId as an int? change this to a String and it won't error anymore:
so change
private int mErrorMsgId;
to
private String mErrorMsgId;
Related
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")
I have a special table in my database where I store the message key - value in the form, for example: question first - How are you, ...?
Now I want to insert for example a name at the end of the question. I don't need a hardcode, I want to do it through some formatting. I know that there is an option to insert text through % or ?1 - but I don't know how to apply this in practice. How are you, % or (?1)?
And what if I need to insert text not only at the end, but also in the random parts:
Hey, (name)! Where is your brother, (brothers name)?
You can insert a String into another String using the String.format() method. Place a %s anywhere in the String where you want and then follow the below syntax. More information here.
String original = "Add to this pre-existing String";
String newString = String.format("Add %s to this pre-existing String", "words");
// original = "Add to this pre-existing String"
// newString = "Add words to this pre-existing String"
In your specific situation, you can store the names as other Strings and do this:
String name = "anyName";
String brothers_name = "anyBrotherName";
String formattedString = String.format("Hey, %s! Where is your brother, %s?", name, brothers_name);
How about this?
String.format("Hey, %s! Where is your brother, %s?","Sally", "Johnny");
For using the %, first you will need to create another variable of type string in which you store the text you want to print.
Example:
String a="Alice";
String b="Bob";
String str=string.format("Hey, %s! Where is your brother, %s?"a,b);
System.out.println(str);
Output:
Hey Alice! Where is your brother, Bob?
You can get more information about this here
I am starting out with Java and trying to find a neat way of refactoring the below code so that I can set the firstName variable as a string and in the same line get and set the firstNameLength string length as an integer.
String firstName = "Boris";
int firstNameLength = firstName.length();
I have been trying variations of the below code but to no avail!
int newAge = String firstName = "Boris".length();
You can't declare 2 new variables, but assignment of firstName is possible.
String firstName;
int newAge = (firstName = "Boris").length();
(You could put both in the same line).
I doubt however, that anyone would consider this more readable than
String firstName = "Boris";
int newAge = firstName.length();
and there are no other benefits.
There's no way you can delcare two variables of different type in one statement.
So you're stuck with 2 statements anyway. So you could put it in one line like this:
String name; int length = (name= "Boris").length();
But really, what's the point?
I guess if you want to make your code more streamlined, you should think about why you need an extra variable holding the length in the first place - as this can always be computed later. So you keep redundant information.
Actually another solution would be to use StringUtils in the following way:
int length = StringUtils.length("Boris");
But this comes with the Apache Common package.
I have a strange scenario. Query string has value first=second=12123423423423432323234
String queryString = request.getParameter("first=second=12123423423423432323234")
So i have to:
capture 'first' and 'second' values
validate the query string has 'first' and 'second'.
Could someone please share how I can achieve this in the best possible way?
I really appreciate your help on this.
I believe your query string should look like
first=firstvalue&second=secondvalue
You can use this in your servlet to print the query string
String firstValue = request.getParameter("first");
String secondValue = request.getParameter("second");
System.out.println("Query String:first="+firstValue+"second=+"secondValue);
In your case, where the query string is
first=second=12123423423423432323234
You could do this
String first = request.getParameter("first");
String second = request.getParameter("second");
if(first.contains("second=")){
second = first.split("second=")[1];
first = first.split("second=")[0];
}
out.println("[First:"+first+"][Second:"+second+"]");
If your parameters are separated properly by & (i.e. first=&second=something), then simply .getParameter("first") and .getParameter("second")
Otherwise, you'd need to play with the string - probably split around =, and for the value of first cut until second is encountered. Though I fail to see how will that work if first has a value: first=foosecond=bar?
I get this error message when i try to run my program
error: incompatible types
epost = split[3];
^
required: String[]
found: String
here is my code:
String [] split = ordre.split(" ");
String [] epostadr;
while(split >= 3) {
String [] epostadr = split[3];
}
I want to save the epostadr in split[3] but it wont let me do that because split only saves Strings while epostadr is a String [], what can i do to change this?
Any help would be greatly appreciated.
String [] epostadr = split[3];
split[3] is of type String while epostadr is of type String[]
Maybe you want to declare epostadr as String? [not sure I am following what you are trying to achieve]
First off, you don't have an array:
String [] epostadr;
This declares a variable than can have an array reference assigned to it.
Then you have:
String [] epostadr = split[3];
This makes no sense. split[3] is a String; you can't assign that to a variable declared as a String array.
If you need epostadr to be an array, you need to create one, assign it, then put the String in a specific location:
String [] epostadr = new String[maxNumberOfStrings];
...
epostadr[index] = split[3];
Edit: this is ignoring that the rest of your code doesn't actually do what you think it does. Your while loop (if it were written correctly) will loop forever; split.length is never going to change. Given these issues you may well want to invest in a beginner's guide to Java/programming, or at the very least go through the Java tutorials available on Oracle's website.
When you use split on a String, it makes it into a String[] so you got that right when making split as a String[]. However, in each array slot, there is a String. You are basically trying to making epostadr, which you declared as a String[], a String and that's where the incompatible types come from. A String[] can't be a String.
It's hard to know exactly what you're trying to do from this code so I'll go through and let you know what's happeneing. It looks like you're trying to take a string stored in the variable ordre, and split it so that each word has it's own index in a string array called split.
So if ordre contained the string "My name is Jones."
String [] split = ordre.split(" ");
That line would create an array named split containing the following values {My, name, is, Jones}
Here is the part that maybe you can clarify, it looks like you want those values to be in the string array epostadr, or maybe just the 3rd index which in this case would be "Jones" since indexes start with 0.
Putting the values in epostadr would be redundant since split already contains those values. But if you really wanted to copy it you could do this.
String [] epostadre = split;
If you wanted just the 3rd index, epostadre can't be a string array, but must be declared as a string and you would do this...
String epostadre = split[3];
Here you're declaring a String, which will hold one value, and setting it equal to the string that is contained in the 3rd index of split, which is Jones. split[0] = "My" split[1] = "name" and so on.
I hope that helps, let me know if you need more clarification.