ChatGPT解决这个技术问题 Extra ChatGPT

"cannot resolve symbol R" in Android Studio

Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.

In every instance in all of my classes where I reference R.id.something, the R is in red and it says "cannot resolve symbol R". Also every time there is R.layout.something it is underlined in red and says "cannot resolve method setContentView(?)". The project always builds fine. It is annoying to see this all the time. I have read many other questions on here about something similar but most involved importing projects from Eclipse. I am using what I believe to be the most recent version of Android Studio and the project was created with Android Studio and worked without any "cannot resolve R" problems. I would like to know what causes this if anyone knows.

in the past I have gotten xml errors such as : progressbar cannot be cast to android.widget.textview, and i fixed that by just changing the name of the textview. I still really dont know what caused the error to begin with.
If u changed the name, perhaps you are now trying to use a string reference that does not exist in res/strings.xml?
i searched many times before asking this question and found many similar questions including the one you mentioned. i did read the suggestion in that question and there is no import Android.R in any of my java files.
Hey everyone I forgot about asking this question since it was asked so long ago. I should have accepted my own answer a year ago that is now the comment above this. The issue was with simply that android studio was in such an early stage at the time and as a new developer I never should have never been using it. Rest assured everything is working fine now and has been. If it is possible please undelete my original answer so I can accept it.
Not finding R isnt your error its an error caused by a Build fault Fix your other errors and you should be fine.

t
tokhi

I had this this issue too. A simple 'gradlew clean' and 'gradlew build' did the trick.

Click on Build->Clean Project and that will perform a gradle clean


some times you also need to restart android studio. or at least for me.
For those who convulse over using the command line, click on Build->Clean Project and that will perform a 'gradlew clean'. ;)
No luck...The cleaning rebuilding doesn't working fr me
if clean,rebuild,invalidate caches-restart doesn't solve go for: import package.R;
For me this was causing the problem: Mismatch among ApplicationId in gradle and package name in manifest (and though the auto import added the wrong address for the R file). I recommend this little article to make clarification of difference between the two. blog.stylingandroid.com/package-name-vs-application-id
O
Om Sao

In the latest versions of Android Studio, at least for me, the following works:

"Tools" -> "Android" -> "Sync Project with Gradle Files"

In latest Android Studio 3.1.3 (July 2018), "Sync Project with Gradle Files" is available in main menu bar.

https://i.stack.imgur.com/fKCc0.png


What was the version of Android Studio you used that time?
Does not work for me (Android Studio 0.8.14). But, Build > Clean project works well.
Still works in Android 1.2.1. Remember to do this more than once, if it doesn't work in first time.
This is the only thing that worked for me. I tried all of the other solutions first.
In Android Studio 3.1.1, this option is in File -> Sync Project with Gradle Files
T
Tushar Monirul

I was using gradle 3.3.0. It was the main culprit. Wasted 6.50 hours from my life. Gradle 3.2.1 removed the error.

classpath 'com.android.tools.build:gradle:3.2.1'

Problem resolved after changing the gradle version. Details history can be found here.


