I have an android project that shows a summary of you car efficiency on which you enter your information and it shows in a listView your summary, but how do I get the user's input, so I can do the math, and show the sum on a different activity?
fun getTotalGallons() : Double {
// add all of the gallons together from the list
// return that total
return ....
}
val editText = EditText() //Here you can use instantiate it or use kotlin
//extensions to used it directly
val stringText = editText.text //do something
Related
I'm trying to create a line chart in Android using MPAndroidChart Library and as entries I have values like 1200.10, 1300.70 and so on, but on my chart the values are rounded (1200, 1301), and I want to display the original values. How can I do that? I tried different solutions but couldn't solve the problem yet. I'm using the Kotlin language. Thanks!
for (item in reversedCashList) {
if (i <= daysNmb) {
var cashValue: String = transformDataForChart(item.value!!)
dataValsEntries.add(Entry(i, cashValue.toFloat()))
i++
}
}
Also, I'm using this formatter Class to format my values because the initial format is like 120.200,10 and I changed them to 120200.10 but this values is displayed as 120200. My Formatter Class:
private fun transformDataForChart(totalValue: String): String {
return if (totalValue.contains(".")) {
val test = totalValue.replace(".", "")
test.replace(",", ".")
} else {
totalValue.replace(",", ".")
}
}
You can try with BigDecimal, something like BigDecimal.valueOf(X).setScale(decimalPlace(usually 2), BigDecimal.ROUND_HALF_UP).floatValue()
The idea is that float cannot hold so many values as the Double, I've encountered this issue as some point as well, and I had to change everything to Double just to make it more easier to maintain... Therefor I don't think is a straight-forward method to keep everything you need in the float format.
I am calculating priceAfterDsicount then place value in EditText(so user can modify it after App calculation)
Value retured from format is arabic numbers
this is code
private fun handleDiscount() {
val price = edPackagePrice.text.toString().toDoubleOrNull()
val discount = discount_percentage_edit_text.text.toString().toIntOrNull()
"handleDiscount before price$price discount$discount".log(mTag)
price?.let {
discount?.let {
val finalValue = String.format("%.1f", ValuesHelper.getPercentage(price, discount),Locale.US)
price_after_discount_edit_text.setText(finalValue)
"handleDiscount ook price$price discount$discount, final $finalValue".log(mTag)
}
}
if (discount == null) {
"handleDiscount $price , ${edPackagePrice.text}".log(mTag)
price_after_discount_edit_text.setText("")
price?.let { price_after_discount_edit_text.setText(price.toString()) }
}
"handleDiscount after price_after_discount_edit_text${price_after_discount_edit_text.text.toString()} ".log(mTag)
}
Output at Run
so what is problem?
NOTE
App language is arabic(user can change it from app).
I found other way to convert arabic number to english
Use Java.math.BigDecimal ,it will automatically construct English numeric equivalent to Arabic numeric equivalent , After you have English numeric equivalent do your calculation and when you want to update the UI after calculation use the device locale to show the end result to user in Arabic , BigDecimal only work with digits i.e. 0123. For special characters like , you have to do exception handling , we have .isDigit() method of Character class that you can leverage to iterate over whole input string and remove , before doing calculation,hope this helps.
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
I am creating an Android application created using Flash AS3. The user will input his/her name(instance namenameField), click the previous (btnPrev) and next (btnNext) button and press save (btnPrev). After restarting the application, the last frame saved was loaded (with the name). However if I want to input 2nd user with different name and save it in different frame, will the 2nd user's save progress be retained (without deleting the progress of the 1st user?). The problem, when I type the previous user name progress and press load (btnLoad), his saved progress doesn't load. Please help.
I am a newbie in programming. Here is my code so far:
*import flash.events.MouseEvent;
var savedstuff:SharedObject = SharedObject.getLocal("myStuff");
btnSave.addEventListener(MouseEvent.CLICK, SaveData);
btnLoad.addEventListener(MouseEvent.CLICK, LoadData);
btnNext.addEventListener(MouseEvent.CLICK, pageNext);
btnPrev.addEventListener(MouseEvent.CLICK, pagePrev);
function pageNext (e:MouseEvent){
nextFrame();
}
function pagePrev (e:MouseEvent){
prevFrame();
}
function SaveData(MouseEvent){
savedstuff.data.username = nameField.text
savedstuff.flush();
}
function LoadData(MouseEvent){
if(savedstuff.size>0){
nameField.text = savedstuff.data.username}
gotoAndStop(savedstuff.data.saveData);
}
if(savedstuff.size>0){
nameField.text = savedstuff.data.username}*
If I understood it correctly you want to save and load savedstuff for two different users, right ?
Since you always saving everything with the name "myStuff" data will be overwritten every time you save. If you want that per user you might want to add the username to the SharedObject name:
var savedstuff:SharedObject;
function SaveData(e:MouseEvent)
{
var userName:String = nameField.text;
savedstuff = SharedObject.getLocal(userName + "myStuff");
savedstuff.data.username = userName;
savedstuff.flush();
}
function LoadData(e:MouseEvent)
{
var userName:String = nameField.text;
savedstuff = SharedObject.getLocal(userName + "myStuff");
if(savedstuff.size > 0)
{
nameField.text = savedstuff.data.username}
gotoAndStop(savedstuff.data.saveData);
}
}