ChatGPT解决这个技术问题 Extra ChatGPT

Android Studio marks R in red with error message "cannot resolve symbol R", but build succeeds

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 project I've tried to create in Android Studio, all usages of R are marked in red with the error message "cannot resolve symbol R", but the compilation succeeds and the application runs. This is really annoying, as it blocks auto-completion and shows huge red waved lines all over my code.

I'm running Android Studio 1.7.0 and creating the project with default settings. A screenshot is attached:

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

This is my build.gradle:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.4'
    }
}
apply plugin: 'android'

dependencies {
    compile files('libs/android-support-v4.jar')
}

android {
    compileSdkVersion 17
    buildToolsVersion "17.0.0"

    defaultConfig {
        minSdkVersion 7
        targetSdkVersion 16
    }
}

This is how the Project Structure looks like:

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

Any idea how to fix this?

Have had this happen on some of my projects. To fix this I 'Clean', 'Rebuild', close project and reopen. Then select Tools --> Android --> Sync Project with Gradle Files. Also have tried the following as well... Close project and physically move the folder to either a new directory or rename the current directory. Now import the project, as if it was new. There are a couple ways to do this, from the initial Android screen, select import and when you locate the Directory, do not import from the project name or master directory, import one level in at 'App'.
Readers, before you try anything else which might be complex... just give a try to restarting android studio.

T
Top-Master

Just Click on Build -> Rebuild Project option in your Android Studio.

But in some cases we may additionally need to, use File -> Invalidate Cache... and restart IDE (beside said rebuild, as something of previous "cannot resolve symbol" state may be cached).

We can auto-complete libraries because they are already built, but own project needs to be built first, and only then Android-Studio can see related resources. #1 Rebuild is required, because Android-Studio does simply rely solely on Gradle's build-result (without static-analysis support, at least at time of writing, 2022). #2 Clearing cache may be required, because the previous build-result (before above rebuild) may be indexed, which may make Android Studio ignore latest Gradle build-result (this is a very good speed optimization, but a very bad Developer-experience as well). There can sometimes be other reasons too, which is why there are many other answers posted here.


I had a .Jpg image that i had changed to .png without proper conversion. removing that file solved the problem. odd though..
I so really wanted to do this thing but Android Studio is notorious on its build. Mine will take more than 30 minutes if I did this.
perfect solution!!
Had to do this twice
sometimes it's because of your XML file mistake. <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity"> Check these lines in xml files and correct it.
B
BlackHatSamurai

I found that this issue was caused because I had errors in my XML files. Once you fix the XML errors, do a clean/build, it fixed the issue.


Just helping whoever's reading. It is likely something in the XML files that is causing the error. For me, (not sure why) but it was caused by a fragment layout line: android:layout_bottom="@id/my_list" Simply switching from this line from one fragment to use layout_top on another fragment.
Same thing for me! Thanks for the help
Same here! Thank you.
Great answer! Thanks
Yes, in my case: my xml element height was '50' instead of '50dp'.
N
Nathaniel Ford

Click on Build -> Rebuild Project and then click Tools -> Android -> Sync Project with Gradle Files.


This works. I have encountered the error after upgrading gradle version.
My situation was: every clean made all R become errors, every build fixed it, but of course 'uncleans' the project. After following this answer I could finally clean the project without getting errors.
Just adding to @user2284700 's answer : In AS 3.1.3 "Sync Project with Gradle Files" is under "File" menu
c
craned

Make sure in your AndroidManifest.xml the package name is correct. That fixed the problem for me when my R.whatever was marked red!

I would also recommend checking all your gradle files to make sure those package names are correct. That shouldn't make everything red, but it will stop your gradle files from syncing properly.


Thanks! I was making a small experiment with package rename for forgott about it...
T
TedVN

DO NOTHING. Just Update Android Studio. Resolve my problem! Work perfectly.


I tried all the solutions mentioned here. Updating the android studio fixed the issue
Thanks for saving me from wasting more hours on this
S
Shashank Bhong

I had similar issue with 'com.android.tools.build:gradle:3.3.1', I tried all above solutions nothing worked. It was actually build:gradle 3.3.1 issue. I changed it to 3.2.1 then it worked.

