[android] "cannot resolve symbol R" in Android Studio

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.

This question is related to android android-studio r.java-file

The answer is


In my case the code was working properly before I updated android studio. After update R file was not generated. I was working on a custom view and had an attribute

<attr name="showText" format="boolean" />

in my declare stylable. This same attribute was also used by by the System's ui:

<style name="Base.Widget.AppCompat.CompoundButton.Switch" parent="android:Widget.CompoundButton">
    <item name="track">@drawable/abc_switch_track_mtrl_alpha</item>
    <item name="android:thumb">@drawable/abc_switch_thumb_material</item>
    <item name="switchTextAppearance">@style/TextAppearance.AppCompat.Widget.Switch</item>
    <item name="android:background">?attr/selectableItemBackgroundBorderless</item>
    <item name="showText">false</item>// this line
</style>

I renamed the previous showText to showTextFormat then gradle sync which regenerated the R.java file.


I am facing an error 'Unable to resolve symbol R' the R appears in java file in red. I've solved it.

  1. Do not save any image with Capital letters like ABC.png. First delete the image or rename it.
  2. Clean project
  3. Rebuild Project

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


First solution

Rebuild your gradle or invalidate/restart your system.

Second solution

delete .gradle and .idea folder from your android project. So you can solve "R" problem

and also remove redline error occur without any reason you get.


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.


In my case, I was trying to clean and rebuild the project. The issue was not fixed because there existed an error in layout file. To recreate, I have added a typo on an attribute in app namespace.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/add_user"
        android:icon="@android:drawable/ic_menu_add"
        android:title="Add User"
        app:showAsActioin="always"
        />
</menu>

Android Studio was not inspecting attributes of the app namespace, It seems file is error free. Now while building the project, It says Cannot resolve symbol 'R'. The errors are shown in the build log.

Cannot resolve symbol 'R' - Android Studio

Fixing the typo fixes it, Watch on Android issues section on build log.


In my case I needed to fix some errors in my layout XML files. There was no icon which indicated that the files contained errors. However, when I clicked them I notices a few red lines. After fixing them, R was found.


In my case, after having the same error (Cannot resolve symbol R) with android studio version 0.8.9, what I did was go to File->Project structure and changed the JDK location to oracle JDK which I manually installed. So in my case in linux instead of /usr/lib/jvm/java-7-oracle which was the preset one. I changed it to /home/phvz/App/jdk1.8.0_20 saved the settings and the R symbol issue was fixed immediately


I had the unresolved R problem because of the same image.png file in two places. One in res>anim and the same file in res>drawable-hdpi. This caused R to become unresolved. I created the problem by making a splash screen image and repeatedly moving it from the Moray graphics directory to the Android project directly. I must have dropped it into res>anim folder by accident. I fixed the problem by removing the duplicate image file from the res>anim folder and Android studio corrected itself.


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.


I have had this with

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

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!


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

  1. Set the proper package folder structure of <manifest> in AndroidManifest.xml.
  2. Set the new package location for android:name of <activity> in AndroidManifest.xml.
  3. Clear cache by

File Menu -> Invalidate Caches / Restart ...

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


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 was facing this problem when I imported google-services.json file to implement Analytics. I already had global_tracker.xml file in the xml folder. During build, while merging contents from google-services.json file, the error was started occurring.

The error is resolved after removing the goolgle-services.json file.


Take into account the following IDE functionalities:

  • Sync Project with gradle files
  • Build -> Clean Project
  • Build -> Rebuild Project
  • File -> Invalidate caches

My simple solution is:

  1. Check that there is no error line in the dependencies of the build.gradle of the app or in all the resource files in the /res directory; where some common errors are when the attribute values are left without references when using:
    • "@string/.."
    • "@style/.."
  2. Make sure you are not getting an error of the type Android resource linking failed when the project is rebuilt.
  3. Open the file that contains the line with the error Cannot resolve symbol 'R'
  4. Scrolling to the last line of the class with said error line
  5. Click on a position to the right of the closing key } of the class

