I am trying to get a button to work correctly when it is clicked. for basic example I am using a chronometer. Using Android Studio 3.4.2, I can uses this code in a Basic Activity project in the Main Activity and it works fine. the same code does not work using a Tabbed Activity when I put it in the fragment, fragment page holder or main activity for my Tabbed Activity.
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity;
import android.view.Menu
import android.view.MenuItem
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*
mport kotlinx.android.synthetic.main.content_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
val chronometer = chronometer
val btnstart = (Button)rootView.findViewById(R.id.btnstart);
btnstart.setOnClickListener(object : View.OnClickListener {
override fun onClick(v: View) {
chronometer.start()
}
})
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_retention, container, false)
}
PID: 5241 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference }
the suggestions here do not seems to give me any positive results either onClickListener doesnt work in Tabbed Activity Android
that did the trick. thank you. I placed this in the fragment under inflater as:
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_bph, container, false)}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val chronometer = chronometer
btnstart.setOnClickListener(object : View.OnClickListener {
override fun onClick(v: View) {
chronometer.start()