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

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

Related

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

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

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)

Struggling to transition code from AppcompatActivity to Fragment. Unable to use setSupportActionBar(toolbar)

I'm trying to transition from using AppcomatActivity to Fragment, because I'm updating my app but I've run into a problem. I get a "Unresolved reference: supportFragmentManager" and "Unresolved reference: setSupportActionBar"(That's all the Logcat shows me) when I try to run my app. Now I chose to switch to using fragments, because I also want to change the apps UI, usage is quicker than the previous version. Anyway here's my code:
Recorder Fragment
package com.khumomashapa.notes.fragments
import android.os.Build
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toolbar
import androidx.annotation.RequiresApi
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import com.astuetz.PagerSlidingTabStrip
import com.khumomashapa.notes.R
import kotlinx.android.synthetic.main.toolbar3.*
class RecorderFragment : Fragment() {
private var tabs: PagerSlidingTabStrip? = null
private var pager: ViewPager? = null
#RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activity?.title = "Recorder";
pager = pager?.findViewById<View>(R.id.pager) as ViewPager
pager!!.adapter = MyAdapter(supportFragmentManager)
tabs = tabs?.findViewById<View>(R.id.tabs) as PagerSlidingTabStrip
tabs!!.setViewPager(pager)
val toolbar = toolbar?.findViewById<View>(R.id.toolbar) as Toolbar
toolbar.popupTheme = R.style.ThemeOverlay_AppCompat_Light
setSupportActionBar(toolbar)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_recorder, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
}
inner class MyAdapter(fm: FragmentManager?) : FragmentPagerAdapter(
fm!!
) {
private val titles = arrayOf(
getString(R.string.tab_title_record),
getString(R.string.tab_title_saved_recordings)
)
override fun getItem(position: Int): Fragment {
when (position) {
0 -> {
return RecordFragment.newInstance(position)
}
1 -> {
return FileViewerFragment.newInstance(position)
}
}
return null!!
}
override fun getCount(): Int {
return titles.size
}
override fun getPageTitle(position: Int): CharSequence? {
return titles[position]
}
}
companion object {
private val LOG_TAG = RecorderFragment::class.java.simpleName
}
}
The purpose of this class is to show a view pager that can switch between to other fragments I've already created. I was able to fix the other errors relating to this like the "Unresolved reference for findViewById" and the "MyAdapter class".
For a Fragment, there are actually two relevant fragment managers. Deciding which one to use depends on your use case.
The Child Fragment Manager
A fragment has a child fragment manager which is responsible for managing its child/nested fragments. You can obtain this with:
Fragment.getChildFragmentManager()
The Parent's Fragment Manager
A fragment also holds reference to it's parent's fragment manager. If the fragment is a direct child of an activity then his represents the activities fragment manager. Otherwise if the fragment is a child of another fragment, it represents the child fragment manager of the parent fragment. This can be obtained with:
Fragment.getParentFragmentManager()
Note that although Fragment has the method Fragment.getFragmentManager(), this is deprecated in favour of Fragment.getParentFragmentManager() so it shouldn't be used.
You can also technically get the activities fragment manager regardless by obtaining a reference to the fragment's activity with Fragment.getAcitivity() and then calling Activity.getSupportFragmentManager(). But generally the parent fragment manager is more useful and clear.

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