783

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.

Tim
  • 41,901
  • 18
  • 127
  • 145
ez4nick
  • 9,756
  • 12
  • 37
  • 69
  • in the past I have gotten xml errors such as : progressbar cannot be cast to android.widget.textview, and i fixed that by just changing the name of the textview. I still really dont know what caused the error to begin with. – ez4nick Jun 11 '13 at 21:27
  • If u changed the name, perhaps you are now trying to use a string reference that does not exist in res/strings.xml? – Eyeball Jun 11 '13 at 21:32
  • i meant the id of the textview was what i changed. i did have to completely make a new xml file from a previous one that had too many errors to deal with – ez4nick Jun 11 '13 at 21:35
  • 3
    i searched many times before asking this question and found many similar questions including the one you mentioned. i did read the suggestion in that question and there is no import Android.R in any of my java files. – ez4nick Jun 11 '13 at 21:50
  • Your issue is unlikely not to be caused by one of the reasons discussed in that question. If it is, you are welcome to file a bug on this pre-release software. – Simon Jun 11 '13 at 21:53
  • i suspect the issue must be in an xml file but i really dont know where. i will spend more time looking into this. – ez4nick Jun 11 '13 at 22:04
  • @Simon the link pointed by you is for Eclipse and this question is on Android Studio – dhaval Jun 12 '13 at 12:04
  • I think I have figured out the issue. The issue is with Android Studio, every time I added the admob library all these errors started. All my other projects without ads don't have similar issues. I'm now using Intelij and staying away from Android Studio – ez4nick Jul 03 '13 at 20:20
  • 2
    Hey everyone I forgot about asking this question since it was asked so long ago. I should have accepted my own answer a year ago that is now the comment above this. The issue was with simply that android studio was in such an early stage at the time and as a new developer I never should have never been using it. Rest assured everything is working fine now and has been. If it is possible please undelete my original answer so I can accept it. – ez4nick Nov 21 '14 at 03:26
  • I haven't seen this solution yet it worked for me: When rebuilding, check the build error messages. I was trying to use Android Wear which required minSDK >=9, not 8 – Script Kitty Jul 04 '16 at 19:16
  • This happened to me today, make sure that you have `R` instead of `r` – Kamin Pallaghy Jul 21 '16 at 01:04
  • 3
    Not finding R isnt your error its an error caused by a Build fault Fix your other errors and you should be fine. – Just_someone Sep 26 '16 at 11:26
  • Sometimes even the easy looking "restart" option helps . Give restart a try first. – eRaisedToX May 30 '17 at 05:33
  • Check in your app's `build.gradle` file that the `applicationId` matches your app. – Protean Apr 11 '18 at 22:59
  • Sometime you get this error BUT due to missing values in your xml files such as: In my /src/main/res/xml/preferences.xml file I referenced a value (android:entries="@array/updateInterval") but I do not have inf file /src/main/res/values/arrays.xml () that will cause R.xml.preferences error! – Dung Aug 24 '18 at 21:31
  • Check your imports for invalid paths. Have you changed a package name? If you have modules, check their imports and paths. If you see the same error check package names in your manifests (project and modules), are they correct? Finally run clear, and rebuild. – i_tanova Sep 14 '18 at 10:16
  • you can check once here :- https://stackoverflow.com/questions/52895833/cannot-resolve-symbol-r-and-nothing-is-working/52899539#52899539 – Rocky Apr 26 '19 at 14:21
  • 1
    happenned to me after pasting code from someone else in my manifest lol – agenis Jan 23 '20 at 10:24

101 Answers101

737

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

tokhi
  • 21,044
  • 23
  • 95
  • 105