In this way, the IDE alert dialog appears to perform the import of the R-class.

GL


Just clean your project and Sync Project with Gradle File.enter image description here

And the problem will be resolved.


Dudes, I think there are a lot of shots in the dark here. In some cases Clean and Sync Project will help only after you fixed the problem.

Step1: So go and look at the top of each file where the package is specified as follows pakage="YourURL.YourProject"; and insure that the correct package (Your Own Project) is specified. You will find this in java files and AndroidManifest.xml and it is critical for the java files to reference the correct package, as that package contains the resources ("R") you are pointing to. Should they not match up the error cannot resolve Symbol R occurs.

Step2: Clean, Sync, whatever. Done

So why does this occur randomly or what did I do wrong??

If you copy and paste code, you should pay close attention to the "package=" as explained above. More importantly, when you paste code, it immediately runs through a sort of debugger (Excuse my bad tech term) to show you "presumed errors", which immediately takes in consideration the "Wrong Package", and you get all the errors. Therefore, even though you immediately corrected the notation after pasting, the debugger has already refreshed. Which is why "Clean, Sync, Whatever" works SOMETIMES


There are many causes for this error.

  1. Sometimes it occurs for replacing an image file keeping same name.
  2. Suppose you deleted an item from your layout .xml say a <Button/> but it is still declared in any Activity or Fragment .java.
  3. Many more.

Best way to track the error is Rebuild it rather clean or sync doing some intentional error.

If it doesn't solve your problem then there must have to be some flaw or runtime error or error occurred due to improper use of resources in may be both java or xml file in your code or design which is forcing gradle to stop because (R)esource file can't index your resources properly and you have to admit that.

If your project ran before you made the changes then comment out the changes you have made and try to rebuild the project.

It will surely work since there will be no changes.

To track down the exact error, check the changes by breaking the changes into smaller module.

For example - If you are making a list visible with a button click and inserting list values in the adapter, first check if you are able to make it visible or not then check for adapter errors.


Try to ensure that the full package name is on the first line. Say you have a file named LoginActivity.java and the package called com.domainname.project.

The first line for LoginActivity.java should be

package com.domainname.project;

This is the equivalent of specifying "namespace" in dot.net. Also ensure the package matches the package within which your *.java file is contained.


Nothing worked for me , then I need to update my android studio to make it working. After updating android studio to the latest version the issue is resolved.


I'm working on a multi-module projects. And this happened to me when I moved all of the ui code to a new module.

Here is how I solve the problem: I find out that when I create the new ui module, in the /res/values, it creates a new strings.xml with nothing useful in it. I delete that strings.xml file, rebuild the project, and it works.


One more thing to try...

  1. Delete the Build folder
  2. Rebuild the project by syncing gradle

I had already tried many of the other suggestions here, like

  • cleaning the project,
  • restarting Android Studio,
  • fixing errors in my xml,
  • syncing project with Gradle files, and
  • updating the build tools version,

but none of these worked.

I finally just manually deleted the whole build folder (after backing up my project) and then restarted Android Studio. After that I made a minor edit (added and deleted a space) in my app build.gradle file and then clicked sync. (I probably could have just done Tools > Android > Sync Project with Gradle Files from the menu.) After that it worked. Something had gotten corrupted in the build folder and starting over with a fresh build fixed it.

I don't know if anyone reads this far down the list of solutions, but I'll add this answer anyway.


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


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.


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.


This happened to me fairly recently when I updated much of a project's libraries. R was not found, but I could build and run the project just fine. It wasn't crashing. The IDE simply showed red everywhere.

