Unresolved reference android studio ошибка

введите сюда описание изображенияСкажу сразу: — я абсолютный ноль в андроид разработке.
Получил вот такую ошибку «Unresolved reference: R». Пробовал чистить, ребилдить, синхронизировать с Gradle, инвалидейтить кеш. Ничего не помогает. Я так понимаю, что мой проект не видит файл с ресурсами. Не знаю почему так произошло. Ведь до этого проект запускался без этой ошибки, а после выхода и входа в андроид студию появилась она. Как ее решить??

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "ru.temocenter.temocenter"
        minSdkVersion 16
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    } }

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.android.support:recyclerview-v7:27.1.1'

    // 3rd party libs
    implementation 'com.google.code.gson:gson:2.8.0'
    implementation 'com.squareup.okhttp3:okhttp:3.10.0' }

задан 5 июн 2018 в 8:40

 Dmitriy Greh's user avatar

Dmitriy Greh Dmitriy Greh

1331 серебряный знак8 бронзовых знаков

4

Я решил этот вопрос. В общем, я просто удалил все те файлы на которые была ругань, сделал билд, посмотрел, что все работает, и добавил их снова — и все работает. Не знаю почему так происходит.

ответ дан 6 июн 2018 в 7:06

 Dmitriy Greh's user avatar

Dmitriy Greh Dmitriy Greh

1331 серебряный знак8 бронзовых знаков

import android.R

Удалите эту строку. Она может быть лишней, не знаю откуда взялась

Анастасия's user avatar

Анастасия

2,2811 золотой знак8 серебряных знаков22 бронзовых знака

ответ дан 27 фев 2021 в 20:43

user12927542's user avatar

Так вам Android Studio подсказывает почему не может проект билднуть. В Android Issues показано в каких файлах есть ошибки. К примеру в вашей разметке activity_contact_detail.xml используется файл под названием shadow и т.д , но
не может его найти из-за этого и происходит ошибка

ответ дан 5 июн 2018 в 13:54

Rasul's user avatar

RasulRasul

1,1385 серебряных знаков14 бронзовых знаков

1

Была похожая ситуация. Возникала при добавлении новой активити. Решалась следующим образом: File -> Invalidate Caches / Restart… -> Invalidate, затем Close Project, затем удаляем его из списка, затем открываем заново. Где-то на просторах StackOverflow это решение описывалась — не могу найти линк. В конечном итоге всё решилось тем, что я перешёл на бета версию AS и проблема исчезла. Однако при очередном обновлении всё повторилось вновь.

ответ дан 4 ноя 2018 в 15:41

S.Raman's user avatar

0

When you’re writing code for Android application and Kotlin, you may frequently encounter a static error from your IDE saying unresolved reference for a specific keyword or variable.

For example, you can produce the error by calling a custom function that you haven’t defined in your code yet:

myFunction("Hello")
// Unresolved reference: myFunction

Or when you assign a variable without declaring them:

myStr = "Hello"
// Unresolved reference: myStr

To resolve the issue, you need to make sure that the referenced keyword (whether it’s a variable, a function, or an object) is available and defined before it’s called.

To declare a variable, use the val or var keyword. To declare a function, use the fun keyword:

val myStr = "Hello"

fun myFunction(str: String) = print(str)

myFunction(myStr)

// no issues

When coding an Android application, this error may happen when you import libraries that haven’t been added to your project yet.

For example, you may import the kotlinx library in your MainActivity.kt file as follows:

package com.example.myapplication

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*

Without adding the kotlin-android-extensions in your build.gradle file, the import kotlinx line above will trigger the unresolved reference issue.

To resolve it, you need to add the kotlin-android-extensions to the build.gradle file plugins list as shown below:

plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-android-extensions'
}

Please make sure that you add the id 'kotlin-android-extensions' line on the build.gradle file that’s inside your app module.

Once you sync the Gradle build, the error should disappear.

If you still see the unresolved reference error after fixing the problem, try to build your Android application with Command + F9 for Mac or Control + F9 for Windows and Linux.

The error should disappear after the build is completed.

To conclude, the unresolved reference error happens when Kotlin has no idea what the keyword you’re typing in the file points to.

It may be a function, a variable, or another construct of the language that you’ve yet to declare in the code.

Or it can also be external Android and Kotlin libraries that you haven’t added to your current project yet.

For example, you may encounter an error saying Unresolved reference: Volley as follows:

val queue = Volley.newRequestQueue(this)

// Unresolved reference: Volley

This is because the Volley library hasn’t been added to the Android project yet.

If you click on the red bulb icon on the code line with the issue, Android Studio has several suggestions to resolve the error, one of them helps you to import the dependency automatically:

In this case, you can simply click on the highlighted option above and Android Studio will resolve the problem for you.

But other libraries may not have such an option, so you need to import them manually in the build.gradle file of your app module.

Once you specify the import, don’t forget to sync the Gradle build again to download the library into your project.

Good luck on fixing the unresolved reference issue! 👍

There are different kinds of errors that android developers come across while developing applications while using android studio. The errors form part of everyday experience as they provide an opportunity to explore and learn every day.

In this article, we shall focus on how to debug or solve the error that usually occurs most of the time when the android studio is opened and a project has not to build successfully which is cannot resolve symbol R in android studio or it can also be presented as unresolved reference R

With the way android projects are structured, that is with an error, the project cannot run successfully, it is a requirement that all errors must be fixed

Sometimes as a developer, you might not understand what is causing the error cannot resolve symbol R or unresolved reference R in your project

