Error cannot find symbol android studio

I was working on my app and everything was normal until I tried to display image in java. I ran the app once and it ran normally, the picture was displayed. After that it asked me to import some

I was working on my app and everything was normal until I tried to display image in java.

I ran the app once and it ran normally, the picture was displayed.
After that it asked me to import some libraries and I imported them. After that I got errors for my activities.

Errors like:

Gradle: error: cannot find symbol variable activity_main
Gradle: error: cannot find symbol variable button1
Gradle: error: cannot find symbol variable button2
Gradle: error: cannot find symbol variable textView
Gradle: error: cannot find symbol variable secondActivity

In MainActivity I have imported these libraries:

import android.R;
import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.Button;

and in secondActivity these:

import android.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

Does anyone know how to fix this?

EDIT: I deleted import android.R; and now it works normally.

Shubhamhackz's user avatar

Shubhamhackz

6,8956 gold badges50 silver badges69 bronze badges

asked Aug 9, 2013 at 19:45

user2668638's user avatar

1

You shouldn’t be importing android.R. That should be automatically generated and recognized. This question contains a lot of helpful tips if you get some error referring to R after removing the import.

Some basic steps after removing the import, if those errors appear:

  • Clean your build, then rebuild
  • Make sure there are no errors or typos in your XML files
  • Make sure your resource names consist of [a-z0-9.]. Capitals or symbols are not allowed for some reason.
  • Perform a Gradle sync (via Tools > Android > Sync Project with Gradle Files)

Community's user avatar

answered Aug 9, 2013 at 20:00

BLaZuRE's user avatar

BLaZuREBLaZuRE

2,3552 gold badges26 silver badges43 bronze badges

5

If you are using multiple flavors?

-make sure the resource file is not declared/added both in only one of the flavors and in main.

Example: a_layout_file.xml file containing the symbol variable(s)

src:

flavor1/res/layout/(no file)

flavor2/res/layout/a_layout_file.xml

main/res/layout/a_layout_file.xml

This setup will give the error: cannot find symbol variable, this is because the resource file can only be in both flavors or only in the main.

answered Jan 4, 2016 at 13:12

TouchBoarder's user avatar

TouchBoarderTouchBoarder

6,4022 gold badges52 silver badges60 bronze badges

If you are using a String build config field in your project, this might be the case:

buildConfigField "String", "source", "play"

If you declare your String like above it will cause the error to happen. The fix is to change it to:

buildConfigField "String", "source", ""play""

answered Dec 30, 2016 at 6:43

Sean Goudarzi's user avatar

Sean GoudarziSean Goudarzi

1,1641 gold badge9 silver badges22 bronze badges

Open project in android studio
click file
and click Invalidate Caches/Restart

answered Mar 19, 2019 at 13:33

RanaUmer's user avatar

RanaUmerRanaUmer

5415 silver badges9 bronze badges

make sure that the imported R is not from another module. I had moved a class from a module to the main project, and the R was the one from the module.

answered Jan 4, 2018 at 15:53

Alberto M's user avatar

Alberto MAlberto M

1,5651 gold badge17 silver badges41 bronze badges

Make sure you have MainActivity and .ScanActivity into your AndroidManifest.xml file:

<activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".ScanActivity">

    </activity>

answered Jul 13, 2017 at 22:14

julien bouteloup's user avatar

Make sure your variables are in scope for the method that is referencing it. For example I had defined a textview locally in a method in the class and was referencing it in another method.

I moved the textview definition outside the method right below the class definition so the other method could access the definition, which resolved the problem.

answered Aug 13, 2017 at 8:07

Jazzmine's user avatar

JazzmineJazzmine

1,7678 gold badges34 silver badges54 bronze badges

Another alternative to @TouchBoarder’s answer above is that you may also have two layout files with the same name but for different api versions. You should delete the older my_file.xml file

my_file.xml
my_file.xml(v21)

answered Apr 26, 2018 at 1:46

Bond James's user avatar

Make sure that the control you are referring to in the XML layout file really exists, even if it’s not being used.

I had this after when I did «removed unused resources» refactory.