Yet another amazing feat by Android studio developers. Reverting back to 3.2.1 was actually the only solution that has worked for me...
Astonishingly still an issue 2 months later. Latest version (3.3.2) didn't fix it, 3.2.1 did.
Instead of moving back to gradle 3.2.1 you can also upgrade Android Studio to version 3.3. See my answer here
it worked by changing 3.3.0 to 3.2.1 but my question it was working fine on 3.3.0 i had just refactor and updated manifest xml file and gradle file and had sync the gradle . May i know what might be the reason
25 hours of internet and looks like this is the only working solution. Thanks android studio :(....
M
Mina Fawzy

I have a similar problem and here is what I did:

Clean Project and Sync Project with Gradle ,

https://i.stack.imgur.com/eJQc7.png

https://i.stack.imgur.com/uYTQZ.jpg

From build gradle (module ) change minSdkVersion from 8 to 9

defaultConfig {
        applicationId "PackageName"
        minSdkVersion 9
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }

But all this didn't help.

Finally I found the answer (this worked in my case)

Change from build.gradle(module:app)

android {
    compileSdkVersion 21
    buildToolsVersion '21.0.1'
......
....
}

Or

Select File | Project Structure change Build Tools Version to 21.1.1

https://i.stack.imgur.com/yeyP5.png


Y
Yuriy Vasylenko

Check your xml files. Clean Project.

This is it.

For example I had an entry in my strings.xml:

<string name="A">Some text</string>

And in activity_main.xml I used this string entry

<TextView
android:id="@+id/textViewA"
android:text="@string/A"/>

While'd been working with project, I deleted that

 <string name="A">Some text</string>

And consequently activity_main.xml became not valid. As the result: cannot resolve R.

So, check your *.xml files and clean project.


A missing image one of my XMLs referred to caused this issue for me. Put the image in the folder, cleaned and R is now happy again.
I accidentally had my string defined twice in strings.xml. Studio didn't show that at all. X-( Thank you for your answer.
Why is there no feedback to underline bad XML files in the IDE?
When something like you mentioned occurs, the issue gets highlighted in the xml. I've tried everything I could find in the internet, but nothing solves my problem, although the app runs normally.
s
serv-inc

If you see this error after moving java files or directories to other locations, then you can guarantee that Android Studio has gotten confused. And guess what? undo-ing those actions doesn't fix the problem.

So you try a clean, but that doesn't work.

And restarting doesn't work either.

But try File -> Invalidate Caches / Restart... -> Invalidate and Restart

Android Studio maintains information about which files are dependent on which other files. And since moving files around is not implemented correctly, moving files causes errors. And that's not all: caches of these dependencies are used in an attempt to speed up the build.

This means you not only have to restart, but you need to invalidate those caches to restore (or more accurately, rebuild) sanity.


Did not help. Tried cleaning/rebuilding too. Error occured after I moved java package into another package. Interestingly, in one package R class can be accessed, but it cannot be accessed in package that I moved.
In the more recent versions of Android Studio, Invalidate and Restart are now the default menu selection. This should help at least a few people. (Too bad they don't fix all the crazy bugs that cause this error in the first place!)
I got this error after moving and renaming a project. This solved the R problem after all cleaning and restarting did not. Thank you.
This is definitely the right answer if you have first tried 1.)Clean & Rebuild 2.)Ensuring your xml files are valid
M
M.A.K. Ripon

I think if you put your Activities files to another folder than the default one. You need to import the com.example.yourproject.R (this is your project R file NOT Android.R file) to ALL activities using R. For example, in MainActivity file insert this line:

import com.example.yourproject.R;

Ah, and there will be still error message before you first build. However, you just press build, Android Studio will generate the R file and the build should success.
and I think it's better that after the fix, you should clean your project and then build. or press Shift + F9 for debug with your device or emulator. I prefer to debug on real device.
M
Mr Robot

There seems to be many causes for this issue. Recently, I added an activity to test with called NewActivity. This created a file called res/menu/new.xml and gradle did not like that name because new is a reserved word.

gradlew clean

or

"Tools" -> "Android" -> "Sync Project with Gradle Files"

Those are definitely good things to try, but you may have some other issues you need to resolve before you run those commands.


thanks worked for me too. Small question - where should i type gradlew clean if i want to do it this way (i did "Tools" -> "Android" -> "Sync Project with Gradle Files")?
Open a command terminal, switch to the project directory and execute "./gradlew clean"
How does this solve the problem better than 'Rebuild Project'?
Yes, in my case I added a png file, called "import.png". I had to rename it, in my case "import_icon.png" and then the project compiled ok.
Z
Zoe stands with Ukraine

R.java file contains the link between xml and java page. "R cannot be resolved" arise only if there is a problem with some of your resource files. So the best and effective way is delete the last done xml or drawable in res file. and then again start from there according to android coding norms. This is the only way. The effective and right way.

Also use Git for proper tracking of code. ..


In my case there were not only problems in XML, but also in PNG (in drawable).
l
lloydyu24

Your code is just scrambled. The answer is fairly simple.

Just go to Build --> Clean Project.

That should do the trick.

Check also your version of Android Studio.

I'm currently using Android Studio 3.0.1.


Cleaning the project worked. Looks like a bug in android gradle plugin
i
invertigo