Vipassana Vijayarangan
  • 8,799
  • 2
  • 17
  • 20
  • 59
    some times you also need to restart android studio. or at least for me. – Foo Bar User Feb 12 '14 at 00:47
  • 1
    can you specify where this option is? – user1532587 Feb 25 '14 at 01:49
  • 24
    For those who convulse over using the command line, click on Build->Clean Project and that will perform a 'gradlew clean'. ;) – Mr. Concolato Mar 31 '14 at 19:44
  • using the command line I received another clue that I can add to my cluebook `export JAVA_HOME is set to an invalid directory: /Library/Java/JavaVirtualMachines/jdk1.8.0_05.jdk/Contents/Home` – Someone Somewhere Dec 18 '14 at 22:57
  • 26
    No luck...The cleaning rebuilding doesn't working fr me – CandleCoder Jan 07 '16 at 01:37
  • 1
    Sometimes just cleaning won't work. You have to take a look at the console to see if any errors popped after the "Clean project" finishes. In my case, there was an invalid character in the strings.xml and that was causing the "R" problem. – CJ_COIMBRA Dec 20 '16 at 23:22
  • sometimes you need to `Build→Rebuild Project` and the `R` problem solved ;-) – Amir Sasani Jan 05 '17 at 17:15
  • 8
    if clean,rebuild,invalidate caches-restart doesn't solve go for: import package.R; – Sudip Bhandari Jan 16 '17 at 15:08
  • This worked for me cheers, I looked in the import and my Import.R was frayed out as unused. a clean sorted it out. – Tony Merritt May 05 '17 at 14:35
  • all the answers here never worked for me. Finally i found the solution i simply import the R into my project **import .R** – Thecarisma Jul 16 '17 at 13:08
  • just invalidate cache and restart android studio -> then when it's already open again, build -> clean project. – nsaudria Dec 13 '17 at 06:50
  • 6
    For me this was causing the problem: Mismatch among ApplicationId in gradle and package name in manifest (and though the auto import added the wrong address for the R file). I recommend this little article to make clarification of difference between the two. blog.stylingandroid.com/package-name-vs-application-id – Fatima Feb 10 '18 at 13:11
  • if i clean the Project then give me this error **Error:null value in entry: blameLogFolder=null** – Ali Jun 18 '18 at 11:34
  • Voted up @FooBarUser but no need to restart the android studio process, only restarted the instance which had this project loaded and it worked – shabby Nov 28 '18 at 06:57
  • One of my XML file had incomplete attribute. That was causing problem. – Tayyab Mazhar Jan 19 '19 at 07:42
  • Clean Project did not worked for me but "File->invalidate cache and restart" does work for me. – ZIA ANSARI Feb 18 '19 at 10:05
  • I had pasted some sample code and the following "import android.R.layout" at the top of the MainActivity.kt (Kotlin language file) stoped R from working proerly. R could not resolve setContentView(R.layout.activity_main) A horrible error making the learning curve point downwards. – flodis Jun 17 '19 at 09:34
  • @FooBarUser Yes RESTART! – linjiejun Jul 25 '19 at 07:38
  • I can't find `Build->Clean` :( – Moeez Oct 22 '20 at 04:46
  • if all the instructions are not working, you can upgrade your gradle plugin. You will see a notification riht bottom part of the android studio. Ex: (just update it)Project update recommended: – paul polash Dec 18 '22 at 09:42
236

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

Om Sao
  • 7,064
  • 2
  • 47
  • 61
Tom C.
  • 2,403
  • 1
  • 11
  • 4
162

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.

