"R cannot be resolved to a variable" error goes away after building project

android, r.java-file

Solution

I found this happening to me with a broken layout. No need to be worry. I am trying my best to giving you the solution:

Solution:

Make sure that anything the R. links to is not broken. Fix all errors in your XML files. If anything in the ADKs are broken, R will not regenerate.

If you somehow hit something and created import `android.R` in your activity, remove it.

Run Project -> Clean. This will delete and regenerate R and BuildConfig.

Make sure Project -> Build Automatically is ticked. If not, build it manually via Menu -> Project -> Build Project .

Wait a few seconds for the errors to disappear.

If it doesn't work:

- delete everything inside the /gen/ folder

If it still doesn't work:

- try right-clicking your project -> Android Tools -> Fix Project Properties.

Check your *.properties files (in the root folder of your app folder) and make sure that the links in there are not broken.

Right-click your project > properties > Android.

Look at the Project Build Target and Library sections on the right side of the page. Your Build Target should match the target in your AndroidManifest.xml. So if it's set to target 17 in AndroidManifest, make sure that the Target Name is Android 4.2. If your Library has an X under the reference, remove and re-add the library until there's a green tick. This might happen if you've moved a few files and folders around.

What to do if R doesn't regenerate

This usually happens when you have a broken xml file.

Check errors inside your XML files, mainly within the /res/ folder

Common places are /layout/ and /values/ especially if you've changed one of them recently

Check AndroidManifest.xml, I find that often I change a string, and forget to change the string name from AndroidManifest.xml.

Check that Android SDK Build-tools is installed. Window->Android SDK Manager->Tools->Android SDK Build-tools

Make sure when you update the Android SDK Tools, you also update the Android SDK Platform-tools and Android ASK Build-tools. Build fails silently if they don't match.

If you can't find the issue:

- right click /gen/ -> Restore from local history... -> tick R.java -> click Restore. This doesn't solve the problem, but it will clear out the extra errors to make the problem easier to find.

Hope it will help you. :)

Problem

I am getting the "R cannot be resolved to a variable" error all of a sudden. I read another thread on this issue and it says to update the android build tools to make the error go away but that did not fix it. But for some reason the error goes away when I build the project. What is going on here?

Original source