I tried to

  • Check for damaged/improper XMLs and images, none found
  • Check for invalid resource file names (e.g. capitalized), none found
  • Downgrade some libraries because maybe it was a resource conflict, not resolved
  • Lowered compileSdkVersion and targetSdkVersion because, in the past, I encountered resource issues due to this. In this project however, that was not the case.
  • Clean, didn't help
  • Rebuild project, didn't help
  • Invalidate caches/Restart multiple times, didn't help
  • Adjusted idea.max.intellisense.filesize to a very high value, didn't help
  • Did a Lint run, no errors found

In the end, I found that downgrading my Gradle build tools (from 3.3.1 to 3.2.1) solved the problem. That was the only change I had to do. The rest, updated. Now, all my libraries are updated without issues.

buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        //classpath 'com.android.tools.build:gradle:3.3.1'
        classpath 'com.android.tools.build:gradle:3.2.1'
        classpath 'com.google.gms:google-services:4.2.0'

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

In an Instant App activity of a non-base feature you can call R.id.fromFeatureOne and R.is.fromFeatureTwo. So items from different resources are referred as of a single resource origin.

Both will be highlighted as acceptable and you can even jump to source. But build will result in an error: "cannot find symbol R.id" which is quite tricky to find the reason, as nothing is highlighted.

The solution is to call com.example.feature.one.R.is.fromFeatureOne and com.example.feature.two.R.is.fromFeatureTwo.

Also issued a bug at Google: https://issuetracker.google.com/u/0/issues/77537714


In my case, it was solved by updating Android Studio from 3.1 to 3.3

To update your Android Studio: File -> Settings -> System Settings -> Updates and then click on check now.

enter image description here


This notation seems to work fine.

android:id="@+id/viewID"

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


Apparently in my case the problem was resolved by adding an "*" at the end

import android.R.*;

After I do "Build->clean project" and "Sync project with gradle". Both them are not resolve. I down build gradle version from 3.3.0 => 3.2.1 (revert as project init state) and it resolve my problem.


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.


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


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.

enter image description here


Just import the R symbol from the root package

import rootpackage.R;

No rebuild, sync or another things...


most of times, this issue is caused by the xml files, take a look at the xml files, looking for any errors.


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

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.

Inspection

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)


It's simple "Sync project with Gradle"


In the project gradle(i.e)build.gradle just update the com.android.tools.build:gradle as

dependencies {

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

}


Build -> clean project or Rebuild project or File -> Invalidate Caches / Restart... -> Invalidate and Restart


In my case, importing the aplication domain name followed by ".R" solved the issue. Example:

import com.example.myapp.R;

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

enter image description here


I had android:textAllCaps = "false" in the androidmanifest which was creating havoc to the R file. I deleted it and all is fine. I think the target sdk was not set high enough.


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;

This problem is caused because of the naming of files in "res" or "drawable" folder. You can't use any capital letter for naming a resource file. So, check if there is any such file and rename it with small letters.

And, also, you can try this: Go to: File > Invalidate cache/restart

These options have worked for me.


I had similar problem currently. The problem was that in my project I had more modules. E.g. app module and library module. Although both, the class and the R.string resource was from the app module I somehow had import com.package.library.R in there. Somehow Android Studio did not recognize this as an error and Gradle/Sync build my project without problems. But when I tried to run Unit Tests Gradle build failed with the described error.

package com.package.app

import com.package.library.R;
//...

class SomeClass {
  //...
  public void someMethod() {
     Toast.make(context, R.string.message, TOAST_LONG).show();
  }
}

When the R.string.messsage resource is actually in my com.packagename.app module and not com.packagename.library module. Removing the import ... solved my problem.


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


IN my case the reason was having some images in res folder with name contain a capital letter..

just rename it with small letter and rebuild


This is caused of recently deleted xmls In Android Studio Clean your project from these xmls by choosing: build -> clean project


Note : This might help you only if your project is very large

TL;DR - The generated R file exceeded 2.56 MB and Android Studio was not indexing it, you can follow the solution for that here :

File size exceeds configured limit (2560000), code insight features not available

