-1

i want to use viewmodelproviders in anko component

i studied viewmodel documentation on google developer guide but this particular use case is not documented

class BroadcastCalendarFragment: Fragment() 
{
  lateinit var mBroadcastModel: BroadcastModel

  override fun onCreateView(inflater: LayoutInflater, container: 
  ViewGroup?, savedInstanceState: Bundle?): View? {
        return BroadcastCalendarUI<Fragment>().createView(AnkoContext.create(ctx, this))
    }
}

class BroadcastCalendarUI<BroadcastCalendarFragment>(): AnkoComponent<BroadcastCalendarFragment>
{

    lateinit var broadcastModel: BroadcastModel

    override fun createView(ui: AnkoContext<BroadcastCalendarFragment>): View = with(ui) {
    verticalLayout{
      button.setOnclickListener{
      broadcastModel = ViewModelProviders.of(BroadcastCalendarFragment()).get(BroadcastModel::class.java)

      }
   } 
  }
}

If I click on the button, there is an error saying

java.lang.IllegalStateException: Can't create ViewModelProvider for detached fragment

(It craps out at the line where I use ViewModelProviders(BroadcastCalendarFragment() in the click listener)

1 Answers1

0
 ViewModelProviders.of(BroadcastCalendarFragment())

is creating a new BroadcastCalendarFragment and trying to find/create the viewmodel from it. The issue is that this new fragment is not attached to any activity and for this the ViewModelProviders is not able to find a suitable provider.

You should be able to find the apropiate fragment instance with

ViewModelProviders.of(owner).get(BroadcastModel::class.java)
Eric Martori
  • 2,885
  • 19
  • 26