fun SubmitOrder(view: View) {
/* pricing of coffee */
val total = quantity * 5
val s: String = ("$$total.00")
money.text = ("Total : $s\nThank You!").toString()
//This is calling On click listener
Toast.makeText(this, "order_Submitted", Toast.LENGTH_SHORT).show()
}
In this code, I need a new line before Thank You! in money.text but I am not getting any new line I am new in android development so, am not able to point out the mistake.
Let's go thru your code line by line:
val s: String = ("$$total.00")
s is a bad variable name, as it's not descriptive at all
you don't need the (braces)
the :String here is optional. In such an obvious case i would emit it.
A $ is a sign to the kotlin compiler to include the following variable. Therefore, you can't use the $ when you mean "US-Dollar". See this post on how to escape it
While ".00" works, it's no good style. I suggest you use string formatting as described here.
can be written as val s = "\$ ${String.format("%.2f", total)}"
you should wherever possible use string resources, but thats out of the scope of this answer
money.text = ("Total : $s\nThank You!").toString()
this is correct, but unnecessary verbose:
"Total : $s\nThank You!" is already a string, so there's no need to .toString()
braces are not needed
can be written as money.text = "Total : $s\nThank You!"
Related
On creating a timer In Android Studio Kotlin.
I'd like to display the time value as it's 2 digit number like '01:04:07'.
Please see the below.
At this point, how do I change the code?
Simply use String.format() like:
timerDisplay.text = String.format("%02d:%02d:%02d", lapsHours, lapsMinutes, lapsSeconds)
You can use DecimalFormat as below:
val f: NumberFormat = DecimalFormat("00")
timerDisplay.text = "${f.format(lapshours)}:${f.format(lapsMin)}:${f.format(lapsSec)}"
You can use your extension function on Int like
fun Int.format(): String{
return if(this<10 && this>=0) "0"+this.toString() else this.toString()
}
simple call format() function on your Int variable to get your required format.
timerDisplay.text = "${lapsHours.format()} : ${lapsMinutes.format()} : ${lapsSeconds.format()}"
I am new to android studio and kotlin. I need to find a way to check if a string contains a char, which is, in this case, "/"
I want to form a piece of code in the following manner:
if (string input contains a character "/") = true {
<code>
}
else{
<code>
}
Please tell me how to do this, and if possible, give me the code I'll need to specify as the condition.
You can use contains, like this:
val a = "hello/"
val b = a.contains("/")
When the string has the character will return true.
I have a NSFW class that scans texts like item names and descriptions against a list of known NSFW-words.
That would be the best approach to test a list of strings like
let nsfw = listof(
"badword",
"curseword",
"ass",
... 200+ more
)
against a string like:
This is the text that contains a badword // returns true
Please note that i need to check for full words. not parts of words.
so the sentence:
The grass is grean // returns false
Because grass is not a bad word.
Ive tried something like this but it doesnt check for full words.
val result = nsfw.filter { it in sentence.toLowerCase() }
You may build a regex like
\b(?:word1|word2|word3...)\b
See the regex demo. Then, use it with the Regex.containsMatchIn method:
val nsfw = listOf(
"badword",
"curseword",
"ass"
)
val s1 = "This is the text that contains a badword"
val s2 = "The grass is grean"
val rx = Regex("\\b(?:${nsfw.joinToString(separator="|")})\\b")
println(rx.containsMatchIn(s1)) // => true
println(rx.containsMatchIn(s2)) // => false
See this Kotlin demo.
Here, nsfw.joinToString(separator="|") joins the words with a pipe (the alternation operator) and the "\\b(?:${nsfw.joinToString(separator="|")})\\b" creates the correct regex.
If your words may contain special regex metacharacters, like +, ?, (, ), etc., you need to "preprocess" the nsfw values with the Regex.escape method:
val rx = Regex("\\b(?:${nsfw.map{Regex.escape(it)}.joinToString("|")})\\b")
^^^^^^^^^^^^^^^^^^^^^^
See the Kotlin demo.
AND one more thing: if the keywords may start/end with chars other than letters, digits and underscores, you cannot rely on \b word boundaries. You may
Use whitespace boundaries: val rx = Regex("(?<!\\S)(?:${nsfw.map{Regex.escape(it)}.joinToString("|")})(?!\\S)")
Use unambiguous word boundaries: val rx = Regex("(?<!\\w)(?:${nsfw.map{Regex.escape(it)}.joinToString("|")})(?!\\w)")
You can use split() on the string that you want to check, with space as a delimiter, so you create a list of its words, although this does not always guarantee that all words will be extracted successfully, since there could exist other word separators like dots or commas etc. If that suits you, do this:
val nsfw = listOf(
"badword",
"curseword",
"ass"
)
val str = "This is the text that contains a badword"
val words = str.toLowerCase().split("\\s+".toRegex())
val containsBadWords = words.firstOrNull { it in nsfw } != null
println(containsBadWords)
will print
true
If you want a list of the "bad words":
val badWords = words.filter { it in nsfw }
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
The following code convert a list to a string and display to Logcat, but all records are displayed in one line. I hope to display top 10 records per line in Logcat in Android Studio 3.0, how can I do ?
Note: Log.e("My", logList.joinToString("<Br/>", limit =10, truncated = "...more...")) doesn't work
val logList=LogHandler().getListAllLog()
Log.e("My", logList.joinToString("|", limit =10, truncated = "...more..."))
val strings = ArrayList<String>()
strings.add("This is line1")
strings.add("This is line2")
strings.add("This is line3")
display(strings)
You should iterator list. Try this:
fun display(strings: List<String>) {
for (str in strings) {
Log.e("YourTag", str)
}
}
you can chop up your List using chunked() method.
e.g. if you want to log 10 records per line, then just call chunked(10).
//assuming logList is an array of String.
//you can use logList.chunked directly if it is a List.
val batchSize = 10 //chop up to 10 per batch
logList.asList().chunked(batchSize)
.forEach{subList -> Log.d("My", subList.joinToString("|" )) }
You can simply use "\n" for new line,in logs.
For example:
Log.e(TAG,"Hello \n World");
which will give output as
Hello
World
I hope this helps,thank you.
if its not your answer,please ignore this answer.