Add only 1 char into String - android

Is it possible to change 1 char into String from code in Kotlin ?
I think yes, but I don't know how.
<string name="carID">Id: </string>
Currently I change whole String like:
carID.text = car.id.toString()
but I want add only number to this ID:

You can convert a char to a string:
val myChar = '1'
val myString = Character.toString(myChar )
Now, you can concat the new string to your other string:
val myIdString = "Id: $myString"
This is of course just the mechanics, you will need to adapt the code as you need and of course there are short-cuts if you want: this was purely for demonstration.

Change your string resource like this:
<string name="carID">Id: %1$s</string>
and you use it:
carID.text = String.format(getString(R.string.carID), "1")
the text will be: Id: 1

Related

Can't get rupee symbol to show correctly from strings.xml

So this works fine:
strFoo = "\u20B9" + strBar
But this doesn't
strFoo = R.string.rupee_symbol.toString() + strBar //.toString() is required
//R.string.rupee_symbol.toString() evaluates to some random number 2131755148... which I believe is a character array...
strings.xml
<string name="rupee_symbol">\u20B9 </string>
I can't figure out why it would behave like that, it looks like the same thing...!
You should not concatenate strings with string resources instead, you can use place holder:
<string name="rupee_symbol">\u20B9%s</string>
And use:
strFoo = resources.getString(R.string.rupee_symbol, strBar)
use getString(R.string.rupee_symbol) instead R.string.rupee_symbol.toString()
For example-
String strBar = String.valueOf(100);
String strFoo = getString(R.string.rupee_symbol)+strBar;
textView.setText( strFoo);

How to use decimal numer (Double data type) as placeholder in String resource