So it can be issue with build:gradle version.


03.2019 This helped. What was interesting is that this happened on only one of my projects and on other two projects did not. Now i hope that Android Studio update didn't mess up something else...
r
reece

Select the File > Project Structure menu option. Press OK on the message box (Project Structure changes don't update build.gradle). Select "Modules" on the "Project Settings" side pane. For each module (project), check that the "Excluded Folders" section does not contain the "build" folder. If they do, press the 'x' button next to the "build" folder. Press OK

You should now see the "MyAppProject/MyApp/build/source" folder. This should contain the "r" folder (where the R.java file is generated). Here, you should either see "debug", "release" in blue (if you have a projectFlavour in your build.gradle, these will be under the "" folder). Within that debug/release folder should be your app's package name and then an R.java file that contains all your resource ids.


This is not relevant any more, but note that I did not have an R.java file in that folder, as you can see in my reply to Loïc.
N
Nathaniel Ford

Rebuild the project. If (1) does not work, restart the Android Studio/Eclipse.

If neither works, check all your xml files. This error occurs when your xml file is incorrect.


In my case, there was an attribute in the manifest.xml file that caused the problem. I had sleepless nights until I discovered at and simply deleted the line. The attribute was android:fullBackupContent=""
C
Community

For some reasons, Android studio use different configs for the editor and for the compiler. If it works for the compiler then it's good. If it doesn't work for the editor. (it sees unresolved files).

You need to add some directories to the source of your project. For example all resources should be marked as "source".

File->Project Structure

Select "Modules", then your project. And select the sources tab. On the right find your resources directory and click on the blue "source" button. Close all and it should work.

Also, you'll have to make sure that

build/source/r/debug is also a source. In I have all my build/source/*/debug marked as source.

main module .iml

<?xml version="1.0" encoding="UTF-8"?>
<module external.system.id="GRADLE" type="JAVA_MODULE" version="4">
  <component name="FacetManager">
    <facet type="android" name="Android">
      <configuration>
        <option name="SELECTED_BUILD_VARIANT" value="debug" />
        <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />
        <option name="ALLOW_USER_CONFIGURATION" value="false" />
        <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
        <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
        <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
      </configuration>
    </facet>
    <facet type="android-gradle" name="Android-Gradle">
      <configuration>
        <option name="GRADLE_PROJECT_PATH" value=":SherlockHolmes" />
      </configuration>
    </facet>
  </component>
  <component name="NewModuleRootManager" inherit-compiler-output="true">
    <exclude-output />
    <content url="file://$MODULE_DIR$">
      <sourceFolder url="file://$MODULE_DIR$/build/source/r/debug" isTestSource="false" />
      <sourceFolder url="file://$MODULE_DIR$/build/source/aidl/debug" isTestSource="false" />
      <sourceFolder url="file://$MODULE_DIR$/build/source/rs/debug" isTestSource="false" />
      <sourceFolder url="file://$MODULE_DIR$/build/source/buildConfig/debug" isTestSource="false" />
      <sourceFolder url="file://$MODULE_DIR$/build/res/rs/debug" isTestSource="false" />
      <sourceFolder url="file://$MODULE_DIR$/build/source/r/test" isTestSource="true" />
      <sourceFolder url="file://$MODULE_DIR$/build/source/aidl/test" isTestSource="true" />
      <sourceFolder url="file://$MODULE_DIR$/build/source/rs/test" isTestSource="true" />
      <sourceFolder url="file://$MODULE_DIR$/build/source/buildConfig/test" isTestSource="true" />
      <sourceFolder url="file://$MODULE_DIR$/build/res/rs/test" isTestSource="true" />
      <sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />
      <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" isTestSource="false" />
      <sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />
      <sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />
      <sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />
      <sourceFolder url="file://$MODULE_DIR$/src/debug/res" isTestSource="false" />
      <sourceFolder url="file://$MODULE_DIR$/src/debug/resources" isTestSource="false" />
      <sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />
      <sourceFolder url="file://$MODULE_DIR$/src/main/assets" isTestSource="false" />
      <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
      <sourceFolder url="file://$MODULE_DIR$/src/main/jni" isTestSource="false" />
      <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />
      <sourceFolder url="file://$MODULE_DIR$/src/main/res" isTestSource="false" />
      <sourceFolder url="file://$MODULE_DIR$/src/main/resources" isTestSource="false" />
      <sourceFolder url="file://$MODULE_DIR$/src/instrumentTest/aidl" isTestSource="true" />
      <sourceFolder url="file://$MODULE_DIR$/src/instrumentTest/assets" isTestSource="true" />
      <sourceFolder url="file://$MODULE_DIR$/src/instrumentTest/java" isTestSource="true" />
      <sourceFolder url="file://$MODULE_DIR$/src/instrumentTest/jni" isTestSource="true" />
      <sourceFolder url="file://$MODULE_DIR$/src/instrumentTest/rs" isTestSource="true" />
      <sourceFolder url="file://$MODULE_DIR$/src/instrumentTest/res" isTestSource="true" />
      <sourceFolder url="file://$MODULE_DIR$/src/instrumentTest/resources" isTestSource="true" />
      <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/exploded-bundles" />
      <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/symbols" />
      <excludeFolder url="file://$MODULE_DIR$/build/tmp" />
    </content>
    <orderEntry type="jdk" jdkName="Android 4.2.2" jdkType="Android SDK" />
    <orderEntry type="sourceFolder" forTests="false" />
    <orderEntry type="library" name="Sherlock.aar" level="project" />
    <orderEntry type="library" name="SlidingMenu.aar" level="project" />
    <orderEntry type="library" name="support-v4-13.0.0" level="project" />
  </component>
</module>

project iml

<?xml version="1.0" encoding="UTF-8"?>
<module external.system.id="GRADLE" type="JAVA_MODULE" version="4">
  <component name="FacetManager">
    <facet type="android-gradle" name="Android-Gradle">
      <configuration>
        <option name="GRADLE_PROJECT_PATH" value=":" />
      </configuration>
    </facet>
  </component>
  <component name="NewModuleRootManager" inherit-compiler-output="true">
    <exclude-output />
    <content url="file://$MODULE_DIR$">
      <excludeFolder url="file://$MODULE_DIR$/.gradle" />
      <excludeFolder url="file://$MODULE_DIR$/build" />
    </content>
    <orderEntry type="inheritedJdk" />
    <orderEntry type="sourceFolder" forTests="false" />
  </component>
</module>

Black magic

Not sure about this one, but I heard it working while I'm pretty sure it shouldn't change anything. Try compiling and saving the project after commenting all lines that requires R. Then when everything is not red. Try adding them back. The strange this is that your build/source doesn't get generated.

Also this question suggest checking "compiler use external build"

Android Studio don't generate R.java for my import project

Side note

Also make sure that in your java code there is no. import android.r; from what you shown, everything seems fine. Just strange that the build/source isn't being created. For example, I have no build/apk. May be you're in release mode and it doesn't create those directories.


Hi Loïc, I added a screenshot of the project structure to the question. As you can see, the entire res folder is marked as "source", and I don't have a build/source directory. Should I get it created? If so, how?
well the build/source directory should get created when building as far as I can say. Android studio being an "alpha" version. It comes with a lots of strange things. I have 1.7.0_21. One idea would be to do a build/rebuil project. If you can run gradle from command line it might throw some errors that aren't shown in the editor.
It doesn't get created, although the project compiles and runs successfully on the device.
The iml files look very similar to yours, with the same folders included and excluded. "file://$MODULE_DIR$/build/source/r/debug" is included even though it does not exist. Using an external build causes other problems (the project doesn't compile at all). How do I check if I'm in release mode?
I
Ilya Kogan

Here is my temporary solution until I find a better one:

Using Everything, find where R.java is created. In my case it was C:\Program Files (x86)\Android\android-studio\system\compiler\.cb969c52\.generated\aapt\.6badd9a4\production\com\\ In the Project view, click the module and press F4. Ignore the warning. Click "+ Add Content Root" and select the aforementioned folder. Make sure it's marked in blue (as a source).

After I did this, suddenly all the warnings are gone. The problem is that if you collaborate with other people, the folder name is different on each machine so be careful when synchronizing.


Have you tried with the latest 0.2.3 version of Android Studio? If you are still getting the issue, report this to code.google.com/p/android/issues so the Android Studio devs are aware of it and can investigate & fix the problem.
No, I gave up on Android Studio. I love the IDE, but there are still so many bugs that it's unsuitable for working in a team. We went back to Eclipse.
No problem. Because Android Studio is still in development, you need to be able to report any bugs that you find (so they can be fixed) and be tolerant of its rough edges. This is not for everyone.
P
Peter O.

This worked for me:

Close and reopen project Press " Sync Project with Gradle file " (is next to AVD manager icon in top menu) repeat 1-2 if Gradle could not Sync for first time. (mine worked in second time).

Worked with Android Studio 1.2.2


B
Bapusaheb Shinde

I resolved it 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.

One day for no apparent reason my app just breaks... errors everywhere... Thank you so much! This was very helpful!
Bless you, Invalidate caches was the only thing that helped
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/xqY8N.png


R
Rohit Sharma

Sometimes these build errors will continue out of nowhere. If this happens to you, try this:

Recheck the validity of the XML in your resource files: If your R.java file was not generated for the last build, you will see errors in your project wherever you reference a resource. This can be caused by a typo in one of your XML files. Layout XML is not always validated, so typos in these files may not be pointedly brought to your attention. Finding the typo and saving the file should cause R.java to regenerate.

Clean your project! Select Build → Clean Project This will rebuild the project from scratch, which may result in an error-free build.

Sync your project with Gradle! Select Tools → Android → Sync Project with Gradle Files Android Studio will rebuild the project from scratch with the correct project settings, which can help to resolve issues after changing your Gradle configuration.

Run Android Lint! Lint may give you good information regarding a problem. If the above does not work, this is where you will most likely find your problem. To run Lint, select Analyze → Inspect Code → select Whole project → OK Carefully analyze Lint suggestions; start with errors and then warnings.

Good luck.


In my case, there was an attribute in the manifest.xml file that caused the problem. I had sleepless nights until I discovered at and simply deleted the line. The attribute was android:fullBackupContent=""
u
user5194610

This error happens to me because there is an invalid input in my activity_main.xml file.

When you try to build or clean your project you will see error messages.

I resolved mine by reading those error messages, correct what is wrong in my xml file. then rebuild project.


M
Mazvél

I had this bug few days ago, I tried looking around until I decided to re-install Android Studio. It worked for me.


Re-installing didn't help :(
This is a very crude method.
i
iOSAndroidWindowsMobileAppsDev

When creating a project from a sample,while not importing the existing project is good (prevents clashes with gradle, .idea, .iml, build, jars and apks, i.e. all unnecessary build-generated files), after creating a new project, copying and pasting all relevant resources, I'd recommend :

checking packages and imports from packages within the project {AndroidManifest declaration and all imports in java classes}, all resources (drawable, mip-map, layouts and menus & your build.gradle (a sample of build.gradle to use with the latest sdk can be provided on request)) to see if they are there & if declared strings and ids actually exist and have been used, after which your only error should be the question asked:

Bulid->Clean Project

Tools->Android->Sync Project with Gradle Files

File->Invalidate Caches and Restart

In worst cases restarting your machine helps.

The above should work. Feel free to ask questions if necessary, i.e. post comments.


p
parvez rafi

this causes mainly because of errors in xml file, check your latest xml changes and rebuild it, same issue with me.


That helped, Thanks!
T
TheBrick

I had a copy/paste reuse error in the package declaration for the manifest

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="wrong.package.name">

the Main activity name had the correct path so the manifest didn't have any checked errors.

After resolving this, the source file still showed errors although build succeeded. I just ran app and then the source error indicators cleared up.


For me, there was an attribute in the manifest.xml file that caused the problem. I simply deleted the line. The attribute was android:fullBackupContent=""
k
kikoso

It has also worked for me by doing manually cleaning the folder .idea/libraries and clicking afterward on "Sync Project with Gradle Files" solves the problem. Apparently this Sync does not remove elements, but keep the old ones and add the current ones. Probably a bug to report :)


L
Lukas Hanacek

Had the same problem with android studio, I found out that build/generated/source/r contained only release folder and not debug. So for some reason debug build did not generate usable R class.

I solved it by opening the project iml file and fixed this line

<option name="RES_FOLDERS_RELATIVE_PATH" value="" />

to

<option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" />

resynced with gradle, commented out lines using R, run debug to generate the R, uncommented lines using R and run the debug again, fixed.


Where would I find the iml file?
same folder where your build.gradle is ... most likely
a
arghtype

The solution is simple:

Go to File > Project Structure > app and choose the Flavours tab, select API 21: Android 5.0 (Lollipop) in the drop down list for Min Sdk Version.


Thanks, this works! I had set the minSdkVersion value to a much lower one, and reverting fixed the issue for me.
M
Mauricio

In my case, I followed all answers I could find on Stackoverflow and none of them seemed to solve this problem. All the answers would point to a possible xml file corruption or conflict with Gradle names. Some answers claimed that it would be necessary to clean the project or Sync Project With Gradle files. none of these solutions would solve the problem. Also, once I was following a tutorial on how to build a Hello World app and I just followed the Android Studio wizard windows without any coding at all, it wouldn't make any sense to suspect it was a typo ar anything like this.

TLDR

The problem turned out to be the Build Tools Version. My was set to 23.0.0 rc1, so I changed it to 22.0.1. I suppose it was because I'm using the last available release of Android Available.

To change this value you can open your Project browser on the left window > right click "app > Open Module Setting" and look for it on the "Properties Tab"


T
Thiago

you need to IMPORT your project R file

import <YOUR-PROJECT-PACKGENAME>.R;

E
Ezio

Cleaning the Project helped in my case

Go to

Build -> Clean Project

N
Nathaniel Ford

If you are getting this error, then clean your project.

Go to build on top of your android studio Choose the option clean project

The reason behind this is that by cleaning your previous .apk file that is present in your android studio project folder on your system is deleted.


Y
Yu Zhang

Recently I import my project into Android studio, a part of R are marked in red with the error meesage "cannot resolve symbol R",but the compilation succeeds and the application runs.

Develop evirment:

IDE: Android studio 3.1.2

System: Mac Os

Solution:

step1:

Find the configuration file for Android studio My path:

/Applications/Android Studio.app/Contents/bin/idea.properties

step2:

Change 2500:

idea.max.intellisense.filesize=2500  

to 5000 or more:

idea.max.intellisense.filesize=5000  

how did you think of that? what does it mean?
# Maximum file size (kilobytes) IDE should provide code assistance for. # The larger file is the slower its editor works and higher overall system memory requirements are # if code assistance is enabled. Remove this property or set to very large number if you need # code assistance for any files available regardless their size. idea.max.intellisense.filesize=2500
R
Ray

I ran into the same error, turns out that the manifest file had some errors. After fixing it, clicked Make Project again, it worked fine. Android studio sometimes do not give very helpful error messages.


ǝ
ǝɲǝɲbρɯͽ

I get bitten by this every now and then and there's another thing to try: match your compileSdk and buildSdk versions to the latest available.

I had changed my compileSdkVersion from 21 back to 19 because the Android Studio (1.1 canary channel) debugger was not tracing properly into prebuilt libraries. I found that it seemed to be tracing based on the buildToolsVersion (19.1.0), which I verified by clicking an error in the stack trace (and then choosing 19 instead of 21). Though I changed it directly in the build.gradle file, a graphical walkthrough is here: https://www.blogger.com/comment.g?blogID=4722727826918942842&postID=3875998513888772255 and I'll summarize:

Android Studio IDE, select File | Project Structure. Choose your module, like "app" In Compile SDK field, choose the latest version Also choose the latest version in Build Tools

Confirm, and the project should automatically sync properly.

The lesson I'm getting from this is that they should both be the same.


r
razz

For me I had this problem after I changed the name of one of my raw resources from extra to extra.jet, then all Rs became red and it wouldn't build. I tried all the above solutions and nothing worked, then i tried to make another copy of it with the original name extra and deleted it from within android studio then Rs returned back to normal and build succeeded.