First, I want to say I am completely new at programming and Kotlin, I'm trying it for just 3 days now, and have no experience at all, just reading a bit about it.
I have an android device with a barcode scanner. I have made an activity with 2 edittext fields and a button. In the first edittextfield (etbc), I scan the barcode with the device, so there comes a 13 digit number in it. Next to this field I have another field, etqty, where I enter the quantity.
I'm trying to get the program to automatically set the focus to etqty, when the 13 digit number is entered in the first field.
I already tried with length, but I don't really get any result. How can I accomplish this, or do I have to use another method?
This is the code I have for now (keep in mind I'm absolutely new to this, so my code can be a bit weird and messy, but for now it does what I want it to do :-))
package com.example.project016
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import java.io.BufferedReader
import java.io.IOException
import java.io .InputStreamReader
import android.widget.Toast
import android.app.Activity
import java.io.OutputStreamWriter
import java.nio.file.StandardOpenOption
class MainActivity: AppCompatActivity () {
override fun onCreate (savedInstanceState: Bundle?) {
super.onCreate (savedInstanceState)
setContentView (R.layout.activity_main)
val etbc = findViewById (R.id.etbc) as EditText
val et1 = findViewById (R.id.et1) as EditText
val etqty = findViewById (R.id.etqty) as EditText
etbc.requestFocus()
if(fileList().contains("notes.txt")) {
try {
val file = InputStreamReader(openFileInput("notes.txt"))
val br = BufferedReader(file)
var line = br.readLine()
val all = StringBuilder()
while (line != null) {
all.append(line + "\n")
line = br.readLine()
}
br.close()
file.close()
et1.setText(all)
}
catch (e:IOException) {
}
}
val button1 = findViewById (R.id.button1) as Button
button1.setOnClickListener {
try {
val file = OutputStreamWriter(openFileOutput("notes.txt", Activity.MODE_APPEND))
file.write (etbc.text.toString() + ";" + etqty.text.toString() + "\n")
file.flush ()
file.close ()
} catch (e : IOException) {
}
Toast.makeText(this, "data were recorded", Toast.LENGTH_SHORT).show()
// finish ()
etbc.getText().clear()
etqty.getText().clear()
}
}
What you could do is to watch the text which is entered in the first field.
You could use TextWatcher for example:
etbc.addTextChangedListener(object : TextWatcher {
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun afterTextChanged(s: Editable) {
if(etbc.text.length > 12) {
etqty.requestFocus()
}
}
})
Give it a try.
Btw. you could also set android:maxLength="13" in the xml
Related
I try to learning kotlin.
I want a make a android app.
But im getting error.
i want to if i write "A" to edittext(#+id/tehlikesinifi), textview (uzmanucret) give me "40"
i write "B" to edittext(#+id/tehlikesinifi), textview (uzmanucret) give me "20"
i write "C" to edittext(#+id/tehlikesinifi), textview (uzmanucret)give me "10"
import abdullah.aydin.aykanosgb.databinding.ActivityFiyat2Binding
import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class fiyat2 : AppCompatActivity() {
private lateinit var binding: ActivityFiyat2Binding
#SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding=ActivityFiyat2Binding.inflate(layoutInflater)
setContentView(binding.root)
var cs= binding.calisansayisi.text.toString()
var usaat=binding.usaatucret.text.toString()
var ts=binding.tehlikesinifi.text.toString()
var uzmanucret =binding.uzmanucret.text.toString()
binding.button.setOnClickListener {
if (ts.equals( "A")){
var uzmandk =40
}else if(ts.equals("B")){
var uzmandk =20
}else if(ts.equals("C")){
var uzmandk =10
}
var uzmandk: String=""
var sonuc: String
sonuc= uzmandk
var sonuc1 = sonuc
binding.uzmanucret.text= "$sonuc"
}
}
}
You have many redundant variables which make your code messy
ts is set only once in onCreate and never get updated. To get the latest value you typed in the EditText, you should get it within the onClickListener
Kotlin control flow expression can return a value. It is more suitable to use when in your case
You don't need to call equals to compare string in Kotlin.
binding.button.setOnClickListener {
binding.uzmanucret.text = when(binding.tehlikesinifi.text.toString()){
"A" -> "40"
"B" -> "20"
"C" -> "10"
else -> null
}
}
package com.example.firstapp
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.EditText
import kotlinx.android.synthetic.main.activity_main.*
import kotlin.random.Random
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val deEditText = findViewById<EditText>(R.id.de) as EditText
val ateEditText = findViewById<EditText>(R.id.ate) as EditText
Randomize.setOnClickListener{
val de = Integer.parseInt(deEditText.text.toString())
val ate = Integer.parseInt(ateEditText.text.toString())
RandomDisplay.text = (Random.nextInt(de - ate) + ate).toString()
}
}
}
I'm trying to create an app that gets two values and picks a random integer between them. I don't know what I'm doing wrong, and I really hope someone can help me. Thanks in advance.
val deEditText = findViewById<EditText>(R.id.de) as EditText
val ateEditText = findViewById<EditText>(R.id.ate) as EditText
Random.nextInt(de - ate)
if value from deEditText minus value from ateEditText is zero or negative, Radom.nextInt would throw IllegalArgumentException
// minimize the end bound to 1 by adding max()
RandomDisplay.text = (Random.nextInt(max(1, de - ate)) + ate).toString()
I'm trying to make a number look like this
932-874838/9
I did this with my EditText to append the - and / after some spaces
editText.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(text: Editable?) {
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
onValueChange(s.toString())
}
})
}
private fun onValueChange(value: String) {
mNumberTxtView.text = value
if (value.length == 3) {
mNumberTxtView.append("-")
}
if (value.length == 10) {
mNumberTxtView.append("/")
}
}
When I'm typing like
932
it automatically appends the - , and that works, but after it appends the - and if I type another number it replaces the - with that number instead of continuing, so it becomes 932- at first but when trying to put another number,
9328
it gets replaced like that removing the appended -
I think the problem is inside the onValueChange() method
onValueChange should be like this:
var test: StringBuilder = StringBuilder()
var lastValue: String = ""
fun onValueChange(value: String) {
if(lastValue.length > value.length) {
test.deleteCharAt(test.lastIndex)
if(test.length == 3 || test.length == 10) {
test.deleteCharAt(test.lastIndex)
}
} else {
test.append(value.last())
if (test.length == 3) {
test.append("-")
} else if (test.length == 10) {
test.append("/")
}
}
lastValue = value
textView.text = test
}
Try this, instead.
private fun onValueChange(value: String) {
if (value.length == 3) {
mNumberTxtView.text = "${value}_"
} else if (value.length == 10) {
mNumberTxtView.text = "${value}/"
}
}
Let me know if this works.
(The curly brackets around "value" in the strings may not be necessary. I'm still getting used to Kotlin's way of handling string concatenation.)
Edited to remove redundant and potentially loop-causing part.
You should not change text in beforeTextChanged and afterTextChanged to prevent re-call of those methods by TextWatcher. Make changes in afterTextChanged.
But be careful not to get yourself into an infinite loop, because any changes you make will cause this method to be called again recursively.
So set invoke of onValueChanged into afterTextChanged method
with removal of mNumberTxtView.text = value
if staemnt never happening true. so please help me. i tried changing some stuff and hope it will work but it never did and only else staement is working.
package com.example.managemntsystem
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var input = editText.text
var empList = arrayListOf<String>("jacob", "raf", "boss", "john")
button.setOnClickListener {
if (input == emplist) {
textView2.setText("WORKING")
}else{
textView2.setText("Not working")
}
}
}
}
use this instead:
if (empList.contains(input.toString()))
This will check if the content of the EditText is equal to any of the list items. Remember to call toString() method when you want the EditText content.
You can also use the in operator:
if (input in empList)
if(empList.contains(input))
I think this will resolve your issue
The reason is your var input = editText.text never gets set again (even though it is a var), so in this case, It's not different from a val. You either need to reassign it or use .text directly:
Set it again:
var input = editText.text
var empList = arrayListOf("jacob", "raf", "boss", "john")
button.setOnClickListener {
input = editText.text // add this line
f (input == emplist) {
textView2.setText("WORKING")
}else{
textView2.setText("Not working")
}
}
Or not use input at all and use text itself:
button.setOnClickListener {
if (editText.text == emplist) {
textView2.setText("WORKING")
}else{
textView2.setText("Not working")
}
}
This my first kotlin/java code. I want learn from this.
When I push "OK" button of Android keyboard, I want my app do same thing as when I push my button with android:onClick="onAnswerClick"
I know my code is not very good. You can't help me to know how to optimize it
I don't know if its a good idea to learn to code on android with kotlin.
import android.annotation.SuppressLint
import android.app.Activity
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.*
import android.widget.AdapterView
import android.widget.Toast
import android.widget.Spinner
import kotlinx.android.synthetic.main.activity_main.*
import android.widget.EditText
class MainActivity : Activity() {
class Calculateurs{
fun aire(r: Double): Double{
return 3.141592 * r * r
}
fun circonference(r: Double): Double{
return 2.0 * 3.141592 * r
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val spinner = findViewById<Spinner>(R.id.spinner) as Spinner
// Create an ArrayAdapter using the string array and a default spinner layout
val adapter = ArrayAdapter.createFromResource(this,
R.array.mesure_array, android.R.layout.simple_spinner_item)
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
// Apply the adapter to the spinner
spinner.adapter = adapter
}
#SuppressLint("SetTextI18n")
fun onAnswerClick(view: View) {
val answer = (findViewById<EditText>(R.id.editText2) as EditText).text.toString()
val spinner = findViewById<View>(R.id.spinner) as Spinner
var rayon = java.lang.Double.parseDouble(answer)
if (spinner.getSelectedItem() == "Diamètre"){
rayon = rayon *2
}
if (rayon < 0) {
val toasty = Toast.makeText(applicationContext, "Ce nombre est négatif !", Toast.LENGTH_SHORT)
toasty.show()
} else if (rayon > 0) {
val c = Calculateurs()
val tc = findViewById<TextView>(R.id.cire) as TextView
tc.text = "" + c.circonference(rayon)
val ta = findViewById<TextView>(R.id.aire) as TextView
ta.text = "" + c.aire(rayon)
} else {
val toasty = Toast.makeText(applicationContext, "Ce nombre est nul !", Toast.LENGTH_SHORT)
toasty.show()
}
}
}
I think your question is how do you get your app to respond to the enter or done key when you press it in an EditText.
Since you did not show your layout, I will make a few assumptions.
Lets say you have and EditText that has the following attributes (plus others)
<EditText
android:id="#+id/field"
android:imeOptions="actionDone"
android:inputType="text"
...
app:layout_constraintTop_toTopOf="parent" />
Here is an example activity that will respond to hitting the enter key.
class MainActivity : AppCompatActivity() {
lateinit var field: EditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
field = findViewById(R.id.field) as EditText
}
override fun onResume() {
super.onResume()
field.setOnEditorActionListener( { textView, action, event ->
var handled = false
if (action == EditorInfo.IME_ACTION_DONE) {
println("call your method here")
handled = true
}
handled
})
}
You can call your onAnswerClick() in the location of the println("call your method here") statement, passing in textView if you like.
This example makes use of Kotlin's SAM Conversion which is covered in this section of the Kotlin documentation, specifically it uses the SAM conversion to create a TextView.OnEditorActionListener from a lambda expression
As Kamil Kulig, points out, there is definitely more samples and examples using Java than Kotlin, but I don't think you have to start with Java. You will need to learn enough Java to be able to understand what's going on in examples and documentation however.