Tushar Monirul
  • 4,944
  • 9
  • 39
  • 49
  • 11
    Yet another amazing feat by Android studio developers. Reverting back to `3.2.1` was actually the only solution that has worked for me... – Vucko Feb 12 '19 at 13:32
  • 1
    Astonishingly still an issue 2 months later. Latest version (3.3.2) didn't fix it, 3.2.1 did. – Jake Lee Mar 24 '19 at 21:20
  • Instead of moving back to gradle `3.2.1` you can also upgrade Android Studio to version `3.3`. See my answer [here](https://stackoverflow.com/a/55533987/4118280) – arne.z Apr 05 '19 at 11:10
  • it worked by changing 3.3.0 to 3.2.1 but my question it was working fine on 3.3.0 i had just refactor and updated manifest xml file and gradle file and had sync the gradle . May i know what might be the reason – insoftservice Apr 08 '19 at 10:25
  • 25 hours of internet and looks like this is the only working solution. Thanks android studio :(.... – Nahabwe Edwin May 01 '19 at 09:34
  • Thanks. I'm also facing this problem. But now it was solved. – P113305A009D8M Jun 21 '19 at 01:50
  • I got notification to update Android Gradle Plugin, So I did .. then I found some layout file couldn't be accessed by `R.layout.`, and I tried to downgrade mine following this solution, from **3.6.0** to **3.5.3** and Yeah, it works. – Ahmed Shendy Feb 28 '20 at 01:36
112

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

Mina Fawzy
  • 20,852
  • 17
  • 133
  • 156
59
  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.

Yuriy Vasylenko
  • 3,031
  • 25
  • 25
  • A missing image one of my XMLs referred to caused this issue for me. Put the image in the folder, cleaned and R is now happy again. – Casey Murray Sep 11 '15 at 05:48
  • I accidentally had my string defined twice in strings.xml. Studio didn't show that at all. X-( Thank you for your answer. – codingjeremy Sep 16 '15 at 17:38
  • 7
    Why is there no feedback to underline bad XML files in the IDE? – Fuhrmanator Sep 21 '18 at 19:46
  • When something like you mentioned occurs, the issue gets highlighted in the xml. I've tried everything I could find in the internet, but nothing solves my problem, although the app runs normally. – Aliton Oliveira Nov 26 '19 at 23:06
56

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.

serv-inc
  • 35,772
  • 9
  • 166
  • 188
SMBiggs
  • 11,034
  • 6
  • 68
  • 83
  • Did not help. Tried cleaning/rebuilding too. Error occured after I moved java package into another package. Interestingly, in one package R class can be accessed, but it cannot be accessed in package that I moved. – rint Nov 05 '16 at 12:02
  • In the more recent versions of Android Studio, Invalidate and Restart are now the default menu selection. This should help at least a few people. (Too bad they don't fix all the crazy bugs that cause this error in the first place!) – SMBiggs May 24 '17 at 04:05
  • 2
    I got this error after moving and renaming a project. This solved the R problem after all cleaning and restarting did not. Thank you. – FrankKrumnow Jul 25 '17 at 09:32
  • 1
    This is definitely the right answer if you have first tried 1.)Clean & Rebuild 2.)Ensuring your xml files are valid – Machine Tribe Aug 01 '19 at 13:26
50

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;
M.A.K. Ripon
  • 2,070
  • 3
  • 29
  • 47
ninjahoahong
  • 2,624
  • 22
  • 20
  • 1
    Ah, and there will be still error message before you first build. However, you just press build, Android Studio will generate the R file and the build should success. – ninjahoahong Mar 12 '14 at 07:44
  • and I think it's better that after the fix, you should clean your project and then build. or press Shift + F9 for debug with your device or emulator. I prefer to debug on real device. – ninjahoahong Mar 12 '14 at 08:03
29

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.

Mr Robot
  • 1,747
  • 6
  • 35
  • 67
chawkinsuf
  • 1,381
  • 1
  • 12
  • 13
  • thanks worked for me too. Small question - where should i type gradlew clean if i want to do it this way (i did "Tools" -> "Android" -> "Sync Project with Gradle Files")? – Sergii Sep 02 '14 at 12:19
  • Open a command terminal, switch to the project directory and execute "./gradlew clean" – chawkinsuf Sep 15 '14 at 19:36
  • How does this solve the problem better than 'Rebuild Project'? – IgorGanapolsky Mar 04 '15 at 02:35
  • Yes, in my case I added a png file, called "import.png". I had to rename it, in my case "import_icon.png" and then the project compiled ok. – mihai71 May 11 '16 at 14:10
24

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

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

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

A P
  • 2,131
  • 2
  • 24
  • 36
17

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

Zoe
  • 27,060
  • 21
  • 118
  • 148
Minto
  • 2,004
  • 1
  • 15
  • 19
17

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.

lloydyu24
  • 753
  • 1
  • 8
  • 17
14

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.

invertigo
  • 6,336
  • 5
  • 39
  • 64
13

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

Pervy Sage
  • 841
  • 1
  • 10
  • 22
  • This happened to me after I refactored my package name, but somehow the android studio left the `import com.example.old-package-name.R`, so I had to rename the import. – auspicious99 May 28 '20 at 11:43
  • I had moved some UI stuff to a sub-package and then got the error, I needed to import R from the parent package. – bweber13 Dec 21 '20 at 20:34
12

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

And the problem will be resolved.

Arunendra
  • 2,034
  • 26
  • 22
  • It should be noted that right clicking on "app" and clicking the synchronise button in the menu does not achieve this. Thanks. – Mafro34 Feb 09 '15 at 20:30
11

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)

