0

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

DanielO
  • 145
  • 1
  • 12

1 Answers1

0

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.

avgx
  • 644
  • 5
  • 8
  • The inject call is on my Activity, which does not have access to the listView field on my custom view. Adding an Inject call to my custom view introduces a new error (See edit in the question) – DanielO Jul 30 '14 at 08:10
  • ok, then you'll better take a look at https://github.com/mmBs/NavigationDrawerSI/blob/master/app/src/main/java/mmbialas/pl/navigationdrawersi/ui/navigationdrawer/NavigationDrawerView.java – avgx Jul 30 '14 at 08:49
  • You should check that you have injected your custom view into activity, as in previous link, take a look at how NavigationDrawerView is comming available in MainActivity – avgx Jul 30 '14 at 08:55
  • I am marking this as the answer because the code you linked solved it for me. I changed my main xml layout to use `` with the layout attribute specified as the layout file of my custom control instead of having `` I don't understand why this works, but it does. – DanielO Jul 31 '14 at 09:12