Error replacing ButterKnife annotation with native ViewBinding

189 Views Asked by At

I'm refactoring a lot my app activities and layouts (e.g. ButterKnife annotation -> viewBinding, *Layout --> ConstraintLayout). For a lot of them there were no problem, but at the moment I'm stuck in this situation of my Activity:

Original code:


    ...

    @BindView(R.id.logged_user)
    TextView mUserLoggedView;

    @BindView(R.id.patient_code)
    EditText mPatientCodeView;

    @BindView(R.id.search_form)
    ScrollView mFormView;

    @BindView(R.id.search_progress_layout)
    LinearLayout mProgressLayout;

    @BindView(R.id.search_progress_text)
    TextView mProgressTextView;

    App application;

    SearchActivityMapper mapper;

    CompositeDisposable mCompositeDisposable;

    @Override
    protected void onCreate(Bundle savedInstance) {
        super.onCreate(savedInstance);

        setContentView(R.layout.activity_search_patient);
        
        ButterKnife.bind(this);
        application = (App) getApplication();
        application.getAppComponent().inject(this);

        ...

Code after review:

    ...

    App application;

    SearchActivityMapper mapper;

    CompositeDisposable mCompositeDisposable;

    @Override
    protected void onCreate(Bundle savedInstance) {
        super.onCreate(savedInstance);

        viewBinding = ActivitySearchPatientBinding.inflate(getLayoutInflater());
        setContentView(viewBinding.getRoot());
        
        ButterKnife.bind(this);
        application = (App) getApplication();
        application.getAppComponent().inject(this);             

        ...

I did the same in all the previous Activity and everything went well; when the latter Activity is launched I got this error

java.lang.NoSuchFieldError: No field mUserLoggedView of type Landroid/widget/TextView; in class Lit/company/etmhome/activities/search/SearchActivity; or its superclasses (declaration of 'it.company.etmhome.activities.search.SearchActivity' appears in /data/data/it.company.etmhome.debug/code_cache/.overlay/base.apk/classes27.dex)

I can't understand why it can't find that field that I removed and it's not present in the whole project.

Am I missing something???

Thanks in advance

1

There are 1 best solutions below

0
Sterling On

I assume the OP has got past this issue by now, but I've recently run into it while migrating some legacy code from Butterknife to View Bindings, so I thought I'd drop the solution here for anyone else who may need it.

Apparently Butterknife caches its field bindings, and will throw this error when those fields no longer exist. I found that the following steps were required to clear it:

  • In Android Studio
    • Build > Clean Project
    • File > Invalidate caches, and clear both the file system and VCS Log caches
  • On-device, clear the app's cache (or uninstall+reinstall if that's easier for you)