Matthew Cawley
  • 2,828
  • 1
  • 31
  • 42
  • Interestingly, I had this issue on just one file and ran the "Inspect Code" process and it cleared itself (clean and rebuild didn't fix it). There must have been something stuck in Lint that only this could clear out. Thanks! – rundavidrun Nov 28 '16 at 05:43
  • Thank you for this! While this found many general errors, which was expected, the piece that brought down the entire castle was a small Syntax error in an XML file generated by Asset Studio! Once I resolved this, a Clean Project allowed me to move forward. – Bink Jul 24 '18 at 20:01
10

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
Ryan Heitner
  • 13,119
  • 6
  • 77
  • 119
  • I had the issue because there was an error in one of my XML files. Resolved the issue then did a `Build->Clean Project` – AjCodez Apr 29 '18 at 01:03
10

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.

Sridhar
  • 11,466
  • 5
  • 39
  • 43
  • In my case I merely had to import R from my new package name `import com.Neue.Package.R;` – Jacksonkr Mar 22 '22 at 00:02
  • The first step was exactly the missing piece for me. The `package` was incorrect set in the AndroidManifest.xml. – Mahm00d Feb 14 '23 at 12:23
9

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

Alex Burov
  • 1,881
  • 1
  • 17
  • 13
8

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.

TBridges42
  • 1,849
  • 1
  • 19
  • 29
8

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

enter image description here

Gundu Bandgar
  • 2,593
  • 1
  • 17
  • 21
7

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.

Jiakang Zhang
  • 869
  • 1
  • 7
  • 6
6

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.

Elsanty
  • 148
  • 1
  • 9
6

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.

S.Pedro
  • 87
  • 2
  • 9
  • Thanks. It worked for me too. I replaces some images in drawable and got that error. – KCP Mar 11 '16 at 11:57
6

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!

Hassan Naqvi
  • 424
  • 6
  • 18
6

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

Siva Prakash
  • 4,626
  • 34
  • 26
6

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.

Oussama Essamadi
  • 358
  • 8
  • 15
5

`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.`
Bapusaheb Shinde
  • 839
  • 2
  • 13
  • 16
  • This is a good answer, although I only needed to place '//' in the gradle file and select resync. Then all AS recognized the import and allowed me to run the app. – Val May 10 '18 at 04:03
4

This notation seems to work fine.

android:id="@+id/viewID"

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

Tevin J
  • 641
  • 2
  • 11
  • 15
4

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.

user1137313
  • 2,390
  • 9
  • 44
  • 91
4

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.

Sourav Roy
  • 323
  • 4
  • 12
4

Just import the R symbol from the root package

import rootpackage.R;

No rebuild, sync or another things...

RazvanParautiu
  • 2,805
  • 2
  • 18
  • 21
4

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

protanvir993
  • 2,759
  • 1
  • 20
  • 17
4

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
    }
}
Aloha
  • 864
  • 18
  • 40
4

In my case, this error showed while I tried to call R from another package. Importing R package solved my issue.

import com.mtdaps.yourapp.R;
Achintha Isuru
  • 2,662
  • 18
  • 24
3

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

ayal gelles
  • 2,829
  • 1
  • 21
  • 18
3

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.

