Question

I have an Activity with a custom view in its Xml layout file:

<com.example.androidmontreal.mvp.infrastructure.views.AndroidRaceResultsView
    android:id="@+id/raceResults"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"/>
    ...

In the onCreate method of this activity I use Butterknife to inject my views:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mvp_main);

    ButterKnife.inject(this);

    ...

}

In my custom view I have a listview. Before adding Butterknife I used to set the adapter for the listview in the onFinishInflate method:

    @Override
protected void onFinishInflate() {
    super.onFinishInflate();

    ...

    listView.setAdapter(resultsAdapter);
}

Since adding Butterknife however, I get an NPE on the line where I set the adapter, because at that stage listview is Null.

My understanding is that the view is only instantiated when the Butterknife.inject() method in the Activity is called, but this happens after the view has been inflated. What I can't figure out is when I should set the adapter for the listView.

Edit: It seems that the children views on my custom view is null, even after utterknife.inject() has been called on the activity. If I add a call to Butterknife.inject to my onFinishInflate method however, I get an error saying that java.lang.IllegalStateException: Required view with id '2131034112' for field 'listView' was not found

Was it helpful?

Solution

You can do it just after

ButterKnife.inject(this);

Internally it fills the listView variable, so it's become available for you.

Ensure that you have

@InjectView(R.id.raceResults)
AndroidRaceResultsView listView;

in you activity.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top