0

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.

Main Activity of Basic 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()

        }
    })

}

Fragment of Tabbed Activity (no matter where i put it, it does not work)

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)

}

This is the Debug error i keep getting:

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

Markus Kauppinen
  • 3,025
  • 4
  • 20
  • 30
badavis78
  • 33
  • 1
  • 6
  • You should setup the listener in onViewCreated() of a fragment, pay attentions, there's onCreateView() method that creates the view, then calls onViewCreated() where the view is ready to be used, otherwise your button is still null and you cannot use it – Tamim Attafi Jul 28 '19 at 23:48
  • 1
    that did the trick. thank you – badavis78 Jul 29 '19 at 04:08

1 Answers1

1

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()
badavis78
  • 33
  • 1
  • 6