Android Studio 3.1.3 - Unresolved reference: R - Kotlin

50,153

Solution 1

The issue can be caused by many factors,

  • as mentioned by martomstom in this Answer the issue is sometimes caused by com.android.tools.build:gradle version, changing it's version to a more stable one would solve the problem: for example: com.android.tools.build:gradle:3.4.0-alpha02 with com.android.tools.build:gradle:3.2.1

  • Also, having libraries from the same group, but with different versions may cause the problem or even more runtime errors. use the exclude group method like the following : implementation('com.squareup.picasso:picasso:2.71828') { exclude(group: 'com.android.support') } in this case, picasso library uses android.support components, the android library version used in picasso is different than the one you're currently using in your app, so in order to solve this issue, we have to exclude it completely from its sub library and class groups.

  • It can also happen by the mismatch of resources and code, including this importation line in your activity may solve the problem too : import com.package.name.R

  • Sometimes it can happen because of the IDE, performances or memory.. Cleaning the project from time to time may save you some time, on Android Studio it would be something like this : Build -> Clean Project / Rebuild Project - Cleaning IDE cash also helps with performance and memory, on Android Studio it would look like this : File-> Invalidate Chases/ Restart -> Invalidate Cashes and Restart

  • I noticed that this problem happens to me the most of the time when importing new resources, Using prohibited characters in their names would fire the error, such as . , , - , UpperCase or special Letters

  • And as a suggestion , if you're using Kotlin, i really recommend using Kotlin extensions in your activity such as : import kotlinx.android.synthetic.main.activity_page.* or if you're using a custom view : kotlinx.android.synthetic.main.view_layout.view.* after that, in onCreat() method of an activity , you'll only have to call the id, for example : my_edit_text_ID.text = "Kotlin Dbest!", or from a custom view : mCostumView.my_edit_text_ID.text = "Kotlin Dbest!"

EDIT :

  • I have faced this issue againe and the problem was the '' R '' library was imported from 2 different sources :

    com.android.R
    
    com.example.package.R
    

    You must only import the '' R '' library with your application package name, in this case com.example.package.R Sometimes the library is not imported at all, to import it, click on the unresolved reference R and press Alt + Enter

EDIT:

As tobltobs mentioned in the comments section: " Most of the time the problem is caused by another error which prevents the build system from creating generated sources. To find the root cause look at the gradle log (the "toggle view" icon below of the green hammer in the Build output) and look for errors unrelated to R or BuildConfig (also generated). If there is no other error left and the problem with R persists then maybe something of this list might help. "

EDIT:

As Patrick Beagan mentioned, Kotlin extensions are now deprecated - I'd advise using ViewBinding instead

Solution 2

I used com.android.tools.build:gradle:3.3.0-alpha13 and had the same issue. Changing to stable Version 3.2.1 solved this problem for me.

Solution 3

So this is a misleading error. The fastest way to get to the root cause is to run:

bash gradlew assembleDebug --debug

then scroll up and look for the real error happening.

However, if it still doesn't seem like you have the answer you are looking for, then read on.

I'm going to explain the 30,000 foot view of what is happening. This is not EXACT order or EXACT flow, it is just pretty damn close ;) so if you know more then I do of the exact order and care to make corrections with links, feel free I won't stop ya :).

The Process

The R file is generated code.

There is an order to the generation.

Gradle will do it's magic, pull it's dependencies and kick off it's warning and error tree first,

then Android converts all Kotlin to Java behind the scenes. Yup that's right, our beloved Kotlin still has to be Java to compile for our beloved ART virtual machine.

Then it runs through and does the adapters that you have created for JVM Statics and a few other tasks. Next up it compiles all the xml databinding files first to create the generated databinding files.

If everything succeeds it moves on to processing the assets and resources. Which creates pointers or IDs for each resource that you reference in code. Next it will run through and begin compiling the code and packaging process after that.

Pretty straight forward process, but here in lies the problem.

The misleading Error

