Hi
I was refactoring a fragment which is inside a Viewpager and I carelessly move a RecyclerView's id to a LinearLayout in the layout xml. While initializing the ViewPager, an Exception was thrown.
java.lang.IllegalStateException: Fragment already added: ...
Normally ButterKnife throws an View 'display_container' with ID for field was of the wrong type. and it does, but the exception is catched by FragmentPagerAdapter and turn out throwing an unrelated exception. It's difficult to find where the problem is.
I suggest adding log.w in ButterKnife.bind() when there is an exception. There maybe other ways to prevent this problem.
That exception comes from FragmentManager, not Butter Knife, and it's not clear how Butter Knife would even cause something like this.
Can you reproduce it in a sample?
For example I defined a RecyclerView in layout xml like this
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/data_container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
But in the code, by mistake, I used
@BindView(R.id.data_container)
TextView textView; // wrong type
In an Activity or a Fragment, ButterKnife will throw an exception which tells the user that a wrong type is used, which is expected.
But when it is in a fragment managed by FragmentPagerAdapter, ButterKnife's exception will be somehow catched by FragmentPagerAdapter and the FragmentPagerAdapter re-throws a confusing IllegalStateException: Fragment already added
final Fragment[] fragments = {
BlankFragment.newInstance()
};
FragmentPagerAdapter adapter = new FragmentPagerAdapter(getSupportFragmentManager(), FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
@NonNull
@Override
public Fragment getItem(int position) {
return fragments[position];
}
@Override
public int getCount() {
return fragments.length;
}
};
pager.setAdapter(adapter);
I think it's FragmentPagerAdapter's fault, but wonder if there is a better solution to warn user.
Ok so let me try to unpack what you're saying...
Do I have that right? This seems like a bug you should file on AndroidX. There's nothing this library can do to change the behavior.
Most helpful comment
For example I defined a RecyclerView in layout xml like this
But in the code, by mistake, I used
In an Activity or a Fragment, ButterKnife will throw an exception which tells the user that a wrong type is used, which is expected.
But when it is in a fragment managed by
FragmentPagerAdapter, ButterKnife's exception will be somehow catched by FragmentPagerAdapter and the FragmentPagerAdapter re-throws a confusingIllegalStateException: Fragment already addedI think it's FragmentPagerAdapter's fault, but wonder if there is a better solution to warn user.