152
votes

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:

Android Studio Screenshot

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:

enter image description here

Any idea how to fix this?

30
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'.Snappy Cracker
Readers, before you try anything else which might be complex... just give a try to restarting android studio.eRaisedToX

30 Answers

111
votes

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

63
votes

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.

44
votes

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

36
votes

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.

17
votes

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

12
votes

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.

9
votes
  1. Select the File > Project Structure menu option.
  2. Press OK on the message box (Project Structure changes don't update build.gradle).
  3. Select "Modules" on the "Project Settings" side pane.
  4. 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.
  5. 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.

9
votes
  1. Rebuild the project.
  2. 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.

6
votes

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.

5
votes

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

  1. Using Everything, find where R.java is created. In my case it was C:\Program Files (x86)\Android\android-studio\system\compiler\<project-name>.cb969c52\.generated\aapt\<module-name>.6badd9a4\production\com\<project-name>\<module-name>

  2. In the Project view, click the module and press F4. Ignore the warning.

  3. 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.

5
votes

This worked for me:

  1. Close and reopen project

  2. 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

5
votes

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.
4
votes

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

enter image description here

4
votes

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.

3
votes

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.

2
votes

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

2
votes

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.

2
votes

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

2
votes

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.

1
votes

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 :)

1
votes

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.

1
votes

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.

1
votes

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"

1
votes

you need to IMPORT your project R file

import <YOUR-PROJECT-PACKGENAME>.R;
1
votes

Cleaning the Project helped in my case

Go to

Build -> Clean Project
1
votes

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

  1. Go to build on top of your android studio
  2. 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.

1
votes

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  
1
votes

You have to change the path:

for example

import it.example.project.myproject.R;

change in

import it.example.project.R;

0
votes

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.

0
votes

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:

  1. Android Studio IDE, select File | Project Structure.
  2. Choose your module, like "app"
  3. In Compile SDK field, choose the latest version
  4. 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.