Was facing a similar issue. But none of the answers here seemed to do the trick.

The R file was larger than 2.56 MB, on opening the generated R file, I got a message saying "Code insights may not be available"

Changing the default in idea.properties to allow for a larger file did the trick.

Apologies for formatting, on mobile.


I see this problem may cause a lot of things. In my case, I had some textView in one of the activities *.xml files. I put inside it text in the editor (to change it later via code) this way: "NAME: <here will be name>". Apparently, "<" and ">" chars broke importing R in my project from every place. I changed it and it started to work. I just forgot I can't use those characters in *.xml files, because they build its structure. It is worth having this in mind.


You can delete one of your layout files (does not matter which one), after that you need to build project. Project will build and after that you need to return your layout file by CTRL + Z. In my case, if I tried to build my project before deleting of layout file, it did not help me. But this way is ok.


In the new android studio 2.2. If your TargetSDK =< 15 then you also might find this issue. Change this in the gradle.build then follow the steps as per previous answers. Sync gradle files and rebuild. You can also invalidate caches and restart the studio that sometimes also helps.


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, Rebuild and "Cache Remove" won't help me, Updating Android Studio Fixed the issue.


I had the same problem. I tried most of what others have mentioned above i.e Gradle Sync, Validate cache and Restart, Clean and Rebuild project...restart android studio and still had the same problem...

The issue for me here, and I'm assuming others may have the same problem. I had space on the name of my newly created layout file...Instead of file_example.xml mine was file _example.xml **(Notice the space between file and _ )**when you try to find the reference to this layout file you will experience an error.

I suggest you look the most recent layout file that you just created, refactor the name slightly and then change your R.layout to the new file in your activity/fragment --> Then clean..rebuild the project, Project will compile without any errors. At least in my case, this was the solution to my problem.


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

Clean Project and Sync Project with Gradle ,

enter image description here

check buildTools version in my sdk enter image description here

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

enter image description here


I've got this problem especially when I accidentally corrupt a layout or a menu resource file. The scenario that I've hit cannot resolve symbol R is when I forget to add "@+id" that where I've to define an id in a menu item.

With a corrupted menu resource file, I get this error if I try to build the project with it. Because that R is a container class for resources, it seems gradle cannot bind R when it cannot parse resources, .xml files.

The solution is simply fixing the resource files, cleaning up the project and rebuild again.


I had my XML files in a LAYOUT folder instead of MENU folder.

This was as a result of moving to Android Studio from Eclipse.

Solution for me was simple ... move my XML files to the MENU folder and recompile.


Simply defining an app namespace in your xml file can cause this. This was a completely innocuous line that only selected out one symbol (out of many) to make unresolved. Simply removing the entire line, greyed in the pic below, enabled my code to reference to unresolved symbol. Even when I added the line back it decided to build without problem. Go figure.

enter image description here


I followed everything above and it didn't work. In my case I had to setup the JDK when I had every single Java Function in red for the Android-L preview...

On Mac:

  1. Click once on what is Red (or underlined) in your code (i.e. Activity, String).
  2. Click on the Red Light Bulb Point that appears on the left.
  3. Select "Setup JDK".
  4. Verify if annotations.jar and android.jar are in the current SDK version you are using (my case SDK 20 Android-L). You should also have the "res" folder, but I somehow still had it in the settings.
  5. If not, select the SDK and press "-".
  6. Then press "+" and locate the SDK folder on your computer (Mac: Applications > Android Studio.app > sdk).
  7. Select the version of the SDK you require (in my case 20 Android-L).
  8. Press Add.
  9. Build and Sync.

Then everything came back to normal for me.


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.


First check is there any error in any xml layout or not, if then resolve it first.

Otherwise remove junit dependency from project and rebuild the project.enter image description here


I found that in big projects, the autogenerated R.java is bigger than 2.55MB (the default limit by Intellij) this causes the file to be generated but not resolved. to solve it simply increase that limit:

  1. in Android Studio Help -> Edit Custom Properties...

