Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getFragmentManager() not working in Kotlin

Tags:

android

kotlin

I'm trying to launch a DialogFragment that is contained within a library module locally in my project. The class which I'm calling it from is using Kotlin and I'm getting the following error on the function getFragmentManager(): None of the following functions can be called with the arguments supplied

  import com.github.adamshurwitz.materialsearchtoolbar.SearchDialogFragment
    ...

    private var searchDialogFragment: SearchDialogFragment? = null
    ...

    searchDialogFragment = SearchDialogFragment()
    searchDialogFragment.show(supportFragmentManager, null)

I have another project where I am calling this in Java and it works fine using: getSupportFragmentManager().

Solutions I have tried:

searchDialogFragment.show(getFragmentManager(), null)
searchDialogFragment.show(supportFragmentManager, null)
searchDialogFragment.show(supportFragmentManager as FragmentManager, null)
searchDialogFragment.show(supportFragmentManager.beginTransaction(), null)
searchDialogFragment.show(supportFragmentManager(), null)
like image 897
Adam Hurwitz Avatar asked Jun 22 '17 18:06

Adam Hurwitz


People also ask

What can I use instead of getFragmentManager?

Yes, using the support library Fragment along with the getSupportFragmentManager is the right thing to do.

How to use FragmentManager in android?

To display a fragment within a layout container, use the FragmentManager to create a FragmentTransaction . Within the transaction, you can then perform an add() or replace() operation on the container. . commit();

What is getFragmentManager?

getFragmentManager() deprecation: The getFragmentManager() and requireFragmentManager() methods on Fragment have been deprecated and replaced with a single getParentFragmentManager() method, which returns the non-null FragmentManager the Fragment is added to (you can use isAdded() to determine if it is safe to call).


1 Answers

Since your searchDialogFragment variable is marked as nullable with the question mark in the declaration you need to use the safe call operator ?.. It only executes when searchDialogFragment is not null:

searchDialogFragment?.show(supportFragmentManager, null)

Or you could use the following to declare your variable as not null but still be able to initialize it later in your code:

private lateinit var searchDialogFragment: SearchDialogFragment
like image 153
Jakob Ulbrich Avatar answered Oct 05 '22 04:10

Jakob Ulbrich