Can one reference id directly in kotlin?My small program can't seem to run - android-studio

Hi im new in android and i read that i can directly reference id from activity_main to mainAcctivity.kt without using findviewbyid.When i do that i get an error but my ids are correct:
This is the error Unresolved reference: button and Unresolved reference: textView
This is my code
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// get reference to button
//val btnClickMe = findViewById(R.id.button) as Button
//val myTextView = findViewById(R.id.textView) as TextView
var timesClicked = 0
// set on-click listener
button.setOnClickListener {
timesClicked += 1
textView.text = timesClicked.toString()
Toast.makeText(this#MainActivity, "Hello Don.", Toast.LENGTH_SHORT).show()
}
}
}```
Please help out,i tried to import android.widget.button and textView that option is not available but when i hardcode the text appears inactive.

You can make use of ViewBinding to reduce the use of findViewById. You can find an example here.
You can go through this blog to have more insight on how to use ViewBinding.
For the above code, you can resolve the issue using the code below:
val myTextView = findViewById<TextView>(R.id.textView)
val btnClickMe = findViewById<Button>(R.id.button)

Related

I'm trying to run video by making a video player app with simplified controls, and having issue with findViewById

The full error message I'm getting is this: Not enough information to infer type variable T
import android.net.Uri
import android.net.Uri.*
import android.os.Bundle
import android.widget.MediaController
import android.widget.VideoView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//Find the VideoView class by its id
val videoView = findViewById(R.id.testView)
//Creating MediaController
val mediaController = MediaController(this)
mediaController.setAnchorView(videoView)
//specify the location of media file
val uri:Uri = parse(
"android.resource://" + packageName
+ "/raw/test"
)
//Setting MediaController and URI, then starting the videoView
videoView.setMediaController(mediaController)
videoView.setVideoURI(uri)
videoView.requestFocus()
videoView.start()
}
}
Full error message i'm getting :
Not enough information to infer type variable T
Kotlin isn’t able to definitively determine what class the findViewById is trying to find, so you will need to define it yourself. Try updating your code to this, to specify that the item is a VideoView object:
val videoView = findViewById(R.id.testView) as VideoView

Android Studio Kotlin app "keeps stopping" when I run it

I am just trying to set up a spinner configured as a dropdown menu, but I can't even test my app to see if it works because every time I run it, it immediately crashes. I know that my issue is related to a null object reference at line 21 in my MainActivity.kt file. Here is the problem code:
val spinner: Spinner = findViewById<Spinner>(R.id.locations)
The id of the spinner is locations, so I'm not sure why this is coming back as a null value.
Here is also the full code for the file:
import android.app.Activity
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Spinner
import android.widget.ArrayAdapter
import android.widget.AdapterView
private var userLocation: Any = ""
private var userDestination: Any = ""
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
val spinner: Spinner = findViewById<Spinner>(R.id.locations)
val locationsAdapter: ArrayAdapter<CharSequence> = ArrayAdapter.createFromResource(
this,
R.array.rooms,
android.R.layout.simple_spinner_item
).also { adapter ->
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinner.adapter = adapter
}
}
class SpinnerActivity : Activity(), AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View?, pos: Int, id:Long) {
userLocation = parent.getItemAtPosition(pos)
val spinner: Spinner = findViewById(R.id.locations)
spinner.onItemSelectedListener = this
}
override fun onNothingSelected(parent: AdapterView<*>) = Unit
}
Declare spinner global for MainActivity:
private lateinit var spinner: Spinner
On the method onCreate initialise the spinner and set its adapter, I would recommend you to set the array adapter as follows:
spinner = findViewById<Spinner>(R.id.locations)
spinner.adapter = ArrayAdapter(this, R.layout.drop_down_generic_item, resources.getStringArray(R.array.rooms))
I don't really understand the SpinnerActivity you showed in the question, sorry. But in MainActivity you can set the spinner.onItemSelectedLister() as follows:
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(adapterView: AdapterView<*>?, view: View?, position: Int, p3: Long) {
val selectedRoom = adapterView?.getItemAtPosition(position)
}
override fun onNothingSelected(p0: AdapterView<*>?) {
}
}
I don't want to confuse you, but have a look at a TextInputLayout with an AutoCompleteTextView, just as a hint. :D

findViewById keeps giving me errors and a headache

Hello all,
I am new to Kotlin and was trying to keep recreating my code to get it easier for me to learn. i have created an dice app and it works. but everytime i create a new project and start. I always get the error on findViewById(R.id.) i make the layout first with all the ID`s assigned but no matter what i do i keep getting this error. I use Android Studio.
I hope someone can help me get this frustration out of my head.I want to know why it keeps getting that error. thanks in advance.
package com.example.dicedicebaby
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//button action`
val rollButton: Button = findViewById(R.id.button)
//action of the button when pressed.
rollButton.setOnClickListener{ stones()}
}
}
fun stones(){
//The normal dice
val fDice=Dice(6)
//D20
val dDice = Dice(20)
//action of dice roll
val dice = fDice.roll()
//D20 action
val secondDice = dDice.roll()
//view
val resultView: TextView = findViewById(R.id.dice)
resultView.text = dice.toString()
val secondView: TextView = findViewById(R.id.Ddice)
secondView.text = secondDice.toString()
}
//makes the dice a dice.
class Dice(private val numSides:Int){
fun roll():Int{
return (1..numSides).random()
}
}
The suggested approach is to migrate to view binding.
Plus, you should declare the stones() function inside the MainActivity class body:
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
//action of the button when pressed.
binding.rollButton.setOnClickListener{ stones() }
}
fun stones(){
//The normal dice
val fDice=Dice(6)
//D20
val dDice = Dice(20)
//action of dice roll
val dice = fDice.roll()
//D20 action
val secondDice = dDice.roll()
//view
binding.dice.text = dice.toString()
binding.Ddice.text = secondDice.toString()
}
}