enter image description here

  1. Accept and add this: idea.max.intellisense.filesize=3000 (3000 or any value greater than the R file size)

enter image description here

  1. finally, restart your Android Studio!

I added some images to drawable resourses, and one of my images was named as "super.jpg", which turn out to be a cause.

Renaming the image and after that syncronization the project with gradle files fixed the error.


You just have to check your Xml file. If there is an error then you can't resolve this error. Just solve error in xml then try.

OR

Clean Your Project from Build -> Clean


Make sure you have AndroidManifest.xml in the project.

It happened to me that I imported a project that didn't have the manifest yet so Android Studio wouldn't recognize it as an Android project. Then I pulled the project in GIT and it downloaded the manifest but still not working. Then I restarted Android Studio and it said something like "Framework detected android".

So make sure your project is configured as an Android project.


  1. Type 1 : close the Project and delete .gradle file in your project and then Rebuild the project
  2. Type 2: If type 1 does not works, then just take back up of of that project9Zip file) and then delete the project. Then extract the Zipped project and just import the extracted project, it will works perfectly, because it works for me.

In my case: res/someLayout.xml file goes some error then i resolve it. Then Clear the project. Error is gone.


i did make project and it works but before that try to check the package name in your manifest, rebuild and clean your project. if the problem didn't resolve, than make your project


I got this error after upgrading the gradle plugin from version 1.3.1 to

classpath group: 'com.android.tools.build', name: 'gradle', version: '2.2.1'

It forced me to change all references like

import [applicationId].R;

to

import [package].R;

And in my library project, appcontext.getPackageName(); stopped working correctly. I used it to get the correct app resources via reflection but after upgrading the gradle plugin it started to return the flavor-specific applicationId, instead of the package... you can read more about this here.


To Fix "can not resolve symbol r" error. Try these solutions.

  1. Build -> Clean Project.

  2. Build -> Build Project.

  3. Build -> Make Project.
  4. Third icon from left in Toolbar -> Sync project with gradle files.
  5. File -> Invalidate caches and restart.
  6. Make sure you are using compatible gradle version in application level gradle file.

e.g. : "classpath 'com.android.tools.build:gradle:X.X.X'".

I hope these solutions can help you.

Thanks for reading.


None of the above answers fixed my problem. So I added my solution just in case someone run into similar issue. In my build.gradle dependencies I had,

compile 'com.android.support:appcompat-v7:22+'

and my compilesdk version was compileSdkVersion 21, so android studio wasn't happy. I simply updated my compilesdkversion to 23 and made sync.

I also updated the dependency as

compile 'com.android.support:appcompat-v7:23.1.1'

to match my support library in Tools--> Android--> SDK Manager --> SDK Tools tab --> Android Support Library --> version. Now everything is fine. Happy coding :)


For me it's important to say Android Studio in the begin will give trouble for learn, but like have here the solution Clean Project can fix this, always check the packed name and don't try to mess with the logic about, I Like the software but sometimes I try to think if the way is right or not, also I Like Linux but for me Android Studio to be rewrite all software maybe this will not happen. Anyway good luck!!!!


On OS X with Android Studio 0.2.13, I did "Jump to Declaration" on the com.< project >.R import in one of my activities. When I went back to the activity file all the warnings were gone.

Edit: You need to build the current build variant before this will work.


This was a big headache for me. In my case the error appeared after configuring "Google Play Services" in Android Studio (installing + build.gradle config). This in turn requires minsdk > 7 but the error is very unclear about it (actually a complaint about this only appears as "info"). Anyhow.. upon changing minsdk to 8 both in the manifest file and the build.gradle file and rebuilding the project, the error was gone.

So.. a general advice about this, if I may generalize - you probably have some problem in your manifest file, or some other configuration file, that is preventing a proper build. Try looking really hard at the error report, even the messages titled "info" for any hint about what it might be...


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.