Victoria Agafonova
  • 2,048
  • 10
  • 33
  • 50
3

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.

LOLapalooza
  • 2,042
  • 3
  • 17
  • 22
3

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

Than Htut
  • 121
  • 1
  • 2
  • 9
3

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.

Danger
  • 433
  • 5
  • 17
3

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.

mp501
  • 666
  • 8
  • 12
3

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

import com.example.myapp.R;
LundinCast
  • 9,412
  • 4
  • 36
  • 48
qjk
  • 81
  • 4
3

Cleaning, Rebuild and "Cache Remove" won't help me, Updating Android Studio Fixed the issue.

Muhammad Sanaullah
  • 435
  • 1
  • 6
  • 12
2

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.

Mike Hays
  • 93
  • 6
2

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.

thefreeman
  • 1,035
  • 11
  • 13
  • .iml files should generally never be touched. The fact that you had to go in there and modify your iml file says that there was something wrong with the IDE configuration. – IgorGanapolsky Mar 04 '15 at 02:42
2

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.

xhenryx14
  • 704
  • 6
  • 10
2

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

Paris G.
  • 81
  • 4
2

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.

Illegal Argument
  • 10,090
  • 2
  • 44
  • 61
2

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.

timmyt123
  • 401
  • 5
  • 8
2

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.

Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358
Lalit Rane
  • 850
  • 10
  • 16
2

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

Vrajesh
  • 1,312
  • 19
  • 25
  • This is probably the most common cause of this error. People: make sure ALL your xml files are correct! Dependencies on an xml file with an error show up in very weird ways, like this! – SMBiggs May 24 '17 at 04:03
2

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.

Levent Divilioglu
  • 11,198
  • 5
  • 59
  • 106
2

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!

M. Sherbeeny
  • 109
  • 2
  • 12
  • > Found that difference in gradle file: compile 'com.android.support:appcompat-v7:23.4.0' . That does mean you had to remove it? or had to add it? – nacho4d Jun 22 '16 at 01:04
  • 1
    I had to edit the version to make it the same as the one in the new working project. – M. Sherbeeny Jun 22 '16 at 02:50
2

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

Angoranator777
  • 334
  • 2
  • 6
2

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

Jaimin Prajapati
  • 341
  • 5
  • 14
2

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

2

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!
riu999
  • 46
  • 4
2

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.

Aman Goyal
  • 409
  • 5
  • 8
2

I have upgraded gradle version and gradle plugin version latest version today and it worked for me.

enter image description here

Afterwards, sync project with gradle files.

quant
  • 493
  • 9
  • 21
2

I was cleaning up the build.gradle and this error appeared.

A lot of "clean and rebuild" answers . None of that worked for me.

What finally worked was I found out I had by accident copy-pasted the wrong 'namespace' name in the build.gradle. Fixed it and it runs.

user1010160
  • 445
  • 3
  • 9
  • This one worked for me. I had renamed my com.abc.xyz to now be com.abc.def. It didn't refactor and rename everything associated with it properly. I had to go into build.gradle (:app) and change the namespace 'com.abc.xyz' to reflect my new name. After that, it worked. Took an hour to track that down. – Rick C. Hodgin Apr 09 '23 at 22:14
  • I did the same. I guess I now know what namespace is used for :) – steven smith Aug 17 '23 at 01:59
1

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

import android.R.*;
Dan
  • 45
  • 1
1

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.

1

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.

Tomap
  • 638
  • 1
  • 8
  • 21
1

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

Tony Tawk
  • 82
  • 2
1

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

Fakher
  • 2,098
  • 3
  • 29
  • 45
1

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

The_Martian
  • 3,684
  • 5
  • 33
  • 61
1

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.

Jan Kubovy
  • 421
  • 5
  • 11
1

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.

Michiel Pater
  • 22,377
  • 5
  • 43
  • 57
1

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.

Erick Boshoff
  • 1,443
  • 2
  • 18
  • 30
1

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.

Community
  • 1
  • 1
Gabor
  • 7,352
  • 4
  • 35
  • 56