Have you updated your SDK tools recently? Launch the android SDK manager and make sure you have the latest SDK tools, which is now separate from the platform tools. I had this same issue when I first updated my SDK manager, the SDK build tools package did not show up for install/update until I closed and reopened the SDK manager.


i believe everything is up to date there. could that really cause a problem like this?
if you don't have the new SDK build tools installed, yes.
P
Pervy Sage

I had to import my R package in android studio. For ex: import com.example.<package name>.R


This happened to me after I refactored my package name, but somehow the android studio left the import com.example.old-package-name.R, so I had to rename the import.
I had moved some UI stuff to a sub-package and then got the error, I needed to import R from the parent package.
A
A P

You should do two things, first clean the project (in build menu) - it deletes the build directory which may be the culprit:

https://i.stack.imgur.com/cvHwL.png

Next, Sync project with Gradle files (under file):

https://i.stack.imgur.com/2lxyP.png

This is the placement for the items in Android Studio 3.6.1 on Windows 10.

If all else fails, Invalidate Caches and Restart (under file) usually does the trick. This closes down the whole program and takes the most amount of time, in my opinion.

https://i.stack.imgur.com/97Oin.png

To clarify, I am running this on windows 10, but it should work on MacOS and Linux as well.


Absolutely amazing, saved my day
@IdoBarnea glad to help!
thanks. Invalidate Caches and Restart solved the problem
A
Arunendra

https://i.stack.imgur.com/hvdVL.png

And the problem will be resolved.


It should be noted that right clicking on "app" and clicking the synchronise button in the menu does not achieve this. Thanks.
R
Ryan Heitner

I have had this with

An uppercase letter in my drawable resources. Import Android.R being added by Android Studio (or Eclipse) Error in xml file


I had the issue because there was an error in one of my XML files. Resolved the issue then did a Build->Clean Project
M
Matthew Cawley

I recently had this issue and the clean/build etc. didn't resolve it. I guessed I had an issue somewhere but wasn't sure where to look to find it (was it in the manifest, resource xml files etc?).

When something is wrong, you can find out what it is by doing a code analysis run.

From the menu at the top choose:

Analyze -> Inspect code, scan the whole project using the 'Default' profile.

Your inspection results will contain an element called 'Android'. In here you will get a list of anything that is causing issues in your resources and manifest file. The errors will open up the generated xml files from your build which will show any errors in red.

My exact issue was caused because I was using flavour based manifest files and I copied some permissions inside the <application> tag in the flavour by accident.

https://i.stack.imgur.com/VCyc5.png

UPDATE: I did have an issue after where Android Studio still showed the error after the fix, even though I could now build and run perfectly fine while the error was still there. (I am running a canary build so putting it down to that for now)