Input Text in EditText and display it in a second screen

I'm trying to create two screen UI. The first screen has an editText and a Submit button. The second screen has a textView to display text that would be entered in the first screen.
Here is the code I used, but the second screen does not show inputted text from the first screen.
MainActivity.kt [First Screen]:
package com.rishis.testinginputtext
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.rishis.testinginputtext.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityMainBinding.inflate(layoutInflater)
binding.button.setOnClickListener{
val intent = Intent(this, SecondActivity::class.java)
startActivity(intent)
}
setContentView(binding.root)
}
}
SecondActivity.kt [Second Screen]:
package com.rishis.testinginputtext
import android.content.Context
import android.os.Bundle
import android.text.Editable
import android.util.AttributeSet
import android.view.View
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import com.rishis.testinginputtext.databinding.ActivityMainBinding
import com.rishis.testinginputtext.databinding.ActivitySecondBinding
class SecondActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivitySecondBinding.inflate(layoutInflater)
val oneBinding = ActivityMainBinding.inflate(layoutInflater)
//textView refers to textView in secondActivity
val textView = binding.textView
//editText refers to EditText in mainActivity
val editText = oneBinding.EditText
textView.setText(editText.text.toString())
setContentView(binding.root)
}
}
How should I display the text entered in the first screen to be shown in the second screen?
You can use the "putExtra" method to send the data to next activity,
and "getExtra" to get the data in next activity.
Please Refer the article-
https://medium.com/#haxzie/using-intents-and-extras-to-pass-data-between-activities-android-beginners-guide-565239407ba0
it's very simple, you just need to use putExtras and getExtra in your activities
your first activity is looks like this:
val textToPass = editText.text.toString()
binding.button.setOnClickListener{
val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("SOME_KEY",textToPass)
startActivity(intent)
}
and in a second activity you can get the text by using a getStringExtra and which look like this
val textToDislplay = intent.getStringExtra("SOME_KEY")
textView.text = textToDisplay

App Keeps Crashing When I'm trying to add two editext

please the app keeps crashing on my phone when i try to add the values of two edit text in android studio
i've tried all i can changing the data types
package com.example.danculator
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
lateinit var addbtn: Button
lateinit var fnum: EditText
lateinit var snum: EditText
lateinit var ans: EditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
addbtn=findViewById(R.id.add) as Button
fnum=findViewById(R.id.fnum) as EditText
snum=findViewById(R.id.snum) as EditText
ans=findViewById(R.id.ans) as EditText
addbtn.setOnClickListener {
ans.setText(fnum.text.toString().toInt() + snum.text.toString().toInt())
}
}
}
Don't use setText(int) that expects a resource id but rather use setText(CharSequence). That is, convert your Int computation to result to a String:
ans.setText((fnum.text.toString().toInt() + snum.text.toString().toInt()).toString())
Also, for future reference, examining the crash stacktrace should be the first step when trying to figure out what is wrong. See Unfortunately MyApp has stopped. How can I solve this?
I never used Kotlin before,but take a look at this part of code:
ans.setText(fnum.text.toString().toInt() + snum.text.toString().toInt())
In this part you are sum two integer values and want to set them as text for ans while you should use a string value for ans.So you should convert this to string again:
ans.setText((fnum.text.toString().toInt() + snum.text.toString().toInt()).toString())

Resources