For example, you will get this error if there is no progressBar in the layout.

rootView = inflater.inflate(R.layout.fragment_stats, container, false);

mProgressBar = rootView.findViewById(R.id.progressBar);

answered Mar 23, 2021 at 2:01

live-love's user avatar

live-lovelive-love

46.3k22 gold badges227 silver badges197 bronze badges

Please check you accidentally added the XML file into the layout folder.

answered Jun 11, 2021 at 6:28

jerald jacob's user avatar

jerald jacobjerald jacob

5551 gold badge3 silver badges16 bronze badges

Make Sure your package name correct at top, wrong package name may cause this issue.

Marco Bonelli's user avatar

Marco Bonelli

60.9k20 gold badges119 silver badges123 bronze badges

answered Nov 27, 2021 at 15:11

fazal ur Rehman's user avatar

I’m having major problems with building my project.

My project is getting built in Android Studio, and the directory is like so:

root
-project
--build
--libs
--src
---java
----com
-----company.project
------<All this projects source>
-projectutils
--build
--src
---main
----java
-----com.company.utils
------<All this projects source>

«project» is the main app, and it includes projectutils as a dependency. It uses Gradle to build, and I’ve added the correct includes to the root settings.gradle, and the correct dependencies to project.

Here is my settings.gradle in the root of my project:

include ':project', ':projectutils'

Here is my build.gradle for my project:

apply plugin: 'android'