1

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.

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
1

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

Zon
  • 18,610
  • 7
  • 91
  • 99
1

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.

user3501236
  • 123
  • 1
  • 2
  • 8
1

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

Susampath
  • 706
  • 10
  • 13
1

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

Braian Coronel
  • 22,105
  • 4
  • 57
  • 62
1

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.

Community
  • 1
  • 1
All Іѕ Vаиітy
  • 24,861
  • 16
  • 87
  • 111
1

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

Mjachowdhury
  • 85
  • 10
0

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.

Paul Moore
  • 136
  • 1
  • 16
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have sufficient [reputation](http://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](http://stackoverflow.com/help/privileges/comment). – duggu Jun 06 '15 at 04:11
  • The user asked 'I would like to know what causes this if anyone knows.' I stated my answer as to my solution. The content of the problem seems to occur by many reasons as stated by another user. What I posted repaired mine. – Paul Moore Jun 08 '15 at 20:46
  • This is posted at the top. We're looking for long answers that provide some explanation and context. Don't just give a one-line answer; explain why your answer is right, ideally with citations. Answers that don't include explanations may be removed – Paul Moore Jun 08 '15 at 20:48
0

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

Android Dev
  • 1,496
  • 1
  • 13
  • 25
0

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.

Community
  • 1
  • 1
Akshay
  • 101
  • 1
  • 10
  • Yes and no. It really makes hard to change SDK or JDK if you have whitespaces or non-ASCII symbols in SDK path. But after some actions it's possible. Though, you are right, it's a problem. – CoolMind Oct 14 '16 at 14:16
0

//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
Jay
  • 674
  • 11
  • 13
0

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.

creep3007
  • 1,794
  • 2
  • 21
  • 22
0

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.

pouyan
  • 3,445
  • 4
  • 26
  • 44
laixiaoyuan
  • 175
  • 2
  • 9
0

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

Pedro Duarte
  • 37
  • 10
0

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.

serwus
  • 155
  • 1
  • 14
0

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.

galibhkhan
  • 34
  • 3
0

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.

Jatin Bansal
  • 123
  • 8
0

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.

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Simba
  • 489
  • 6
  • 7
0

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
Avinash T.
  • 2,280
  • 2
  • 16
  • 23
kiran bankar
  • 91
  • 1
  • 1
0
     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

0

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.

0

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

Mohammad Shraim
  • 1,173
  • 12
  • 21
0

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.

Agilanbu
  • 2,747
  • 2
  • 28
  • 33
Valentin
  • 400
  • 2
  • 11
0

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

Marco Aurelio Silva
  • 1,524
  • 1
  • 12
  • 6
0

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.

Lwf804
  • 21
  • 1
0
  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.
Manjunath
  • 52
  • 1
  • 10
0

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

Alyoshak
  • 2,696
  • 10
  • 43
  • 70
0

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.

Tejas Shukla
  • 144
  • 7
0

One of the reasons could be, you have modified your layout/resource file recently and the resource (string/color/drawable etc.) is not available in your code but you have used the reference in design.

Try to look for such references, remove/comment them and try to rebuild.

Chintan Shah
  • 1,744
  • 2
  • 26
  • 28
0

this is not error . if you got error close the project . then open the project after that you can get one error

Cannot resolve symbol 'default_web_client_id'

it can be solved by inserting Web client ID in to Stings values

Rasathurai Karan
  • 673
  • 5
  • 16
0

I have done all the steps mentioned in the other answers but it still did not got resolved. I am using android studio chipmunk finally I was able to resolve that by removing

maven { url "https://jitpack.io" }

From setting.gradle I am answering to this question I think doing this might help someone

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Dkathayat1
  • 216
  • 1
  • 8
0

problem:can not resolve R.id.register_user_name

it may be strange but it worked for me:

1)go and make R.layout.something (something may be any word you want for example R.layout.activity_register)

  1. then replace it again with R.id.register_user_name (your original code)

try it and hope it will work for you:)

chaimae
  • 16
  • 2