I just started learning kotlin, and in my app I want to take value placed by user from EditText to my MainActivity and work on it (for example add 1.5 to that value and show that value on the screen), but I have no idea how to do it, the code I wrote so far:
val btnClick= findViewById<Button>(R.id.btn)
val tekstNaButtonie = findViewById<TextView>(R.id.siema)
val mEdit = findViewById<EditText>(R.id.editTextTextPersonName)
val strrr = mEdit.getText()
val strrrr = strrr.toString()
val liczba = strrrr.toFloat()
val liczbaa = liczba + 1.5f
btnClick.setOnClickListener {
tekstNaButtonie.text = liczbaa.toString()
Toast.makeText(this#MainActivity,"Kliknales mnie!",Toast.LENGTH_LONG).show()
}
My Xml:
android:id="#+id/editTextTextPersonName"
android:layout_width="100sp"
android:layout_height="48sp"
android:layout_marginStart="16sp"
android:layout_marginTop="12sp"
android:ems="10"
android:hint="0"
android:importantForAutofill="no"
android:inputType="numberDecimal"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
with this code app don't want to start:
enter image description here
I think it would be easiest to do this using toFloatOrNull(). It will return null instead of throwing an exception if the text is not a number. Then you can skip doing the calculation if the number is null. Optionally you can show a message to the user.
Also, you need to be checking these values inside your button, or the button will only see what the original value was.
val btnClick= findViewById<Button>(R.id.btn)
val tekstNaButtonie = findViewById<TextView>(R.id.siema)
val mEdit = findViewById<EditText>(R.id.editTextTextPersonName)
btnClick.setOnClickListener {
val liczba = mEdit.getText().toString().toFloatOrNull()
if (liczba != null) {
val liczbaa = liczba + 1.5f
tekstNaButtonie.text = liczbaa.toString()
Toast.makeText(this#MainActivity,"Kliknales mnie!",Toast.LENGTH_LONG).show()
} else {
//Maybe show user an error message
}
}
Or if you want to treat invalid input as 0, you can use ?: the elvis operator to provide a default of 0:
val btnClick= findViewById<Button>(R.id.btn)
val tekstNaButtonie = findViewById<TextView>(R.id.siema)
val mEdit = findViewById<EditText>(R.id.editTextTextPersonName)
btnClick.setOnClickListener {
val liczba = mEdit.getText().toString().toFloatOrNull() ?: 0f
val liczbaa = liczba + 1.5f
tekstNaButtonie.text = liczbaa.toString()
Toast.makeText(this#MainActivity,"Kliknales mnie!",Toast.LENGTH_LONG).show()
}
Related
Context:
I click on a button -> a WindowDialogue appears -> there are 2 LineEdit Nodes and a button
Supposed procedure:
I fill these LineEdits, press the button, and the function tied to the button receives the texts from the LineEdits (and creates a dictionary key-value pair).
Problem:
The texts from the LineEdits do not pass down to the function (through connect()).
I tried passing the text directly with LineEdit.text. I tried writing it in a different variable and passing the variable. The debug shows the function is getting executed (no problem with that), but the strings passed from the LineEdits are always empty. Somehow, it worked for some time when I explicitly pressed ENTER after filling the LineEdits. But after I tried to fix the aforementioned problem, it stopped working altogether.
P.S. Everything I mentioned is created dynamically through the code, if that matters.
Code:
#Declaring the variables
var temp_text_key = ""
var temp_text_value = ""
#Function to show up a dialogue window with LineEdits and Confirm button
func _on_add_new_property(dict: Dictionary):
temporal_window_dialogue = WindowDialog.new()
temporal_window_dialogue.rect_min_size = Vector2(410,90)
temporal_window_dialogue.resizable = true
temporal_window_dialogue.popup_exclusive = true
temporal_window_dialogue.window_title = "Adding new property to %s" % get_dict_name_by_id(professions, dict["id"])
var le_key = LineEdit.new()
le_key.placeholder_text = "Name of the property"
le_key.hint_tooltip = "Name of the property"
le_key.connect("text_changed", self, "_on_add_new_prop_text_entered", ["key"])
var le_value = LineEdit.new()
le_value.expand_to_text_length = true
le_value.placeholder_text = "Value of the property"
le_value.set("custom_constants/minimum_spaces", 36)
le_value.hint_tooltip = "Value of the property"
le_value.connect("text_changed", self, "_on_add_new_prop_text_entered", ["value"])
var lab = Label.new()
lab.text = "Should the Value become a Dictionary?"
var check_bt = CheckBox.new()
var vbox = VBoxContainer.new()
var grid_container = GridContainer.new()
grid_container.columns = 2
var accept_bt = Button.new()
accept_bt.text = "Confirm"
temporal_window_dialogue.add_child(vbox)
vbox.add_child(grid_container)
grid_container.add_child(le_key)
grid_container.add_child(le_value)
grid_container.add_child(lab)
grid_container.add_child(check_bt)
vbox.add_child(accept_bt)
grid_container.set("custom_constants/vseparation", 5)
grid_container.set("custom_constants/hseparation", 5)
check_bt.connect("pressed", self, "_on_check_dict_pressed")
popup_window.add_child(temporal_window_dialogue)
temporal_window_dialogue.connect("popup_hide", self, "_on_close_specific_codegenerated_popup", [temporal_window_dialogue])
temporal_window_dialogue.popup_centered()
accept_bt.connect("pressed", self, "_on_add_new_property_confirmation", [dict, temp_text_key, temp_text_value])
#Function to create a new key/value pair in a dictionary
func _on_add_new_property_confirmation(dict: Dictionary, prop_name: String, prop_value: String):
if prop_name == "" or prop_value == "":
send_message_to_console("Neither of the two can be empty", 3)
return
if add_dictionary_flag:
dict[prop_name] = {
prop_value: {
"id": get_free_local_id_for_dict(dict)
}
}
elif !add_dictionary_flag:
if keywords_for_dictionaries.has(prop_name):
send_message_to_console("Only Dictionary items can become %s" % prop_name)
dict[prop_name] = prop_value
temp_text_key = ""
temp_text_value = ""
#Optional function to write the text from LineEdits to the variables
func _on_add_new_prop_text_entered(new_text, key_or_value):
if key_or_value == "key":
temp_text_key = new_text
elif key_or_value == "value":
temp_text_value = new_text
You mentioned using 'LineEdit.text', but have you tried the following?
var text = LineEdit.get_text()
If this doesn't help, please update your original post to include code examples.
I am new to SoapUi. I am exploring on how multiple request in soapUi is done using groovy script.
below is the example that im trying to do, based on example that i found through "googling"
import com.eviware.soapui.SoapUI;
import com.eviware.soapui.model.testsuite.*;
import com.eviware.soapui.impl.wsdl.testcase.WsdlTestCaseRunner
import java.util.Random
import com.eviware.soapui.model.testsuite.TestRunner.Status
// Define your testCase pointer
//def testcase = testRunner.testCase.testSuite.project.testSuites["TestSuite - User Management REST API"].getTestCaseByName ("Authenticate User")
def counterUser = testRunner.testCase.testSuite.getPropertyValue( "counter" )
int value = counterUser.toInteger()
String tester = ""
30.times {
value = value + 1
tester = "tester " + value.toString()
testRunner.testCase.testSuite.setPropertyValue( "userName", tester )
testRunner.runTestStepByName("POST - createUser - Create a User")
}
testRunner.testCase.testSuite.setPropertyValue( "counter", value.toString() )
I want to create a 30 users which start from Tester1...tester2.....tester30.
Is it possible to do this way? I keep getting an error such as NullPointerException at this line
int value = counterUser.toInteger()
I got what you say.
That is because, initially there is no value for counter which results to null and you are applying toInteger() over it.
Just change:
From:
int value = counterUser.toInteger()
To:
int value = counterUser?.toInteger() ?: 0
How it would be possible to generate Excell reports from Play Framework v2.x(Scala). I found there's a Play-Excel module but it supports PlayFramework v1.0. Is there anything suitable for v2.x?
In the end I choose to use Spoiwo. Scala Wrapper for Apache POI. It has a neat starting guide. However, doesn't have an example with PlayFramework.
Here's my quick and dirty hack to generate simple report from case class.
def generateReportXLSX(waybillId: Long) = Action{ implicit request =>
val headerStyle =
CellStyle(fillPattern = CellFill.Solid, fillForegroundColor = Color.DarkGrey, fillBackgroundColor = Color.AquaMarine, font = Font(bold = true))
val listItems: List[Item] = Items.findByWaybillId(waybillId)
val listRows = listItems.map{ item =>
Row().withCellValues(item.id.getOrElse(1), item.itemCode, item.senderName.getOrElse(""))
}
val gettingStartedSheet = Sheet(name = "Накладная ")
.withRows(listRows)
.withColumns(
Column(index = 0, style = CellStyle(font = Font(bold = true)), autoSized = true)
)
gettingStartedSheet.saveAsXlsx("/home/user/dumps/"+waybillId+".xlsx")
Ok.sendFile(new File(("/home/user/dumps/"+waybillId+".xlsx")))
}
In the code below I'm trying to update one of the tag value. My problem is that which tag value I need to update, I know only at run time.
Below code does not work to update the tag value even though I'm able to get the tag value by this code.
def temp1="""
<TradeRecord>
<TradeId>1000</TradeId>
<SecurityId>10382456</SecurityId>
<TradeType>SELLL</TradeType>
<TradeDate>2014-03-21</TradeDate>
<Broker>100</Broker>
<Exchange>1</Exchange>
<Status>INIT</Status>
<Quantity>12765</Quantity>
<ApprovedBy />
</TradeRecord>
"""
def records = new XmlParser().parseText(temp1)
childRecords = records.children()
j = childRecords.size()
def tagname = 'Quantity'
for (int i=0; i<j; i++){
if (childRecords[i].name() == tagname) {
log.info childRecords[i].text()
childRecords[i].text() = "9999"
log.info childRecords[i].text()
}
}
You can not assign to the text()-getter, but there is the value, which has a setter; e.g.:
childRecords[i].value = "9999"
But this also can be done more groovy:
def temp1="""
<TradeRecord>
<TradeId>1000</TradeId>
<SecurityId>10382456</SecurityId>
<TradeType>SELLL</TradeType>
<TradeDate>2014-03-21</TradeDate>
<Broker>100</Broker>
<Exchange>1</Exchange>
<Status>INIT</Status>
<Quantity>12765</Quantity>
<ApprovedBy />
</TradeRecord>
"""
def records = new XmlParser().parseText(temp1)
final tagname = 'Quantity'
records."$tagname".each{
it.value = '9999'
}
println groovy.xml.XmlUtil.serialize(records)
This is the related code fragment where I can't print out the values from valuebox. May I know what's the problem?
public GuaranteedDefsAnalysis(UnitGraph graph)
{
super(graph);
DominatorsFinder df = new MHGDominatorsFinder(graph);
unitToGenerateSet = new HashMap<Unit, FlowSet>(graph.size() * 2 + 1, 0.7f);
// pre-compute generate sets
for(Iterator unitIt = graph.iterator(); unitIt.hasNext();){
Unit s = (Unit) unitIt.next();
FlowSet genSet = emptySet.clone();
for(Iterator domsIt = df.getDominators(s).iterator(); domsIt.hasNext();){
Unit dom = (Unit) domsIt.next();
for(Iterator boxIt = dom.getDefBoxes().iterator(); boxIt.hasNext();){
ValueBox box = (ValueBox) boxIt.next();
box.getValue().toString(); // simply using toString does not work
if(box.getValue() instanceof Local)
genSet.add(box.getValue(), genSet);
}
}
unitToGenerateSet.put(s, genSet);
}
doAnalysis();
}
Can you maybe rephrase your question? What do you mean by "does not work"? Did you forget to add the println statement maybe?