Kotlin Android项目遇NoSuchFieldError:字段存在却报错求解决方案
fragment_contain in Your Kotlin Android App Hey there, let’s work through this NoSuchFieldError you’re hitting. The error says it can’t find the static field fragment_contain in com.android.example.cameraxbasic.R$id, even though you’re sure the field exists. Looking at your code and crash log, here are the key fixes to try:
1. Double-Check Your Layout File
First, verify that your activity_main.xml layout actually has the correct ID:
- Open
res/layout/activity_main.xmland confirm there’s a view withandroid:id="@+id/fragment_contain"(exact spelling, no typos like missing letters or extra spaces). - It’s easy to accidentally type
fragment_containerinstead offragment_contain—a tiny typo that causes big headaches!
2. Clean & Rebuild Your Project
Android Studio’s generated R file can sometimes get stuck with outdated cache, leading to missing fields. Do this step-by-step:
- Go to Build > Clean Project to wipe old build files.
- Then run Build > Rebuild Project to generate fresh resources and
Rclasses. - If that doesn’t work, manually delete the
.gradleandbuildfolders in your project root, then sync with Gradle (File > Sync Project with Gradle Files).
3. Fix the R Class Import (Critical!)
Looking at your crash log:
Process: com.virtusync.scanningtool, PID: 21098
java.lang.NoSuchFieldError: No static field fragment_contain of type I in class Lcom/android/example/cameraxbasic/R$id;...
Your app’s package is com.virtusync.scanningtool, but the error is referencing com.android.example.cameraxbasic.R$id—this means your code is pulling the wrong R class!
- Check the imports at the top of
MainActivityWarrant.kt: you probably haveimport com.android.example.cameraxbasic.Rinstead ofimport com.virtusync.scanningtool.R. - Replace the incorrect import with your app’s actual
Rclass, then recompile.
4. Rule Out Resource Conflicts
If you’re working with multiple modules or libraries, resource IDs can clash. Try:
- Renaming the ID in your layout to something unique (e.g.,
android:id="@+id/vs_fragment_contain"). - Update the reference in your activity code to match the new ID:
container = this.findViewById(R.id.vs_fragment_contain).
5. Disable Instant Run
Instant Run can sometimes skip updating resources properly. Turn it off:
- Go to Settings > Build, Execution, Deployment > Instant Run.
- Uncheck "Enable Instant Run to hot swap code/resource changes on deploy".
- Rebuild and run your app again.
Quick Note on Your Code
In your MainActivityWarrant’s onCreate method, make sure after fixing the ID issue, the container variable is correctly initialized before using it in onResume (which it should be, as long as the ID is found).
内容的提问来源于stack exchange,提问作者Iyke