In most circumstances, the way one can solve the error cannot resolve symbol R or unresolved symbol R is not the way another one can. The error may occur due to various issues which we are going to provide solutions in this article.

To know that your project has the error cannot resolve symbol R or unresolved reference R is that, in the kotlin activity (.kt) or java activity (.java) files, the R will always be in red as shown below

Solved cannot resolve symbol R in Android Studio

In some cases, the red in the letter R may not be visible until when you run or build your project and that’s when the letter R will turn red and also display the errors in the build output as shown below

Solved cannot resolve symbol R in Android Studio

One thing with android is when it displays an error and you debug in the logcat or in the messages view section, it always points to the specific piece of code that has an error, the only problem will be if you are not familiar with how to solve the error that is present

How to fix error cannot resolve symbol R in android studio

As we have highlighted above, the error can also be presented as unresolved reference R.

There are different ways in which the error can be fixed.

       (i) Ensure the package name is correct

A package name is that name that uniquely identifies your application on your device and it is the same used in the google play store to identify the application. Mostly the package name in android in default is com.example.projectname

From a previous tutorial, we discussed why most developers have a problem with the package name and we noted that it’s due to copying pieces of code from a tutorial and therefore fails to be compatible with their project.

It’s therefore recommended to update the package name by changing or renaming the package name in android

To ensure that the package name for your app is correct, compare what you have in your activity either java or kotlin file with what is there in the android manifest file and also in build.gradle file for the app

  • The activity file package name is shown below

Solved cannot resolve symbol R in Android Studio

  • For the manifest file is as follows

Solved cannot resolve symbol R in Android Studio

  • For the build.gradle file for the app is as follows

Solved cannot resolve symbol R in Android Studio

From the above screenshots, it is clearly noted that the package name present in build.gradle file for app and in the android manifest file is com.example.loginproject while the one in kotlin activity file is package com.example.signupproject

If the package name is not correct in the kotlin or java activity is not the same as that in build.gradle file for the app and in the android manifest file is not the same, the error cannot resolve symbol R or unresolved reference R will be present

To fix the error, ensure that you update the package name in the activities that you have for your project to match the one in the manifest file and also in build.gradle file

When you update the package name in your activities to the correct package name, the red in the letter R will automatically disappear

        (ii) Clean and Rebuild the project

In cases where you do not know what is causing the error exactly, the first step to debug the error is to clean and rebuild the project.

The clean and rebuild the project ensures that if there are pieces of code that are not perfectly placed in their positions and if there are unnecessary pieces of code, the clean and rebuild ensures that only the required files are the ones in use

To clean the project,

  • in android studio click build and then clean project

Solved cannot resolve symbol R in Android Studio

To rebuild the project,

  • in android studio, click build and then build project

Solved cannot resolve symbol R in Android Studio

If there are no other existing errors in the code, the clean and rebuild project will resolve the error

          (iii) Make the project

The make project in android studio runs through all the files to diagnose if there are cached files that have not yet been updated to the current version of the code.

If there were errors in your project and you have resolved them, the make project will run over your project and update it to the current version

To make the project,

  • When using the Windows operating system, click ctrl and f9 and wait for it to build
  • Or click the hammer icon in the android studio at the second navigation at the top

Solved cannot resolve symbol R in Android Studio

      (iv) Sync your project with Gradle files

Syncing your project with Gradle files ensures that your project will pick the settings in the Gradle files and use them in the interior files.

The sync is necessary since when any dependency or feature is added in the Gradle file and you fail to sync and then you try to use the features that you have imported, your code will display errors

To sync your project with Gradle files,

  • In the android studio, click file and then sync project with Gradle files

Solved cannot resolve symbol R in Android Studio

Conclusion

With the four methods we have discussed above, the error cannot resolve symbol R or unresolved reference R will be fixed.

Note that in some cases, you can use any of the four methods and your error will be solved or you may be forced to try all of the above four methods to solve the error

That’s it for this article, I hope you have solved the error successfully and you can now run the project and install the apk in your mobile device

How to Fix Unresolved Reference Android Studio – This occurs because Android Studio cannot create the R.java file properly.

Solving “Unresolved Reference” Problem In Android Studio in two ways:
1. Click the Builds menu –> Rebuild Project

If method 1 doesn’t work, try the following:
2. Click the File menu –> Invalidate caches / Restart

But if you can’t use the method above, try checking the following specific problems:

Unresolved Referense : permission

for example, an error that occurs in the code (which I copied from someone’s website), I found errors such as:

How to Fix Unresolved Reference Android Studio

While I’ve included in the manifest file:

 <uses-permission android:name=”android.permission.ACCESS_FINE_LOCATION” />
So what must be changed is, before the error “Manifest.permission” is written, add the words “android”, so that it becomes:
android.Manifest.permission.ACCESS_FINE_LOCATION“.

How to Fix Unresolved Reference Android Studio

Error will gone.

Unresolved reference: FusedLocationProviderClient

If this is the case, add the following lines to the file build.gradle:

implementation "com.google.android.gms:play-services-location:15.0.1"

Then clik  Sync Now.

Done. I hope this article is useful.

Read more…
> How to Convert Int to String in Python
> requires ext-mbstring * -> it is missing from your system
> Illuminate Database QueryException Could not find driver
> Simple Linux Distro Lightweight Desktop Environment
> Adafruit_Sensor.h: No such file or directory

Kotlin Discussions

Loading

  • Unrecognized tag minecraft ошибка
  • Unrecognised disk label ошибка
  • Unreal tournament 2004 ошибка при запуске
  • Unreal engine ошибка при создании проекта c
  • Unreal engine ошибка ls 0019 is 0001