I want to use a more than 1 data type inside a placeholder within a String resource but whenever I try to use a demical number as a numerical value, an error is returned.
Kotlin
val currentLocale = Locale.getDefault()
val distanceWalked = 5.2
val numberFormatter: NumberFormat
val amountOut: String
numberFormatter = NumberFormat.getNumberInstance(currentLocale)
amountOut = numberFormatter.format(distanceWalked)
tv.txt = getString(R.string.distance_decimalnumber_placeholder,amountOut,"*")
Stirng resouce
<string name="distance_decimalnumber_placeholder">You have walked %1$d%2$s metres</string>
Expected result
You have walked 5.2* metres
Error
java.util.IllegalFormatConversionException: d != java.lang.Double
Wrong argument type for formatting argument '#1' in distance_decimalnumber_placeholder: conversion is 'd', received String (argument #2 in method call)
First mistake d is for ints
The problem:
You aready converted to string at: amountOut = numberFormatter.format(distanceWalked) you need to replace with string now
Solution: You don`t need to use $f you need to use $s
tv.txt = getString(R.string.distance_decimalnumber_placeholder,amountOut /* this is a string also*/ ,"*")
<string name="distance_decimalnumber_placeholder">You have walked %1$s%2$s metres</string>
I would like to mention two things :
Don't use d for double ... d is treated as int so use f instead of d. So don't use this
<string name="distance_decimalnumber_placeholder">You have walked %1$d%2$s metres</string>
And You don't need a chartype specifier to display * use * after the f like this
<string name="distance_decimalnumber_placeholder">You have walked %1$f* metres</string>
Notice that I have added only one place holder.

How to handle special character in Kotlin Android

I have a String which I am getting from API (no control over it). When the String contains a special character like an apostrophe, it will be converted to something else.
It looks something like this:
text_view.text = "Hannah's Law"
When displayed on Android, it will be:
Hannah's Law
I tried to convert the String to byteArray and then encode to UTF-8 but no luck:
val byteArray = template.execute(bindingDictionary).toByteArray() // This is the Actual String
String(byteArray,Charsets.UTF_8) // Did not work
'
is HTML for the apostrophe. You can use fromHtml to convert that to text with the apostrophe.
val fromApi = "Hannah's Law"
val textFromHtmlFromApi = HtmlCompat.fromHtml(fromApi, HtmlCompat.FROM_HTML_MODE_LEGACY)
text_view.text = textFromHtmlFromApi
use unicode symbols like here https://www.rapidtables.com/code/text/unicode-characters.html
for example instead
String str = "Hannah's Law"
use
String str = "Hannah\u0027s Law"
same thing if you need for example space in the end of string
String str = "string with space in the end\u0020"
for Kotlin use
var str: String = "string with space in the end\u0020"

How to append 2 strings in Kotlin?

I am trying to concatenate 2 String but not sure how to go about it.
this is my code:
val word = R.string.word
and i'm trying to append it with "$currentPage/5" inside the setText("$currentPage/5")
i tried to make it in this way setText("$word $currentPage/5")
and this way setText("${R.string.value} $currentPage/5")
and it did not work , it only shows me numbers not the text
try to use this:
val word = getString(R.string.word)
text_view.text = "$word $currentPage/5"
If you want to edit your value (e.g. current page) wrap it with {}
E.g.
val word = getString(R.string.word)
text_view.text = "$word ${currentPage/5}"
Remember to use proper kotlin syntax
In Kotlin, the concatenation of string can be done by **interpolation/templates**.
val a = "Its"
val b = "Kotlin!"
val c = "$a $b"
The output will be Its Kotlin!
Or we can alson do concatenate using the **+ / plus() operator**:
val a = "String"
val b = "Concatenate"
val c = a + b
val d =a.plus(b)
print(c)
The output will be: StringConcatenate
print(d)
The output will be: StringConcatenate
Or you can concatenate using the StringBuilder which is a normal way to do that.
To concatenate two string, we could do
val concatenatedWord = "${resources.getString(R.string.value)}:
${number/3}."
If R.string.value was "The result" and number was 15, value of concatenatedWord will be "The result: 5."
Or we could also concatenate using the + operator or using StringBuilder.
But if you do
textView.text = "${resources.getString(R.string.value)}: ${number/3}."
AS will warn "Do not concatenate text displayed with setText." so, in the case of setting concatenated text in textview, consider using
String.format("%s: %d.", resources.getString(R.string.value):
number/3)
As a future resource and answer why the accepted answer works:-
String Templates:-
Strings may contain template expressions, i.e. pieces of code that are evaluated and whose results are concatenated into the string.
How to implement these?
A template expression should start with a dollar sign ($) and consists of either a simple name:
when the expression is a simple variable.
val i = 10
println("i = $i") // prints "i = 10"
or else arbitrary expression in curly braces:
val s = "abc"
println("$s.length is ${s.length}") // prints "abc.length is 3"
Note :- Templates are supported both inside raw strings and inside escaped strings.
val nameOfAnimal = "fish"
val speciesClass = "is an Aquatic Vertebrate"
println(nameOfAnimal.plus(speciesClass))
println(nameOfAnimal+speciesClass)
println("$nameOfAnimal $speciesClass")
Results:
fishis an Aquatic Vertebrate
fishis an Aquatic Vertebrate
fish is an Aquatic Vertebrate

How to pass Data to the getText?

I have the following String ressource:
<string name="foo">This is a {0} test. Hello {1}</string>
Now I want to pass the values 1 and foo when calling:
getResources().getText(R.string.foo)
how to make this? Or is it not possible?
getResources().getString(R.string.foo, 1, "foo"); but string should be using string format ... so your string in string should looks like:
<string name="foo">This is a %d test. Hello %s</string>
I'm not too sure if Java has something like this inbuilt. I did once write a method that would do the exact thing you're looking for, however:
public static String format(String str, Object... objects)
{
String tag = "";
for (int i = 0; i < objects.length; i++)
{
tag = "\\{" + i + "\\}";
str = str.replaceFirst(tag, objects[i].toString());
}
return str;
}
And this would format the string, to replace the '{i}' with the objects passed; just like in C#.
example:
format(getResources().getString(R.string.foo), "cool", "world!");
You can do it this way :
string name="foo">This is a %d test. Hello %s string>
with
getString(R.string.foo, 1, "foo");
Source : Are parameters in strings.xml possible?
You can find more information on formatting and formats here : http://developer.android.com/reference/java/util/Formatter.html
I believe that the simplest way to do what you're wanting is to save the line of code you have to a variable then use the Java String replace() function.
String fooText = getResources().getText(R.string.foo);
fooText = fooText.replace("{0}", myZeroVar);
fooText = fooText.replace("{1}", myOneVar);

Categories

Resources