android {
    compileSdkVersion 19
    buildToolsVersion '20.0.0'
    defaultConfig {
        applicationId 'com.company.project'
        minSdkVersion 15
        targetSdkVersion 17
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
    productFlavors {
    }
}

dependencies {
    compile 'com.actionbarsherlock:actionbarsherlock:4.4.0@aar'
    compile files('libs/android-support-v4.jar')
    compile files('libs/commons-validator-1.4.0.jar')
    compile 'com.viewpagerindicator:library:2.4.1@aar'
    compile 'joda-time:joda-time:2.3'
    compile project(':projectutils')
}

No matter what I do, it always gives the error Error:(4, 34) error: package com.company.utils.database does not exist, even though I’ve added the correct dependency and the Android auto-complete can see and parse the import command, so obviously Android studio is able to see it correctly. There are a ton more errors, but they are all fundamentally the same: It can’t seem to find com.company.utils and I have no idea what else I need to do.

I’ve spent all day trying to get this thing set up just to get it running and this is the biggest brick wall so far. I have literally no idea what I could be missing to cause these errors. I’ve fixed a bunch of similar errors with Facebook and Kumulos but this one won’t work no matter what I try. Could anyone give me some pointers?

1. Overview

In this tutorial, we’ll review what compilation errors are. Then we’ll specifically explain the “cannot find symbol” error and how it’s caused.

2. Compile Time Errors

During compilation, the compiler analyses and verifies the code for numerous things, such as reference types, type casts, and method declarations, to name a few. This part of the compilation process is important, since during this phase we’ll get a compilation error.

Basically, there are three types of compile-time errors:

  • We can have syntax errors. One of the most common mistakes any programmer can make is forgetting to put the semicolon at the end of the statement. Some other mistakes include forgetting imports, mismatching parentheses, or omitting the return statement.
  • Next, there are type-checking errors. This is the process of verifying type safety in our code. With this check, we’re making sure that we have consistent types of expressions. For example, if we define a variable of type int, we should never assign a double or String value to it.
  • Finally, there’s the possibility that the compiler crashes. This is very rare, but it can happen. In this case, it’s good to know that our code might not be the problem, and that it’s an external issue instead.

The “cannot find symbol” error comes up mainly when we try to use a variable that’s not defined or declared in our program.

When our code compiles, the compiler needs to verify all the identifiers we have. The error cannot find symbol” means we’re referring to something that the compiler doesn’t know about.

3.1. What Can Cause the “cannot find symbol” Error?

There’s really only one cause; the compiler couldn’t find the definition of a variable we’re trying to reference.

But there are many reasons why this happens. To help us understand why, let’s remind ourselves what our Java source code consists of:

  • Keywords: true, false, class, while
  • Literals: numbers and text
  • Operators and other non-alphanumeric tokens: -, /, +, =, {
  • Identifiers: main, Reader, i, toString, etc.
  • Comments and whitespace

4. Misspelling

The most common issues are all spelling-related. If we recall that all Java identifiers are case-sensitive, we can see that the following would all be different ways to incorrectly refer to the StringBuilder class:

  • StringBiulder
  • stringBuilder
  • String_Builder

5. Instance Scope

This error can also be caused when using something that was declared outside of the scope of the class.

For example, let’s say we have an Article class that calls a generateId method:

public class Article {
    private int length;
    private long id;

    public Article(int length) {
        this.length = length;
        this.id = generateId();
    }
}

But we declare the generateId method in a separate class:

public class IdGenerator {
    public long generateId() {
        Random random = new Random();
        return random.nextInt();
    }
}

With this setup, the compiler will give a “cannot find symbol” error for generateId on line 7 of the Article snippet. This is because the syntax of line 7 implies that the generateId method is declared in Article.

Like in all mature languages, there’s more than one way to address this issue, but one way would be to construct IdGenerator in the Article class and then call the method:

public class Article {
    private int length;
    private long id;

    public Article(int length) {
        this.length = length;
        this.id = new IdGenerator().generateId();
    }
}

6. Undefined Variables

Sometimes we forget to declare the variable. As we can see from the snippet below, we’re trying to manipulate the variable we haven’t declared, which in this case is text:

public class Article {
    private int length;

    // ...

    public void setText(String newText) {
        this.text = newText; // text variable was never defined
    }
}

We solve this problem by declaring the variable text of type String:

public class Article {
    private int length;
    private String text;
    // ...

    public void setText(String newText) {
        this.text = newText;
    }
}

7. Variable Scope

When a variable declaration is out of scope at the point we tried to use it, it’ll cause an error during compilation. This typically happens when we work with loops.

Variables inside the loop aren’t accessible outside the loop:

public boolean findLetterB(String text) {
    for (int i=0; i < text.length(); i++) {
        Character character = text.charAt(i);
        if (String.valueOf(character).equals("b")) {
            return true;
        }
        return false;
    }

    if (character == "a") {  // <-- error!
        ...
    }
}

The if statement should go inside the for loop if we need to examine characters more:

public boolean findLetterB(String text) {
    for (int i = 0; i < text.length(); i++) {
        Character character = text.charAt(i);
        if (String.valueOf(character).equals("b")) {
            return true;
        } else if (String.valueOf(character).equals("a")) {
            ...
        }
        return false;
    }
}

8. Invalid Use of Methods or Fields

The “cannot find symbol” error will also occur if we use a field as a method or vice versa:

public class Article {
    private int length;
    private long id;
    private List<String> texts;

    public Article(int length) {
        this.length = length;
    }
    // getters and setters
}

If we try to refer to the Article’s texts field as if it were a method:

Article article = new Article(300);
List<String> texts = article.texts();

Then we’d see the error.

This is because the compiler is looking for a method called texts, and there isn’t one.

Actually, there’s a getter method we can use instead:

Article article = new Article(300);
List<String> texts = article.getTexts();

Mistakenly operating on an array rather than an array element is also an issue:

for (String text : texts) {
    String firstLetter = texts.charAt(0); // it should be text.charAt(0)
}

And so is forgetting the new keyword:

String s = String(); // should be 'new String()'

9. Package and Class Imports

Another problem is forgetting to import the class or package, like using a List object without importing java.util.List:

// missing import statement: 
// import java.util.List

public class Article {
    private int length;
    private long id;
    private List<String> texts;  <-- error!
    public Article(int length) {
        this.length = length;
    }
}

This code won’t compile, since the program doesn’t know what List is.

10. Wrong Imports

Importing the wrong type, due to IDE completion or auto-correction is also a common issue.

Think of a scenario where we want to use dates in Java. A lot of times, we could import a wrong Date class, which doesn’t provide the same methods and functionalities as other date classes that we might need:

Date date = new Date();
int year, month, day;

To get the year, month, or day for java.util.Date, we also need to import the Calendar class and extract the information from there.

Simply invoking getDate() from java.util.Date won’t work:

...
date.getDay();
date.getMonth();
date.getYear();

Instead, we use the Calendar object:

...
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Paris"));
cal.setTime(date);
year = cal.get(Calendar.YEAR);
month = cal.get(Calendar.MONTH);
day = cal.get(Calendar.DAY_OF_MONTH);

However, if we’ve imported the LocalDate class, we won’t need additional code to provide us the information we need:

...
LocalDate localDate=date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
year = localDate.getYear();
month = localDate.getMonthValue();
day = localDate.getDayOfMonth();

11. Conclusion

Compilers work on a fixed set of rules that are language-specific. If a code doesn’t stick to these rules, the compiler can’t perform a conversion process, which results in a compilation error. When we face the “cannot find symbol” compilation error, the key is to identify the cause.

From the error message, we can find the line of code where the error occurs, and which element is wrong. Knowing the most common issues that cause this error will make solving it quick and easy.

wggg

0 / 0 / 0

Регистрация: 09.03.2013

Сообщений: 30

1

23.11.2015, 22:36. Показов 2395. Ответов 1

Метки нет (Все метки)


Подскажите.

Java
1
2
3
4
5
6
7
8
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        //Объявляем использование кнопки, привязываем к нашей кнопке:
    Button button=(Button)findViewById(R.id.bs); // указывает ошибку в данной строке"error cannot find symbol variable bs"
    }

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



2882 / 2294 / 769

Регистрация: 12.05.2014

Сообщений: 7,978

24.11.2015, 11:46

2

в файле activity_main.xml нет элемента с id = bs



0



Symbols and Symbol Table

Before diving into the details of the “cannot find a symbol” error, here is a brief introduction to symbols and symbol tables in Java.  A symbol refers to an identifier in the compilation process in Java. All the identifiers used in the source code are collected into a symbol table in the lexical analysis stage. The symbol table is a very significant data structure created and maintained by the compilers to store all the identifiers and their information.

This information is entered into the symbol tables during lexical and syntax analysis which is then used in multiple phases of compilation.

From classes, variables, interfaces to methods, all of them require an identifier for declaration. During the code generation process, when these identifiers are encountered in the source code, the compiler checks for them in the symbol tables and the stored information is then used to verify the declarations, the scope of a variable, and verifying that the expression is semantically correct or not.

The compilation process usually does not go as smooth as you would think. Errors are inevitable in any development stage and one of the very commonly occurring errors during the compilation process is Java “cannot Find Symbol” Error. In this article, we will be discussing the reasons behind the occurrence of Java cannot find symbol errors and how you can resolve them.

As the name suggests, the Java cannot find symbol error occurs when a required symbol cannot be found in the symbol table. Although there can be various reasons behind this, it points to one fact the Java compiler was unable to find the symbol and its details associated with a given identifier.

As there are a variety of Java compilers available, many of them use slightly different terminologies, because of that, you can also find the “cannot find symbol” error termed as the “symbol not found” or “cannot resolve symbol” error. Besides the name, there is simply no difference between these errors.

Structure of Java Cannot Find Symbol Error

The compiler output a specific error message with the cannot find symbol error.

It contains the following two fields that indicate the missing symbol and its location:

  1. Symbol: The name and type of the identifier you are looking for.
  2. Location: The particular class in which that identifier has been referenced.

Causes of Java Cannot Find Symbol Error

We will be discussing the following most common causes of the cannot find symbol error during compilation,

  • misspelt identifiers
  • Undeclared variables
  • Out of scope references to variables and methods
  • The unintentional omission of import statements

Misspelt identifier names

This is the most common and most occurring reason behind the Java cannot find symbol error. Misspelling an existing variable, class, interface, package name or a method causes the “cannot find symbol error” as the compiler cannot recognize the symbol and identifies it as an undeclared variable. Java identifiers are also case-sensitive, so even a slight variation of an existing variable will result in this error.

See code example below:

1. public class MisspelledMethodNameExample {
2.    static int findLarger(int n1, int n2) {
3.      if (n1 > n2) return n1;
4.      if (n2 > n11) return n2;
5.      if (n2 == n11) return -1;
6.    }
7. 
8.    public static void main(String... args) {
9.       int value = findlarger(20, 4); // findlarger ≠ findLarger
10.      System.out.println(value);
11.   }
12. }
MisspelledMethodNameExample.java:9: error: cannot find symbol   
 int value = Fibonacci(20);
              ^
 symbol:   method findLarger(int, int)
  location: class MisspelledMethodNameExample

It can be easily resolved by correcting the spelling of the function in line 9.

Undeclared variables

When the Java compiler come across an identifier used in the code but it cannot be found in the symbol table, the “cannot find symbol” error is shown. The only reason behind the absence of a variable from the symbol table is that it is not declared in the code. Some new programming languages do not require explicit declaration of variables but it is mandatory in Java to always declare a variable before it is used or referenced in the source code.

The code snippet below demonstrates an undeclared variable in the code. In this case, the identifier sum on line 7, causes the Java “cannot find symbol error”.

See code example below:

1. public class UndeclaredVariableExample
2. {
3.     public static void main(String... args) {
4.        int num1 = 5;
5.        int num2 = 10;
6.        int num3 = 43;
7.        sum = (num1 + num2 + num3) // sum is not declared
8.        System.out.println(sum);
9.      }
10. }
UndeclaredVariableExample.java:7: error: cannot find symbol
    sum = (num1 + num2 + num3);
    ^
  symbol:   variable sum
  location: class UndeclaredVariableExample

UndeclaredVariableExample.java:8: error: cannot find symbol
    System.out.println(sum);
                       ^
  symbol:   variable sum
  location: class UndeclaredVariableExample
2 errors

Declaring this variable by specifying the appropriate data type can easily resolve the error.

See this corrected code below,

1. public class UndeclaredVariableExample
2. {
3.    public static void main(String args) {
4.      int num1 = 5;
5.      int num2 = 10;
6.      int num3 = 43;
7. 
8.      int sum = (num1 + num2 + num3);
9.      System.out.println(sum);
10.     }
11. }

Out of scope variable

When a Java code attempts to access a variable declared out of scope such as in a non-inherited scope the compiler will result in issuing the “cannot find symbol” error. This commonly happens when you attempt to access a variable declared inside a method or a loop, from outside of the method.

See this code example below where the “cannot find symbol” error has occurred when the counter variable which is declared inside a for loop is attempted to be accessed from out of the loop.

See code below:

1. public class OutOfScopeExample 
2. {
3.      public static void main(String args) {
4. 
5.             for (int counter = 0; counter < 100; counter++) 
6.             { … }
7. 
8. System.out.println(“Even numbers from 0 to 100”)
9.       if (counter mod 2 == 0) 
10.       {
11.            System.out.println(counter);
12.       }
13.    }
14. }
OutOfScopeVariableExample.java:9: error: cannot find symbol
    if (counter mod 2 == 0)
        ^
  symbol:   variable counter
  location: class OutOfScopeVariableExample

OutOfScopeVariableExample.java:12: error: cannot find symbol
      System.out.println(counter);
                         ^
 symbol:   variable counter
  location: class OutOfScopeVariableExample
2 errors

I can be easily resolved by just moving the if block inside the for loop (local scope).

See this code example,

1. public class OutOfScopeExample 
2. {
3.     public static void main(String... args) {
4. 
5.        for (int counter = 0; counter < 100; counter++) 
6.        { 
7.         System.out.println(“Even numbers from 0 to 100”)
8.         if (counter mod 2 == 0) 
9.        {
10.           System.out.println(counter);
11.        }
12.     }
13.   }
14. }

Missing import statement

Java allows you to use built-in classes or any imported libraries in your code to save your time by reusing the code but it requires importing them properly using the import statements at the start. Missing the import statement in your code will result in the cannot find symbol error.

java.util.Math class is utilized in the code given below but it is not declared with the “import” keyword, resulting in the “cannot find symbol error”.

See code below:

1. public class MissingImportExample {
2. 
3.     public static void main(String args) 
4.     {
5.         double sqrt19 = Math.sqrt(19);
6. System.out.println("sqrt19 = " + sqrt19);
7.    }
8. }
MissingImportExample.java:6: error: cannot find symbol
  double sqrt19 = Math.sqrt(19);
                  ^
  symbol:   class Math
  location: class MissingImportExample

Adding the missing import statement can easily solve the issue, see code below:

1. import java.util.Math;
2. 
3.    public class MissingImporExample {
4. 
5.     public static void main(String args) 
6.    {
7.       double sqrt19 = Math.sqrt(19);
8.  System.out.println("sqrt19 = " + sqrt19);
9.    }
10. }

Miscellaneous reasons

We have covered some of the main causes of the “cannot find symbol” Java error but occasionally it can also result due to some unexpected reasons. One such case is when attempting to create an object without the new keyword or an accidental semicolon at the wrong place that would terminate the statement at an unexpected point.

Also Read: Functional Interfaces In Java

Some other causes for the cannot find symbol error may include when you forget to recompile the code or you end up using the dependencies with an incompatible version of Java. Building a project with a very old JDK version can also be a reason as well as mistakenly redefining platform or library classes with the same identifier.

Conclusion

We have discussed that the “cannot find symbol Java” error is a Java compile-time error which is encountered whenever an identifier in the source code is not identified by the compiler. Similar to any other compilation error, it is very significant to understand the causes of this error, so that you can easily pinpoint the issue and address it properly.

Once you can discover the reason behind the error, it can be easily resolved as demonstrated by various examples in this article.

You must have encountered the error “Cannot resolve symbol R” many times while building android projects. When you first create a new activity or new class, The R is red and Android Studio says it can’t recognize the symbol R. So you may hover over the R symbol, press Alt + Enter to import missing appropriate files. But doing so doesn’t fix this error. The letter R stands for the Resource. This error occurs because of the incapability of the build process to Sync Resource files with your projects. Usually, this happens because of the improper build of the project. 

Why There is a Need to fix “cannot resolve symbol R” in Android Studio?

The error “Cannot resolve symbol R”  in Android studio has faced mostly, when you shift your code to another Computer or send the code to another person. The “R” turns red and can’t run the Application and throw the error in “Logcat”. Most often “R cannot be resolved” error appears if there is an issue with some of your resource files. Due to this error, you are unable to build your application. That’s why we need to solve this error as it not getting away by just doing a simple restart or hitting Alt+Enter.

Now the point that comes here is how we can fix “cannot resolve symbol R” in Android Studio. So in this article, we are going to discuss six different methods to fix “cannot resolve symbol R” in Android Studio. 

Method 1

Try the sync Gradle. Just follow this path: File > Sync project with Gradle Files.

Method 2

Change Gradle version: Open your build.gradle file, search for gradle version and change the version. Say suppose you are using minSdkVersion 8 then change it to 9 and then build your project and also try to change buildToolsVersion. To change it follow this path: File > Project Structure > Modules.

After selecting the appropriate version click “OK“.

Method 3

Make sure your package name is correct in AndroidManifest.xml. Because sometimes, the R file is not generated because of package name in AndroidManifest does not match with the package module that you have. You might need to check  XML Files specifically if you have followed the correct syntax for ids. Then clean the project.

Method 4

Step 1: Clean the Project

To clean project: Click on Build > Clean project   

Step 2: Rebuild Project

Click on “Build” and click on “Rebuild Project

Method 5

You may import com.example.your_project.R file in all your activities, do note that this file is not Android.R but your project R file. All you have to do is add this line to your activities import com.example.your_project.R.

Method 6

Try Invalidate caches and restart. Just click on Files from the top left and choose the “Invalidate Caches / Restart” option.

Понравилась статья? Поделить с друзьями:
  • Error cannot find pspell
  • Error cannot find parameter
  • Error cannot find module webpack lib rules descriptiondatamatcherruleplugin require stack
  • Error cannot find module webpack cli package json
  • Error cannot find module webpack cli bin config yargs