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

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?

This question is related to android gradle android-studio

The answer is


The problem, like most people have submitted, is most likely from the .xml files. But it can be quite a chore locating it.

In my case, there was an attribute in the manifest.xml file that caused the problem. I had sleepless nights until I discovered it and simply deleted the line. The attribute was

android:fullBackupContent=""


  • Android studio-> Build -> Make Project Or Make Module 'xxx' fix the problem.
  • Yes, run app can not fix the problem...
  • Yes, clean can not fix the problem...
  • Yes, File -> Invalidate cache can not fix the problem...
  • by the way, should I use yes? or may be no is right in English?

You have to change the path:

for example

import it.example.project.myproject.R;

change in

import it.example.project.R;


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.


Already this has a lot of useful answers but here is something which might work, it did in my case:

Remove unnecessary imports from your class then Clean project or restart Studio.


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


The problem is that R is a pojo file generated when you build the project and it consist of references to resources in the res directory such as strings, drawable (icons or images) xml layouts etc. You may find it interesting to read the R.java file although you may have to exit android studio to do so. You may find it helpful to ignore this type of error because when you compile and build it will go away.

What not to do is import the R file


When I was beginner at Android studio ,this was general issue I face through . Generally the problem arises when the R.java files during conversion of hex code properly donot recognize the appropriate magic number . So we should kept in mind that all the XML files are properly wriiten.This is oftenly arises due to problem in XML files . Go in each XML files n be sure all the files are true means valid . Then go to File and synchronize the project .My error remove many times by such steps .


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.


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.


you need to IMPORT your project R file

import <YOUR-PROJECT-PACKGENAME>.R;

Try to first clean and rebuild the project using these command

1) Sync Project with Gradle files
2) Build -> Clean Project
3) Build -> Rebuild Project

before doing that check if any error in the XML file. If XML file contains any error its create problem to rebuild the project and affecting the

R


I had same problem while using exercise files from a training website and tried resolving the problem by uninstalling android studio and deleting all associated directories and reinstalling it but this yielded no result. However, I noticed that The tutorial i was viewing stored its exercise files on the DESKTOP while mine was in a folder in my DOWNLOADS directory so I Simply copied all exercise files to my Desktop; this made my exercise folder structure identical to that of the tutorial creator and this did the trick.


If other solutions does not working. Install new Android Studio version.


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  

I had the same problem when I added some image files in drawable folder, where the files name was in 'Uppercase'.I renamed them to normal format name and pressed rebuild project. It worked for me.


I had a similar issue for weeks but i had the design lib version with + in my build.gradle which made it download the latest version. So i set it to the version of the package and it worked.


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


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.

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.


Just add this sentence in your build.gradle:

compile 'com.android.support:design:23.1.1'

Many a times this usually happens when you have changed any of your layout files - where you might have included a new library component (happens generally during copy paste of code). Due to this copy-paste, you might tend to forget adding the dependency in the build.gradle file.

Hence, when you build/compile your project, Android Studio isn't able to understand that newly added component of the library (because the library hasn't become a part of the project yet).

Therefore, make sure you've added the new dependency in the build.gradle. Then do a gradle-sync.


In most cases, there is some problems with your resources, i.e. layouts, styles, etc. so try to find and fix the problem in your resources then clean your project.


  • In my case, it was gradle issue. I solved it by refreshing gradle :

  • Firstly, Click on gradle icon which right side on Android Studio

  • Then click on the refresh button


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.


The better way to resolve this problem is to restart your Android Studio. If you don't want to do a restart, then click on Build -> Clean Project.


I had this issue too. I deleted the extra images from my project's drawable folder.


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.


One thing which works for me every time is:

go to --> build.gradle (Module: app) file of your project --> do a little change (for example: put a space somewhere and remove it back) --> then android studio will ask you to sync your gradle file--> at top right corner of the file --> select "sync now".

After syncing completes, it'll resolve the issue in most of the cases.


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.


  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.


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.


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


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.


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


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

enter image description here


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


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.


Check the version of Gradle install in Android Studio and the one mentioned in Build.Grable file

`dependencies { classpath 'com.android.tools.build:gradle:3.1.1'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}`

I replace 3.1.1 to 3.0.0 and it worked for me, check your own version of Gradle. Or try to create new project and check its build.gradle file to know the installed version.


It's Very important to know that android studio has two type of import

  1. java import type
  2. android studio innere import type

and our problem with android import type as import android.R

it's work good? but you did't import android.R?

android studio add this automatic but with different syntax

to solve our problem

  • firstly you need to make a new project "Blank"
  • then copy all files from your first project to the new project except java files
  • then you need to make new java class with the same name

and Easily copy the all contents of you Activity java class

"Don't copy modules and package only copy the content of class"

and don't forget to add extends .... to your class

you will see message ask you to import some of modules

you must deselect android.R and press OK

it's will work correctly

" If you find android.R only at the dialog box you must click cancel"

//See Next Image

Select Class To Import if you don't know exactly where the java class file which cased this problem do this solution with all java file in your project

//Good Luck @ ABT


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.


Recheck the naming convention of the images and the validity of the XML in your resource files- then rebuild the project after cleaning.


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


This happened to me, i found it was caused by some cache files which were invalid. so i disabled cache by adding

android.enableBuildCache=false

to gradle properties.


Issue : Android Studio marks R in red with error message “cannot resolve symbol R”

Solution : I resolved the 'R' error by adding the following to the import & then rebuilding the project and the error went away.

import com.mkyong.android.R;

Explanation: Sometimes the Android Studio does not add the import even when you do build multiple times or run the 'optimize import' command. Sometimes the error is resolved when you 'restart Android Studio' but at times even after restarting Android Studio multiple times the error remains. Thanks.


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.


  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.


This problem occurs when you rename the package name. After renaming the package name, you must change the older package name to the newer one.

For me it solved the problem once I changed that.

After that, you might get errors in xml files, that you have to change the package name there also. That's it.


Cleaning the Project helped in my case

Go to

Build -> Clean Project

Just sync with gradle file.It works for me


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


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.


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.


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"


Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to gradle

Gradle - Move a folder from ABC to XYZ A failure occurred while executing com.android.build.gradle.internal.tasks Gradle: Could not determine java version from '11.0.2' Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0 Failed to resolve: com.android.support:appcompat-v7:28.0 Failed to resolve: com.google.firebase:firebase-core:16.0.1 com.google.android.gms:play-services-measurement-base is being requested by various other libraries java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0)

Examples related to android-studio

A failure occurred while executing com.android.build.gradle.internal.tasks "Failed to install the following Android SDK packages as some licences have not been accepted" error Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util This version of Android Studio cannot open this project, please retry with Android Studio 3.4 or newer WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()' Flutter plugin not installed error;. When running flutter doctor ADB.exe is obsolete and has serious performance problems Android design support library for API 28 (P) not working Flutter command not found How to find the path of Flutter SDK