zobot1
zobot1

Reputation: 141

R cannot be resolved to a variable

I would like to fix this error

R cannot be resolved to a variable

I looked up many answers, but I could not get the right one; I tried everything. Could any one help me?

My main activity which is automatically created. The error is showing for the three lines starting at case R.id.button1::

package de.vogella.android.temprature1;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

public class Convert extends Activity {
    private EditText text;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        text = (EditText) findViewById(R.id.editText1);
    }

    // This method is called at button click because we assigned the name to the
    // "On Click property" of the button
    public void myClickHandler(View view) {
    switch (view.getId()) {
        case R.id.button1:
            RadioButton celsiusButton = (RadioButton) findViewById(R.id.radio0);
            RadioButton fahrenheitButton = (RadioButton) findViewById(R.id.radio1);
            if (text.getText().length() == 0) {
                Toast.makeText(this, "Please enter a valid number",
                Toast.LENGTH_LONG).show();
                return;
            }

            float inputValue = Float.parseFloat(text.getText().toString());
            if (celsiusButton.isChecked()) {
                text.setText(String.valueOf(convertFahrenheitToCelsius(inputValue)));
            } else {
                text.setText(String.valueOf(convertCelsiusToFahrenheit(inputValue)));
            }

            // Switch to the other button
            if (fahrenheitButton.isChecked()) {
                fahrenheitButton.setChecked(false);
                celsiusButton.setChecked(true);
            } else {
                fahrenheitButton.setChecked(true);
                celsiusButton.setChecked(false);
            }
            break;
        }
    }

    // Converts to celsius
    private float convertFahrenheitToCelsius(float fahrenheit) {
        return ((fahrenheit - 32) * 5 / 9);
    }

    // Converts to fahrenheit
    private float convertCelsiusToFahrenheit(float celsius) {
        return ((celsius * 9) / 5) + 32;
    }
}

my main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:background="@color/myColor">
    <EditText android:layout_height="wrap_content" android:id="@+id/editText1"
        android:layout_width="match_parent" android:inputType="numberDecimal|numberSigned"></EditText>
    <RadioGroup android:layout_height="wrap_content" android:id="@+id/radioGroup1"
        android:layout_width="match_parent">
        <RadioButton android:layout_width="wrap_content"
            android:id="@+id/radio0" android:layout_height="wrap_content"
            android:text="@string/celsius" android:checked="true"></RadioButton>
        <RadioButton android:layout_width="wrap_content"
            android:id="@+id/radio1" android:layout_height="wrap_content"
            android:text="@string/fahrenheit"></RadioButton>
    </RadioGroup>
    <Button android:id="@+id/button1" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="@string/calc"
        android:onClick="myClickHandler"></Button>
</LinearLayout>

my string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, Convert!</string>
    <string name="app_name">de.vogella.android.temprature1</string>
<string name="myClickHandler">myClickHandler</string>
<string name="celsius">to Celsius</string>
<string name="farenheit">to Farenheit</string>
<string name="calc">Calculate</string>
</resources>

Upvotes: 14

Views: 107274

Answers (29)

kemal
kemal

Reputation: 1

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

Upvotes: 0

sukhwinder
sukhwinder

Reputation: 1

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.

Upvotes: 0

wired00
wired00

Reputation: 14438

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

Upvotes: -1

Oualid Ait wafli
Oualid Ait wafli

Reputation: 1

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.

Upvotes: 0

user1783074
user1783074

Reputation: 9

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.

Upvotes: 0

Vinoj John Hosan
Vinoj John Hosan

Reputation: 6863

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

Upvotes: 0

alain.filterstream
alain.filterstream

Reputation: 13

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

Upvotes: 0

android developer
android developer

Reputation: 116332

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.

Upvotes: 17

kolyaseg
kolyaseg

Reputation: 543

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.

Upvotes: -1

user3154700
user3154700

Reputation: 111

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

Upvotes: 2

Ash
Ash

Reputation: 9351

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.

Upvotes: 0

Tiago Duarte
Tiago Duarte

Reputation: 3376

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

Upvotes: 1

bheatcoker
bheatcoker

Reputation: 539

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.

Upvotes: 2

user2427915
user2427915

Reputation: 1

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

Upvotes: 0

makkasi
makkasi

Reputation: 7288

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

Upvotes: 4

Abilash
Abilash

Reputation: 1163

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

Upvotes: 0

Michael Mossman
Michael Mossman

Reputation: 91

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.

Upvotes: 4

midiwriter
midiwriter

Reputation: 426

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.

Upvotes: 4

Dina
Dina

Reputation: 11

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.

Upvotes: 1

shreeraj salunkhe
shreeraj salunkhe

Reputation: 1

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.

Upvotes: 0

Bhavin2887
Bhavin2887

Reputation: 180

Just look in to your header files there will be:

import somefile.R;

Just remove that line and that's it.

Upvotes: 1

gaurav
gaurav

Reputation: 62

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

Upvotes: -2

theCleverBulldog
theCleverBulldog

Reputation: 99

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.

Upvotes: 9

robbycandra
robbycandra

Reputation: 780

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.

Upvotes: 1

scar
scar

Reputation: 191

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

Upvotes: 1

NuSkooler
NuSkooler

Reputation: 5525

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.

Upvotes: 0

davidmarkscott
davidmarkscott

Reputation: 191

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.

Upvotes: 5

ivan
ivan

Reputation: 191

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

Upvotes: 19

Mark Mooibroek
Mark Mooibroek

Reputation: 7696

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

Upvotes: 0

Related Questions