Skip to content

Cannot use TraitContext in Fragments or other places where context is null in constructor #60

Open
@sgrif

Description

@sgrif

I've run into issues attempting to do the following:

class MyFragment extends ListFragment with TraitContext[Context] {
  override def basis = getActivity
  lazy val adapter = new MyAdapter

  override def onCreate(savedInstanceState: Bundle) = {
    super.onCreate(savedInstanceState)
    setListAdapter(adapter)
  }

  //Actual data is given to the adapter later, though the data itself is irrelevant
}

class MyAdapter(implicit context: Context) extends BaseAdapter {
  def layoutInflater = LayoutInflater.from(context)

  override def getView(index: Int, convertView: View, parent: ViewGroup) = {
    if (convertView == null) {
      layoutInflater.inflate(...) // Error occurs here
    }
  }
}

The issue stems from the fact that getActivity returns null at the point where implicit val ctx = basis is evaluated. This could be fixed if ctx were changed to a def or a lazy val.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions