[android] "R cannot be resolved to a variable"?

In Eclipse, I've created a project from a source and now it shows errors - "R cannot be resolved to a variable". From what I found here, I had cleared and rebuilt the project, but still the R file doesn't appear in the /gen folder.

Any ideas?

This question is related to android android-resources

The answer is


import com.de.vogella.android.temprature1.R;

Project > Clean...

usually regenerates R.java file located in gen/com.mypackage


I know this is an old question but I just solved my own version of it and perhaps this might help someone.

After two days of tearing my hair out with this, I finally got around it by deleting the raw folder, then recreating it and dropping the file(s) back in.

After that, another Project > Clean and it at last compiled.


What you really need to do it just install "build-tools" from sdk manager, and r.java will be generated automatically.


your android manifest must start with correct package

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="HERE - Correct package NAME"
    android:versionCode="1"
    android:versionName="1.0" >`

I got similar problem and solution I found out was in resources any of the file aka background, sound etc must not contain capital letters or any special symbol other than _


Tip: update SDK and all utilities else one time. It helped to me.


I been having this and i did trace it back to the layout files.. It happend to me again however i could not find noting in the layout files. I looked in the string.xml and there was it.. one of the string names started with cap and that was causing the problem.


for me, the best solution to suggest to people that have problems with the "R" file would be to try the next steps (order doesn't matter) :

  1. update ADT & SDK , Eclipse and Java.

  2. remove gen folder , and create it again .

  3. do a clean-project.

  4. right click the project and choose android-tools -> fix-project-properties .

  5. right click the project and choose properties -> java-build-path -> order-and-export. make sure the order is :

    • Android 4.3 (always the latest version)

    • Android private libraries

    • android dependencies

    • your library project/s if needed

    • yourAppProject/gen

    • yourAppProject/src

  6. make sure all files in the res folder's subfolders have names that are ok : only lowercase letters, digits and underscore ("_") .

  7. always make sure the targetSdk is pointed to the latest API (currently 18) , and set it in the project.properties file


If R is missing

  • Locate your R.java file, it should be in the folder ./gen/
  • If it is missing, and "build project" doesnt build it, one of your XML files has errors, fix them or even delete them, then right-click your project and click build project
  • R.java file should be generated

Did you just update both sdk and adt(from 21 to 22), then you need to install a new item: Android SDK Build-tools

Refer to: Eclipse giving error, missing R.java file after recent update


Problem was eclipse was not generating R.java. To resolve this issue please go to project->clean... and select your project and select ok and then clean and build project and import your package name R file(Ex com.demo.R). It works.


Sooo many different possible solutions! For me, I found that Eclipse had created the faulty file in the wrong package. I fixed it by moving it into the same package as the R.java file.


Fix any XML formatting errors in the XML Files in your /res/menu folder.

Might be a compile time error from the XML file being improperly formatted.


Simple Solution:

Check whether in gen[generated Java Files], under your project package, there is a R.java file.

If no,

  1. There is some errors in xml files you have added or modified. check that deeply. Fix all yellow lints and go through the error log and console
  2. Check your xml files should be small letter, '_' and digits.
  3. Check your image names you have added also should be small letter, '_' and digits.
  4. Clean the project.
  5. Check R.java created. if yes, and still error occurs, follow the yes instructions below, else check xmls once again

If yes,

  1. replace the 'import android.R' by your project package.R ex: 'com.mysmallapp.main.R' in all files.
  2. Clean the project

Sometimes you can accidentially add an import to "R", so if at the top of your code you see some weird import about that that you did not add yourself, delete the reference, and everything should go back to normal


If Clean/Rebuild Project doesn't work try to check our package name in AndroidManifest.xml.

The problem "R cannot be resolved" happens when you change your package name in the AndroidManifest.xml file. It uses your Android package name to create a subdirectory under the "gen" directory where it stores the R.java file.


i lived with this problem for 2 weeks and today i find the solution that is "icrease (MINIMUM SDK REQUIRED) to maximum possible"


  • Rebuild
  • Clean ( Menu --> Project --> Clean )
  • Delete your import de.vogella.android.temprature1.R;

I had the same problem. I fix it by deleting the file in 'gen' directory, then I clean the project then the R.java was automatically generated.


Check your AndroidManifest.xml file, see if the package name is correct. If you copied an example it is likely this is wrong and the source of your problem.


I have just had this problem.

It was caused because I had a redundant menu resource that referred to a non-existing string.

Removed the menu XML and back came R.


It is possible you have an error in your *.xml files: layouts and etc.


I had the same problem. I didn't have any lines stating "import something.R". Cleaning and rebuilding also didn't solve the issue.

It turned out to be because of the name of a layout xml file. Those files can only contain lowercase letters, or numbers, or underscores. When I changed the filename (and everything that refers to it) from myLayout.xml to my_layout.xml, everything worked.


Before you try anything else, please check that your package declaration in your AndroidManifest.xml file matches the actual package name in your project's src folder! This has caused this error many times for me when creating test projects which I copy from existing projects. Hope this saves you time!

Also, creating an XML file with any capital letters will trigger this error.


I do my projects in FlashBuilder 4.7 and it gerenerates a row in strings.xml:

<string name="action_settings">Settings</string>

Once i deleted it, i got the same errors. When returned it in place everythings worked again.


For me somehow the Project properties; Android; Project Build Target was not set. I chose a Android version there (e.g. 4.2) and it fixed it.


This can happen when the android naming convention isn't followed. Check if you have placed a file/photo into one of the android folders and make sure that the file name contains only lower case letters


I had this problem and turns out this was due to an error in one of my layout xml files that I had just changed


I found this problem when trying to run the Notepadv3 programme from Googles 'first lesson'..

For me it was an issue with the xml file, due to the API level I was using. I renamed each case of Match_Parent to the older type of Fill_Parent. Oh and if you have already auto-built the project then you need to delete 'import android.R' on NoteEdit.java and Notepadv3.java, clean the project (click 'Project', then 'clean...') before saving.

Solved it for me. Came from this post Android NDK r4 san-angeles problem

Can't believe Google dosen't warn of this problem - I have been setting up another PC to start programming again and even with a bit of prior knowledge this was a pain.. How do you set the API when importing an existing project??? Can't see where there is any dialogue option when you 'File' 'Import' etc ..

Scamparelli


I had the same error. Error was that, I had placed a file in res/raw folder with invalid filename. As soon as I corrected the file name to a valid one, error was resolved!

Allowed characters for naming a file:-

1. a-z
2. . _
3. 0-9
4. no capital letters

Capital letters were the issue in my case!


When other solutions fail, select your project and delete it. MAKE SURE YOU DO NOT REMOVE FILES FROM DISK.

Then use file>import>existing android code into workspace, and select the location of your project.


  1. check if files in res folder have any errors then
  2. Right click on project -> Android tools -> Fix project properties
  3. Project Clean

I solved the problem with resolving R resource on fc19.x86_64 and ADT v22.0.5-757759 by installing additional libraries after Fedora and ADT upgrade.

yum install ld-linux.so.2
yum install libstdc++.so.6
yum install libz.so.1

Those libraries are required by adb (Android Debug Bridge version 1.0.31).

Then restart Eclipse and perform project clean Project->Clean check project you would like to clean.

Hope it helps :)


If Clean/Rebuild Project doesn't work try to check our package name in AndroidManifest.xml.

The problem "R cannot be resolved" happens when you change your package name in the AndroidManifest.xml file. It uses your Android package name to create a subdirectory under the "gen" directory where it stores the R.java file.


Check the androidmanifest.xml file and layoutfolder xml files. They should be created properly as the starting and ending clause in xml should be placed properly. Update the files, clean and build. And all set!


I got this when I renamed a project. Although the project is renamed, some references are not. Clearing lint, and then rerunning lint helped. (Right click project > Android Tools > Clear Lint Markers, then Run Lint)


i'm new to android development. I had the same problem and revolved around this thread for about a week. It turned out that as you download latest Android SDKs like API 23 which has recently been released, or if you update build tools, you need to modify the build.gradle file under Gradle Scripts if it does not get updated. It is located in app folder of your Project directory. You can open this file with notepad. My file now looks like this.

    apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.0"

    defaultConfig {
        applicationId "com.example.sukhwinder.justjava"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile 'com.android.support:appcompat-v7:23.+'
    compile fileTree(dir: 'libs', include: ['*.jar'])
}

Make sure compileSdkVersion, buildToolsVersion and targetSdkVersion match the latest version of Android SDK and Build Tools installed on your machine.


1) see if the xml files in the Package Explorer tree have an error-icon if they do, fix errors and R-class will be generated.

example hint: FILL_PARENT was renamed MATCH_PARENT in API Level 8; so if you're targeting platform 2.1 (api 7), change all occurences back to "fill_parent"

2) if you added "import android.R;" trying to do a quick-fix, remove that line


Check if the package name in the AndroidManifest.xml file is the same than the package name of your java class.

Eg. AndroidManifest.xml

 package="com.example.de.vogella.android.widget.example"

In your class MyWidgetProvider.java

package com.example.de.vogella.android.widget.example;

It was the cause of my error in this example.


Try to modify AndroidManifest file.

For example add space and delete this space. After this OPERATION, save project. Resources will be refreshed. It can help.


Nothing mentioned above worked for me. However, I fixed it myself.

Solution:

If you've any other files except activity_main.xml / main.xml inside app_name/res/layout remove it and try clean and build.

Note:

The unwanted files or (rather used later) files inside app_name/res/layout would be *.out.xml. Remove the same.


In my case, R.java wasn't getting generated because of a hierarchical parent error, which in turn was cured by updated one or more Eclipse plugins (Go Eclipse-->Help-->Check for Updates)


This error is because of deleting R.java file from project /gen folder. If you have backup of your project, please go to the project directory and paste R.java file which you copy from your backup section.

Corrupt R.java file can also be caused by an error in XML. Often these kinds of errors don't show up in eclipse, so I'd suggest taking a look at your XML files. After that you can also try to Clean your project by going to Project -> Clean... in the menu bar.


Just look in to your header files there will be:

import somefile.R;

Just remove that line and that's it.


My problem was strange and took some time to find. Somehow the package of the src file changed so that the last entry in the package was deleted. So for example initially my class MyActivity.java was in package com.abc.client.test.app but after I added a user permission, the app got removed and the package was renamed to com.abc.client.test. I don't know how it happened. Renaming the package and putting the java file in the correct place fixed the problem.


I've seen many answers suggesting to "fix errors in your XML files" but only giving general hints and tips on how to fix the XML.

Here is a systematic way to find the XML errors:

Look at the "Problems" tab in Eclipse. Ignore all "R cannot be resolved to a variable". Look at what remains. For me, it looks something like this:

Unparsed aapt error(s)! Check the console for output.

I quote from http://developer.android.com/tools/building/index.html#detailed-build :

The Android Asset Packaging Tool (aapt) takes your application resource files, such as the AndroidManifest.xml file and the XML files for your Activities, and compiles them. An R.java is also produced so you can reference your resources from your Java code.

Now, open the "Console" tab. Window -> Show View > Console

This should show you the exact error, in which file it occurred, and at what line number:

[2014-05-13 08:27:05 - MyFirstApp] /Users/alain/code/experimental/android/adt_workspace4.4/MyFirstApp/res/menu/main_activity_actions.xml:4: error: Error: No resource found that matches the given name (at 'icon' with value '@drawable/ic_action_search').
[2014-05-13 08:27:05 - MyFirstApp] /Users/alain/code/experimental/android/adt_workspace4.4/MyFirstApp/res/menu/main_activity_actions.xml:4: error: Error: No resource found that matches the given name (at 'title' with value '@string/action_search').

In my case, the first error is because I am referencing ic_action_search but I have not yet put ic_action_search.png in my res/drawable-*dpi directories. The second error is because I am referencing a string "action_search" but I have not yet defined it in res/values/strings.xml

It would have been nice if the ADT plugin actually took you to the line and file where the error is if you click on the error in the Console output, but for now, you have to do it manually.

The problem with Eclipse is that is is not stopping the build when aapt fails but continues to the next stage of the build, which is the Java Compiler. The command-line tools do not have this problem:

To generate build.xml:

$ android list targets

For me, I have:

Available Android targets:
----------
id: 1 or "android-16"
     Name: Android 4.1.2
     Type: Platform
     API level: 16
     Revision: 4
     Skins: HVGA, QVGA, WQVGA400, WQVGA432, WSVGA, WVGA800 (default), WVGA854, WXGA720, WXGA800, WXGA800-7in
 Tag/ABIs : default/armeabi-v7a, default/mips, default/x86
----------
id: 2 or "android-19"
     Name: Android 4.4.2
     Type: Platform
     API level: 19
     Revision: 3
     Skins: HVGA, QVGA, WQVGA400, WQVGA432, WSVGA, WVGA800 (default), WVGA854, WXGA720, WXGA800, WXGA800-7in
 Tag/ABIs : default/armeabi-v7a

Choose your target from the above list and use it in the next command:

$ android update project --target <your_target_id> --path /path/to/android/project

Now that build.xml is generated, you can build your project using one of these:

$ ant debug
$ ant -verbose debug
$ ant -debug debug

If the build fails at the aapt stage, it correctly does not generate R.java, but also it correctly does not continue to the Java Compiler stage. The console output will show you (just like in the Eclipse Console View) the filenames and line numbers where your XML errors are.

and here is how to turn on line numbers in Eclipse:

http://www.mkyong.com/eclipse/how-to-display-line-numbers-in-eclipse/

Preferences -> General -> Editors -> Text Editors -> [x] Show line numbers

For me the error got fixed by making some changes in Android SDK Manager.
Whatever be the latest API level available, install its "SDK Platform". For me latest API level available was 16, so I installed its's SDK Platform as shown in the image below. It works fine now.

Screenshot of Android SDK Manager after fixing the problem
Cheers, Mayank


what did it for me...

when i checked my project properties file (/project_root/project.properties), it had a reference to an old android version target which i no longer had installed

# Project target.
target=android-15

as soon as I changed this to say 17, it worked perfectly, soon as the file was saved my gen folders were built and inflated.

# Project target.
target=android-17

If you haven't yet, try cleaning your project as already suggested. In Eclipse Indigo, this is Project -> Clean... -> (Make sure your project(s) are checked) -> OK. After that, right click on your project and choose "Refresh".

If this is still a issue, a few questions:

  1. Did you recently change the package name of your application in AndroidManifest.xml?
  2. Does the 'activity' node in your AndroidManifest.xml describing the class "Convert" specify a package/name that cannot be resolved naturally with that of your application? As an example, if your application is com.foo.bar and your activity is described as com.foobar.Convert, R.* will not automagically function -- you would need to explicitly include R for the proper package.

I just had this error on my first hello world android application (3-Nov-2013).

Along with a few pointers from other users, this is what I had to do:

Control+Shift+O

Delete the import *.R from the top of the main activity .java file

Save the file, clean and compile the project (usually build is automatic)

Run SDK Manager, enable the build tools if not already checked, and hit Update regardless

Close and reopen Eclipse and the problem was gone


for me, the best solution to suggest to people that have problems with the "R" file would be to try the next steps (order doesn't matter) :

  1. update ADT & SDK , Eclipse and Java (both 1.6 and the latest one).

    EDIT: now the ADT supports Java 1.7 . link here.

  2. remove gen folder , and create it again .

  3. do a clean-project.

  4. right click the project and choose android-tools -> fix-project-properties .

  5. right click the project and choose properties -> java-build-path -> order-and-export. make sure the order is :

    • Android 4.4 (always the latest version)

    • Android private libraries

    • android dependencies

    • your library project/s if needed

    • yourAppProject/gen

    • yourAppProject/src

  6. make sure all files in the res folder's subfolders have names that are ok : only lowercase letters, digits and underscore ("_") .

  7. always make sure the targetSdk is pointed to the latest API (currently 19) , and set it in the project.properties file

  8. try to run Lint and read its warnings. they might help you out.

  9. make sure your project compiles on 1.6 java and not a different version.

  10. restart eclipse.


For me, there was a missing slash at the end of my SDK. In Eclipse > Preferences > Android > SDK Location

For example, change

/home/matt/android-sdk-linux

to

/home/matt/android-sdk-linux/

I had this problem and none of the other guides helped, and then I realized I didn't have the java jdk installed on my system. If you haven't done this either go download the version corresponding to the version of eclipse you installed (x86 or x64)


I had the same issue and main reason why R.java was not re-generated is errors in any of the files in the project. Once we fix those the R.java should get generated.


My setup was broken after a recent update where the SDK build tools need to be installed separately after the SDK installation. So build tools update + Eclipse restart fixed this for me.

Credit goes to the Android reply here


All the above suggestions should work normally, if you are still facing issue I suspect you are using 64bit OS and ADT is looking for 32bit binaries

try executing below command in terminal and clean the project once

sudo apt-get install ia32-libs

I got this error when I added a js file to the res folder.

An error indicator was set on the res folder icon. In all the classes where I used R I got this error.

I moved the js file to the assets folder and everything worked.