How to add an onClickListener on a View in custom fragment?

  android, android-fragments, java, kotlin

I am creating a Login and signup form. I have created two custom fragments, one for login and one for signup. Both have some clickable textViews, and I want to add onClickListener to these textViews, however I am getting Null Pointer Exception when I am trying to access these views from my fragment class.

My custom login fragment class:

package com.example.contactsaver


import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import kotlinx.android.synthetic.main.fragment_login.*


class LoginFragment: Fragment(){

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        val view = inflater.inflate(R.layout.fragment_login,null)
        return view
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        tvNewAccount.setOnClickListener {
             //todo
        }
    }
}

Main Activity:

package com.example.contactsaver

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.fragment.app.Fragment


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val loginFragment = LoginFragment()
        setFragment(loginFragment)
    }



    private fun setFragment(fragment: Fragment){
        supportFragmentManager.beginTransaction().apply {
            replace(R.id.flFragments,fragment)
            commit()
        }
    }


}

This is the error:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at com.example.contactsaver.LoginFragment.onCreate(LoginFragment.kt:26) 

Source: Android Questions

LEAVE A COMMENT