I am currently developing an app and I am trying to make a Utils file with some general functions that I can use throughout my application to avoid having to copy/paste the same function many times. I have a Utils class file and I am passing the current Activity into that class. For some reason, when I call findViewById() in init, it returns null and the app crashes. I have tried logging the activity that is being passed into the Utils class, and to my eyes it appears like the right activity, so I am not sure why it is failing. I will show the relevant code below:
Utils.kt (There is more, but it isn't relevant to the question)
class Utils(activity: Activity) {
private var currentActivity: Activity
private var fragmentManager: FragmentManager
private var topAppBar: MaterialToolbar
val activitiesList = listOf(
"recipes", "budget", "inventory", "customers",
"reports"
)
init {
currentActivity = activity
println(currentActivity)
fragmentManager = (activity as AppCompatActivity).supportFragmentManager
topAppBar = currentActivity.findViewById(R.id.top_app_bar)
}
}
MainActivity.kt (Again there is more, but not relevant)
class MainActivity : AppCompatActivity() {
private lateinit var drawerLayout: DrawerLayout
private lateinit var topAppBar: MaterialToolbar
private lateinit var utils: Utils
private val fragmentManager = supportFragmentManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
fragmentManager.beginTransaction().replace(R.id.frame_layout, HomeFragment()).commit()
utils = Utils(this@MainActivity)
topAppBar = findViewById(R.id.top_app_bar)
drawerLayout = findViewById(R.id.drawer_layout)
val navigationView: NavigationView = findViewById(R.id.navigation_view)
The error comes from the Utils.kt file in the last line of actual code where I try to assign topAppBar to the view of id top_app_bar, but it returns null. My println (yes I know I should be using Log.i but println is quicker to type) in the Utils class returns com.example.bakingapp.MainActivity@501533d, which is what I would expect if I am understanding what is happening correctly. Any insight as to why I can't find the views would be appreciated.
I figured out the problem. It is a scope issue. I am trying to find the id of a view outside of the current Activity/Fragment I am looking at. I realized then a lot of my code could/should be moved into the Fragment I was trying to target and this has fixed my issues.