Just like this: enter image description here

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.


You should do two things, first clean the project (in build menu):

Build -> Clean Project

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

File -> Sync project with Gradle files

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.

File -> invalidate caches


     The above answers are also the ways to fix the error but if does not work for anyone  then i have an option...

Just Close the project and nothing else and start it again so it will load References... Follow the ScreenShots.

enter image description here enter image description here


Check the Manifest file and make sure the package name is correct

package="com.packagename.your"

I think I have the ultimate solution. I did a research and found that Android Studio hates 'White Spaces' in installation paths or directories. It doesn't accept a SDK, placed at a directory that contains a white space. For example

C:\Program Files(x86)\Android\sdk

This directory is not valid as it contains a white space. Here, I have already answered a question where a guy was unable to change his JDK path in Android Studio because there was a white space in his SDK directory. This is weird, but it seems that Android Studio hates directories with white spaces. So the solution is -

Install the Android Studio as well as Android SDK in a directory or path where, there isn't any white space.

For example- Install Android Studio in

C:\AndroidStudio\

And install Android SDK in

C:\Sdk\

Both this directories are valid as there isn't any white space. Every path that doesn't contain white spaces is valid. It also resolves other problems like 'Failed to resolve: junit:junit:4.12' or 'Gradle sync project failed' etc.


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.


What worked for me was:

  1. Created a new project.

  2. Found that the R is wokring!

  3. Compared all the configurations.
  4. Found that difference in gradle file: compile 'com.android.support:appcompat-v7:23.4.0'

  5. Sync, and it worked again!


None of these worked for me on Ubuntu 12.04. I had to do the following:

sudo apt-get install lib32stdc++6
sudo apt-get install lib32z1

After that, I followed some other advice in this thread, did Build -> Clean Project and everything was fine.


change the latest sdk version,that was work for me

1.Click file and then click project structure 2.then select "app" then click ok,its worked for me. enter image description here


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.


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.


Have a look at the Gradle Console. In my case, I had included a resource with the wrong file extension.

AAPT: libpng error: Not a PNG file
:app:mergeDebugResources FAILED

FAILURE: Build failed with an exception.

After renaming the file and Sync Project with Gradle Files everything was fine.


If you have any error on .xml file no matter what you do you can not fix that issue. I would suggest that

-first, check your XML file to look for any error and

-second look for event log what Android studio caught the error and it will give you which file and where the error is.

That is how I fixed my R issue


None of the above answers helped me. I finally realized that the issue was that the "build" folder was missing from Android Studio. I found a number of lines in the projects "iml" file excluding "build/*". After removing those, the build file appeared and the errors disappeared.


  1. Check your xml files.
  2. 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.


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


//sometime due to incomplete sync it creates problem

//so just follow the steps and it will do your work for sure

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

For me, the issue was that I upgraded to a version of Gradle that seems to have some bugs. 3.4.0-alpha02 was what I updated to and found this to be the culprit of the "Cannot resolve symbol R" error. I reverted to 3.3.0-alpha10 (i.e. classpath 'com.android.tools.build:gradle:3.3.0-alpha10') and it solved the issue.

This obviously isn't a long-lasting solution as I'll need to upgrade sooner or later but as of Nov 3, 2018 3.4.0-alpha02 is the latest version and it hinders my development by not letting me hop around the IDE by clicking on R references.


See the below Image Goto File -> Project Setting -> Set All Setting like image and Sync it will put all latest setting in you project.This Image contain project settings. if your project imaported successfull then you have to do this. beacause it will import all update setting and gradle.


I also got this issue and I solved it in this way. First Go to Gradle and click clean. Secondly Click Build.

Make sure not to Clean from android studio


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

Examples related to r.java-file

"cannot resolve symbol R" in Android Studio No generated R.java file in my project Developing for Android in Eclipse: R.java not regenerating