Android build.gradle报错:Cannot invoke method android() on null object 及compileSdkVersion未指定问题求助
Hey there, let's break down these two frustrating errors and get your project syncing again—even after rolling back your changes, these issues are usually tied to misconfigured files or cached data, not your actual version code edits.
First Error: "Cannot invoke method android() on null object"
This almost always happens when you've put module-level Gradle code in the project-level build.gradle file, or vice versa. Android projects have two key build.gradle files:
- The root project build.gradle (in your project's top folder): This handles project-wide dependencies and repositories, and should never have an
android{}block. - The app module build.gradle (in
app/folder): This is where your app-specific config (like compileSdk, version codes) lives—this is exactly where the code you pasted should be.
Double-check that you didn't accidentally move your android{} block into the root build.gradle. A correct root build.gradle looks something like this:
buildscript { repositories { google() mavenCentral() } dependencies { // Use a Gradle plugin version compatible with your compileSdk (e.g., 7.0.0 for compileSdk 29+) classpath "com.android.tools.build:gradle:7.0.0" } } allprojects { repositories { google() mavenCentral() } } task clean(type: Delete) { delete rootProject.buildDir }
Second Error: "compileSdkVersion is not specified"
Even though your code clearly defines compileSdkVersion 29, this error often sticks around because of stale Gradle cache. Android Studio sometimes holds onto old config data that conflicts with your current code. Here's how to fix it:
- Go to
File > Invalidate Caches...in Android Studio, check the box for "Invalidate and Restart", then let the IDE reboot. - If that doesn't work, manually delete the
.gradlefolder in your project root and thebuildfolder inside yourapp/module. Then click the "Sync Project with Gradle Files" button (the elephant icon in the top toolbar) to re-sync.
Bonus Check: Plugin Compatibility
Make sure your Gradle plugin version (in the root build.gradle's classpath) is compatible with your compileSdkVersion 29. For compileSdk 29, you'll need at least Gradle plugin 4.0.0—older versions won't recognize that SDK level.
Final Steps to Verify
- Confirm your pasted code is in
app/build.gradle(not the root build.gradle). - Run the cache invalidation and restart.
- Delete the
.gradleandapp/buildfolders if needed, then re-sync.
That should resolve both errors and get your project back on track!
内容的提问来源于stack exchange,提问作者Symoon98