Interestingly, I had this issue on just one file and ran the "Inspect Code" process and it cleared itself (clean and rebuild didn't fix it). There must have been something stuck in Lint that only this could clear out. Thanks!
Thank you for this! While this found many general errors, which was expected, the piece that brought down the entire castle was a small Syntax error in an XML file generated by Asset Studio! Once I resolved this, a Clean Project allowed me to move forward.
S
Sridhar

I faced this issue when I manually renamed the domain folder of my app. To fix this issue, I had to

Set the proper package folder structure of in AndroidManifest.xml. Set the new package location for android:name of in AndroidManifest.xml. Clear cache by

File Menu -> Invalidate Caches / Restart ...

The issue will be gone, once the Android studio restarts and builds the fresh index.


In my case I merely had to import R from my new package name import com.Neue.Package.R;
A
Alex Burov

I had the same issue: Android Studio 3.2 The project compiles and runs fine, but I am getting "Cannot resolve symbol "R" on-screen warnings

Does not help:

Build->Clean Project

Build->Rebuild Project

File->Invalidate Caches/Restart

Helps:

either

in build.gradle

dependencies {
        classpath 'com.android.tools.build:gradle:3.3.0'
...
}

replace with

   dependencies {
            classpath 'com.android.tools.build:gradle:3.2.1'
    ...
    }

or

Update Android Studio to 3.3


You saved my life ! Updating android studio to 3.4 solved the issue for me
T
TBridges42

This is a very old question, but it still happens a lot and there is no truly comprehensive answer here.

I have had this problem more times than I want to admit. It can be caused by a wide variety of issues that mostly all have to do with your project structure not matching what's expected. Here's a list of all the problems I've had:

Importing from Eclipse to Android Studio does not always work smoothly, especially with older versions of Android Studio. Make sure you're using the correct directory tree. It should look like this for a moderately mature app:

AppName/        // AppName is your app's name, obviously
    .gradle/    // This is a compiler created directory. You should normally leave it alone
    .idea/      // Ditto
    build/      // This too
    gradle/     // And this
    app/
        build/
        libs/
        src/
            androidTest/   // Tests based on the Android instrumentation runner should go here
            main/
                java/
                    fully/           // Typically com
                        qualified/   // the domain name. Longer package 
                                     // names may have deeper folder trees
                            AppName/ // All your java files go here
                res/
                    drawable-*/      // One of these for each resolution you support
                    layout/          // All of your general layouts
                    menu/            // All of your menu layouts
                    values/          // All of your resource xml files
                    xml/             // PreferenceScreen layouts go here
                AndroidManifest.xml
            debug/         
            test/          // Pure jUnit tests should go here
        .gitignore
        app.iml
        build.gradle   // This is the gradle file you should be making most changes to
        proguard-rules.pro
    .gitignore
    build.gradle       // This gradle file should mostly be left alone
    gradle.properties
    gradlew
    local.properties
    AppName.iml
    settings.gradle

It may not look like this in your IDE. There is a drop-down above the file tree that displays your files in different ways, and it defaults on my system to one called Android that breaks your files out into their different types. It's easier to fix this kind of problem from the one called Project, and even easier directly from your OS's file system, because Android Studio collapses folders that only contain another folder onto a single line.

Especially if you ever change the name of your app, you need to make sure that the source tree main/java/com/domain/AppName is updated. Also make sure that the package tag in your AndroidManifest.xml is correct.

If there are errors in either your Gradle files or your AndroidManifest.xml, this will prevent Android Studio from properly building your resource files. Gradle files can be broken by upgrading Android Studio sometimes, especially from the pre-1.0 versions. Sometimes this is because it stops supporting older versions of the Gradle plugin, so you need to update your version numbers. It can sometimes be hard to find what the current versions are. As of today, 7/17/15, my apps are compiling fine with com.android.tools.build:gradle:1.2.3. This is in the dependencies block in the outermost gradle file,

If your AndroidManifest references a non-existent drawable or string resource or activity, it will break and cause this error. Sometimes if anything references a nonexistent drawable or string resource you will get this error.

If you have a file in your resources that is corrupted, or an invalid xml file, you will get this error.

In my experience, sometimes Android Studio just hiccups for no reason, and you need to restart it and/or your PC. I don't know why, but sometimes it works.

If you have two xml resources with the same name, in directories that do not override each other, you can have this problem. For instance, you can have the same name in drawable-mhdpi and drawable-xhdpi because they override each other depending on the target device, but if you have the same name in layout and in menu, it will cause a problem. Rename or delete one of the files.

If only some resources are having this problem, those resources are most likely in the wrong directory.

In one case I had to completely reinstall Android Studio. I don't know what was wrong, but it worked.

In one case I moved my entire project to a different directory and re-imported it as a new project. I don't know what was wrong, but it worked.

Xml files with reserved words for names can cause this problem. Rename or delete them.

There are a few ways your Gradle file can end up referencing a version of the build-tools that you do not have installed. Correct this by changing Gradle or downloading the appropriate build-tools.

Finally, after you've fixed whatever is wrong, you need to clean your Gradle project. You do this by going to the Build menu at the top and selecting Clean Project.


G
Gundu Bandgar

Just go to Android Top menu list. click on Build Menu, in under Build click on Rebuild Project.

https://i.stack.imgur.com/5tmuZ.png


J
Jiakang Zhang

I have a special case for this problem.

In my project, every thing goes well, it can compile and build successfully, but in my Android Studio IDE(and I also tried Intelligent IDEA, they are in the same situation) the R.java file can not be resolved well and always be drop in red line.

https://i.stack.imgur.com/ntmYS.jpg

This almost made me crazy, I can't bear the read color when I am programing.

At last I found this tricky problem is cause by my R.java's file size. My project is very a huge one, it supports many multi-languages and multi screen sizes. There are so many resources that my R.java's file size is about 2.5M.

The max size of a file in Android Studio is 2.5M in default settings, so files bigger than this limit can't not be resolved well. And you can change the default settings in "AndroidStudio-root/bin/idea.properties".

change this line:

idea.max.intellisense.filesize=2500

to :

idea.max.intellisense.filesize=5000

Then restart Android studio, the red color dismissed, I can program happily again.


In Android 3.2 just help/Edit Custom Properties
S
S.Pedro

Build > Clean Project

This worked for me. Had the same problem a few times, and this seems to set it right. Unless you have changed something or called a variable R. This issue usually happens out of nowhere, when it happens to me, so I imagine its just Android studios freaking out. haha

Have a good one, and good luck with your projects.


Thanks. It worked for me too. I replaces some images in drawable and got that error.
H
Hassan Naqvi

Do: Build > Clean Project

IMPORTANT: Make sure you don't have any Errors after Clean Project in Message Pane (Alt+0). If you find any red circles with exclamation mark, than you must remove those errors in your code.

Mostly these errors are related to @string/ or @array/. Clean Project again and done!


E
Elsanty

I had the same problem, and it happens when I create a new project.

What I do is:

check for SDK updates

then android studio updates,

then reopen the project

open the andoridmanifest.xml

erase a space between a "_>" in the android:label and save.

That works for me.


O
Oussama Essamadi

I had a hard time fixing this myself.

Make sure you have no errors in your layout.xml files.

Go to Build > Clean project

It worked for me, hope it works for you too.


S
Siva Prakash

I had the same problem and most times it is resolved by

Sync project with gradle files

Doing Build -> Clean Project

Doing File -> Invalidate Caches

But this time the error persisted even after doing all these things and at last i found the culprit.

The problem was in an xml file, where i have given ordinary string value for an android:id instead of an id resource type.

MISTAKE

android:id="username"

CORRECTION

android:id="@id/username"

Messing up things related to resources in xml files is a major reason for this error.Beware of the fact that it may not be shown as an error in the xml layout file.

NOTE

In most cases the compiler shows you the source of error in the Message. Try to check it first before attempting other solutions


B
Bapusaheb Shinde

`I had same problem and it solved by :

1) Sync Project with gradle files
2) Build -> Clean Project
3) Build -> Rebuild Project
4) File -> Invalidate caches

//imp step
5) Check your xml files properly.`

This is a good answer, although I only needed to place '//' in the gradle file and select resync. Then all AS recognized the import and allowed me to run the app.
T
Tevin J

This notation seems to work fine.

android:id="@+id/viewID"

Android Studio's design panel doesn't seem to work well.


u
user1137313

Same problem. Started when I added a few images in my drawable folder and tried to access them. Also the images added were having the extension with capital letters. That seems to have crashed the build, since even if I renamed them, the message was the same and R was inaccessible. What I did is, in the .iml file I looked for the excludeFolder and removed them (like bellow):

  <excludeFolder url="file://$MODULE_DIR$/build/apk" />
  <excludeFolder url="file://$MODULE_DIR$/build/assets" />
  <excludeFolder url="file://$MODULE_DIR$/build/bundles" />
  <excludeFolder url="file://$MODULE_DIR$/build/classes" />
  <excludeFolder url="file://$MODULE_DIR$/build/dependency-cache" />
  <excludeFolder url="file://$MODULE_DIR$/build/incremental" />
  <excludeFolder url="file://$MODULE_DIR$/build/libs" />
  <excludeFolder url="file://$MODULE_DIR$/build/manifests" />
  <excludeFolder url="file://$MODULE_DIR$/build/res" />
  <excludeFolder url="file://$MODULE_DIR$/build/symbols" />
  <excludeFolder url="file://$MODULE_DIR$/build/tmp" />

After that I rebuilt the project and R magically re-appeared.


S
Sourav Roy

There are many causes for this error.

Sometimes it occurs for replacing an image file keeping same name. Suppose you deleted an item from your layout .xml say a