If any step fails before the R generation is complete, then the R does not get generated. Sometimes a simple rebuild is all you need to do, sometimes a simple File->Invalidate Cache and Restart is all you need. However, more often than not you have a code issue in your gradle, your xml, your databinding or your adapters that are preventing the compiler from even reaching the R generation stage.

So the next question is

"Well shoot, how do we troubleshoot it if the errors are worthless or non-existent".

Well first let's talk about the many ways these errors present themselves.

  • Duplicate Databinding class found
  • xml Binding Error at line #
  • Couldn't find matching signature of bind:customAdapterMethod
  • Can't find R file of the correct project, only shows import options for sub modules or incorrect namespace R files.
  • Couldn't find DataBindingUtility or DataBinding for activity/fragment
  • And many other various ways as well, too many to list them all

Next, let's talk about potential candidates causing the problem. As there are sooo many lol.

  • Gradle Syncing issues
  • Bad versions of Gradle or Tools, you may have gone too far forward in your last gradle file modification. Try stepping back one version and "invalidate cache and restart" if that fixed it, great, if not, read on.
  • Caching Issues (File->Restart and Invalidate Cache)
  • xml elements with wrong namespace
  • xml elements with bad IDs or references IDs out of order (i.e. you say align to right of an element that is lower in the xml document then the sibling element that is trying to reference it)
  • xml data binding issues referencing namespace or member that doesn't exist or is not typed correctly
  • xml data binding issues in non-auto-filled spots like custom attributes using adapters as those are harder to spot. i.e. bind:myCustomMethod=@"myObject.mistypedProperty()"
  • JVM Static adapters with issues or duplicated signatures
  • Duplicated or bad character in the Strings or Dimens file or any other xml file for that matter
  • Private variable marked for @Binding without properties to access it
  • Member variable marked for @Binding that matches a parent class method causing duplications that manifests itself in almost impossible errors
  • Mismatch of types like using an adapter that takes (Int) but you are passing (Int?) via data binding and it isn't recognized with JVM Statics until compile time
  • You selected IMPORT on a popup to import R file of a sub module instead of the application file
  • Having bindable members in a child or parent class, but not giving fully qualified namespace to class cast in the XML usage of the parent or child class. As the databinding compiler is not smart enough to realize the variable provided for class Foo is also parentFoo baseclass, so you have to qualify it as android:text="@((com.path.parentFoo)foo).parentMethod"
  • Having a method name in a class, that matches a "generated property from @Binding member variable" i.e. firstName as a variable, but then having a method called getFirstName in a parent or child class, because you are now matching a method name that will get auto generated, thus causing dataBindingUtility duplication class errors.
  • There are more causes, but this should give you a series of places to look, but the list can go on and on seriously.

Unfortunately this happens a lot in bleeding edge technologies where the UI tools are not up to speed with the terminal based tools yet. So I suggest you run from the project root in a terminal with

bash gradlew assembleDebug --debug

When it fails, and it will. Start scrolling up through the logs until you find the red where you see what is actually failing and preventing the next stage from occurring.

You will find this especially useful when you start dealing with databinding.

TIP:

When you start dealing with databinding, make sure you compile and run often because the goal is to recognize right away before doing other files to make sure you didn't break generation and make your life MUCH easier to know code you just added caused the issue before getting too far.

Times to compile and run to confirm no issues before moving on.

  • If you add a few JVM statics compile and run
  • If you add variables to your XML to use
  • If you bind to properties of your model in 1 file
  • If you add a binding to a JVMStatic
  • If you add bindable members or properties to an model
  • If you refactor moving observable member variables or properties into children or base classes
  • Any other xml or binding related elements that can effect the generated code.

Like I mentioned above, the reason is to avoid getting so many changes, that it becomes a troubleshooting nightmare to find a generic vague, horrible error related to generated databinding code. I'm sure the tools will improve, but for now, do yourself a favor and compile and run often when changing Databinding related items.

Happy Coding

Solution 4

Use gradle commands.
In Android Studio, on the right menu:
Gradle -> :app -> Tasks -> build -> clean.
After that, Gradle -> :app -> Tasks -> build -> build

Solution 5

I had the same problem, and I tried not to downgrade from gradle version 3.3 to gradle version 3.2.1. Instead I updated Android Studio to version 3.3, which made the trick for me ;-)

Share:
50,153
Tamim Attafi
Author by

Tamim Attafi

Shh, all is better in black 🖤

Updated on July 09, 2022

Comments

  • Tamim Attafi
    Tamim Attafi almost 2 years

    I am new to kotlin, i have converted some code from java but it seems like there's something wrong, The R in findViewById(R.id.my_id) is highlighted in red and it shows this message : "Unresolved reference: R".. I've been looking for a solution but i seem not to figure it out, So what should i do? Here's a screenshot :

    enter image description here

  • k-thorat
    k-thorat over 5 years
    If you don't see Gradle menu on right. Check Android MenuBar -> View-> Tool Windows -> Gradle
  • Subodh Nijsure
    Subodh Nijsure over 5 years
    Yup reverting to 3.3.0-alpha13 stable 3.2.1 fixed the issue!
  • DKV
    DKV over 5 years
    for me even the r is unresolved able to run the app. i am using mac
  • IgorGanapolsky
    IgorGanapolsky over 5 years
    You can also do this from commandline: rm -rf .gradle | rm -rf build/ | ./gradlew assemble
  • Sergei Emelianov
    Sergei Emelianov about 5 years
    Updating Android Studio to the 3.3.1 version solved this issue for me
  • MainActivity
    MainActivity about 5 years
    Still actual for 3.3.1 stable. Needed to change to 3.2.1 and R is resolved. App was compiling but R was not imported, while Kotlin extensions worked OK.
  • Tamim Attafi
    Tamim Attafi about 5 years
    @KMC, i'm glad it helped, if you still want to use these libraries, you may use the exclude method, i have updated the second bullet you might check it out.
  • Jeffery Ma
    Jeffery Ma about 5 years
    kotlin version = '1.3.21' gradle plugin version = '3.3.2' gradle version = '4.10.1' got this problem on Android Studio 3.2.1 , upgrade Android Studio to 3.3.2 solved the problem
  • vikzilla
    vikzilla over 4 years
    Adding import com.package.name.R atop the fragment helped
  • tobltobs
    tobltobs over 4 years
    A bit long, you might add a tl;dr that looking at the gradle log output will help to find the real cause.
  • Andy Weinstein
    Andy Weinstein over 4 years
    my problem was with package name - I had changed it, but evidently not everywhere - an autogenerated activity used the old name. I did a refactor on the package name and all was back to normal.
  • wildcat12
    wildcat12 about 4 years
    That didn't work for me. File->Invalidate Caches/Restart worked for me as suggested by another answer, but there isn't a single solution to this problem as pointed out by others. It can be caused by numerous things.
  • CodeClown42
    CodeClown42 over 3 years
    This has happened to me when integrating lib sources (eg. removing a .jar/aar and replacing it with a src folder) for debugging purposes. The R import in this case is not the package name where the problem file is, it's the package where the Activity source is for the MAIN activity from AndroidManifest.xml.
  • J A S K I E R
    J A S K I E R over 3 years
    package com.mydomain.appname In my case I've copied the code, therefore I have forgotten to change the package name to mine.
  • Patrick Beagan
    Patrick Beagan over 2 years
    Kotlin extensions are now deprecated - I'd advise using ViewBinding instead
  • mahee96
    mahee96 over 2 years
    Still gets me, had checked the imports only to find it was android.R... removing it automatically triggered IDE's auto import for correct file which is package level R class
  • JCarlosR
    JCarlosR about 2 years
    Another potential cause: I had defined a library module with the same package name as my main module. Android Studio resolved the view id fine, but there were conflicts when running my androidTests. There was no specific clue about this when compiling.