Android tutorial error: R cannot be resolved to a variable - android

http://developer.android.com/training/basics/firstapp/building-ui.html
I have been following this tutorial, but I have two errors, both "R cannot be resolved to a variable". I have made android apps (easy ones) in the past, and I remember this problem being fixed by checking whether or not I have an import R statement (which I don't) and whether or not the project has been cleaned before being built again (I cleaned it and I still get the error). I am at a loss as to what to do. Thanks!
*I also want to mention I did see the thread of the same title with 170 hits, and the solution of "delete the import R statement" does not apply to my problem (I don't think)
Thanks again
All code is straight from the link above, but here it is for convenience
activity_my_first.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<EditText android:id="#+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/edit_message" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send" />
</LinearLayout>
MyFirstActivity.java
package com.example.myfirstapp;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
public class MyFirstActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_first);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_my_first, menu);
return true;
}
}
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">My First App</string>
<string name="edit_message">Enter a message</string>
<string name="button_send">Send</string>
<string name="menu_settings">Menu Settings</string>
</resources>
edit: When I clean the project, I get this message in the Console:
[2012-06-29 11:12:38 - MyFirstApp] W/ResourceType( 6140): Bad XML
block: header size 91 or total size 0 is larger than data size 0
[2012-06-29 11:12:38 - MyFirstApp]
C:\Users\zhong\workspace\eclipse\MyFirstApp\res\menu\activity_my_first.xml:2:
error: Error: No resource found that matches the given name (at
'title' with value '#string/menu_settings').
edit: added a line to layout xml file <string name="menu_settings">Menu Settings</string>
Fixed cleaning project errors, but I still can't run the project from the two R errors.

I'm working my way through the same example, and had the same (or very similar) problem.
Finally I noticed that there was a tiny little red x on the manifest.xml.
Sure enough, it was complaining about this:
android:label="#string/title_activity_hello_world" >
So I added:
<string name="title_activity_hello_world">Hello World</string>
to strings.xml and now it works.

I had the same issue while following the tutorial.
Cleaning the project or cleaning the imports did not solve the problem.
How the problem was (simply) solved : I quit Eclipse and relaunched it.

2 possible things
The package name specified in the Android Manifest isn't the same as the in the Java files.
Or, your IDE hasn't generated the R.java file in the gen/ folder. Try building again (despite the error) and it will usually clear it up.
Basically the R.java file is generated for you and in the same package so you can refer to it as simply R.

I had android:text="#string/button_send"
Which gave the error: No resource found that matches the given name (at 'text' with value '#string/button_send').
I tried to solve the error using the tuturial. But the tutorial fails to tell me to write all the lines required one by one. So I miss to write "<string name="button_send">Send</string>" in the strings.xml.
After adding the previous line the error disappear! Which I believe is something similar to the original problem in this thread.
So if I had copied the whole lines from the given tutorial it may had not happened, but by typing our-self is how I think is the best way of learning.

I found the solution:
go to your project->res->menu than open the XML file there and delete this line:
android:title="#string/menu_settings"
I deleted it and it start to work,after 3 hours of the same warning in the problem section.
It even make sense when you read it, "at title with value #string/menu_settings"

Pleas confirm there is no error in
1- Project folder
2- Problem View of eclipse
3- Console
4- error log as in image

You have to make sure to
Clean your project Project-->Clean
The /res directory doesn't contain errors (some files will show up
with a red icon on the file explorer)
Your imports doesn't contain this line import android.R;
Check that in AndroidManifest.xml, the attribute package has the
correct value. <manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="your.correct.package.name"

This fixed it for me:
https://stackoverflow.com/a/3259974/1538785
Seems like eclipse likes to add an import line to java files for no reason. Go onto your java file, hit ctrl+shift+o and all the import statements will appear. Delete the line that says import andriod.R

Right click on the Project, select "Android Tools" > "Add Support Library" > "Android Support Library, revision 11" > "Install"

In my case, the problem was that I was on 64-bit Linux, and the required 32-bit libraries were not installed, meaning that the build tools could not generate R.java.
Running this command, then cleaning the project, fixed the problem:
sudo apt-get install ia32-libs

Make sure the executables (aapt etc.) in sdk/build-tools/android-xyz/* are executable if you are running the default download on your Linux box...

I had the same error trying to do the first tutorial. To get the app to run I edited MainActivity.java so it looked like this
package com.example.myfirstapp;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

Related

R.java is not being created?

I dowloaded google-play-services from sdk manager and copy pasted all the code from admob samplebut it is not working. Everything seems perfect only errors produced are R can't be resolved to a variable.
Here is a sample error
Error: No resource found that matches the given name (at 'text' with value '#string/load_interstitial').
Here is strings.xml file
<resources>
<string name="app_name">Google Ads SDK Sample</string>
<string name="ad_unit_id">INSERT_YOUR_AD_UNIT_ID_HERE</string>
<string name="load_interstitial">Load Interstitial</string>
<string name="interstitial_not_ready">Interstitial Not Ready</string>
<string name="banner_in_xml">Banner in XML</string>
<string name="banner_in_code">Banner in Code</string>
<string name="interstitial">Interstitial</string>
</resources>
Try to delete the import line import com.your.package.name.app.R, then, any resource calls such as mView= (View) mView.findViewById(R.id.resource_name); will highlight the 'R' with an error, a 'Quick fix' will prompt you to import R, and there will be at least two options:
android.R
your.package.name.R
Select the R corresponding to your package name, and you should be good to go. Hope that helps.
Or.....second region,
Each time I had a problem with R not been generated, or even disappeared, this was due to some problem in the XML layout file that prevented the application from being built.
The error in res folder cause missing of R.java filevso please check your res folder for any error.
The error may be with image too any capital letter or blank space can cause missing of R.java file.
Also check all the XML file ,error with res files only

setContentView not working in my android code

I have an error in my android code..my setContentView is not working.
my code is setContentView(R.layout.secondlayout);
Error is secondlayout cannot be resolved or it is not a feild.
Make sure that you placed the secondlayout.xml file inside res -> layout folder. Also make sure there is no error in this file. If the below line is there in your import statements, remove it.
import android.R;
Try this
import com.example.appname.R
Then, in eclipse go to project>clean , choose your project and press OK. Then wait until it is done. The clean operation regenrates R.

duplicate entry in R generated class android

i have this line
public static final int text_view222=0x7f060077;
in my R.java file duplicate and cause error in my android application , any body know how to fix this.
UPDATE :
i have aslo other R file from another projects that came when i add them as a library project ..
i face this problem before and after spending 1 hour i found that i have a TextView which it id have a space character before the id name and another TextView without the space . so in you case you have this some where in your layout files.
look at the space before the id name.
<TextView android:id="#+id/ text_view222"
...
...
..
/>
and another one without space
<TextView android:id="#+id/text_view222"
...
...
..
/>
I had the same problem. My mistake was in two xml. file i have puted the following
android:id="#+id/ETclienteNuevoDireccion"
and another:
android:id="#+id/ETclienteNuevoDireccion "
I only had a space more to the end of the line.
Try to delete the file and then clean the project. Project > Clean...
Delete your R.java file.
Do a Project --> Clean
Restart eclipse.
R.java should automatically re-build (assuming there are no errors in your project).

Must I import com.companyname.productname.R?

I'm getting R cannot be resolved error.
I read R cannot be resolved - Android error. But there android.R file.
My project compiles if .java files contain import com.companyname.productname.R statement.
If I change my productname in AndroidManifest.xml there's many errors saying package com.companyname.productname does not exist.
I tried to remove all import com.companyname.productname.R lines, but then I got package R does not exist errors on lines with R.*. How can I work around this? Thanks.
Update:
So answer is yes, I must import com.companyname.productname.R. I managed to compile project after changing productname in AndroidManifest and find-and-replace all import com.companyname.productname.R statements with new productname.
You custom R class is generated based on the package name in your AndroidManifest. So if you change it there, it will be newly generated with the new package name.
Therefore make sure that you import the correct one and remove all old imports.
If you R class is not generated, you should check the for XML errors in your resource files and/or your AndroidManifest. Fix the issues there and your R file should be generated again.

Android: Unable to instantiate activity / ClassNotFoundException

I recently published an app to the market and I'm now getting an error by some user, the app presumably crashes right when it starts. Unfortunately I can't contact him directly and the app works fine in the emulator as well as on my phone (and some friends' phones).EDIT: I guess that this happens to more than one user as I received comments in the market like "crashes on start" or "doesn't work". I only received this one stacktrace but there's no info about the configuration, device, Android version, etc.
The app is a simple soundboard, so there's really no magic involved, but I can't get why it fails on some phones. Here's the stack trace I'm getting, I hope anybody can help me out:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.my.app/com.my.app.SoundMachine}: java.lang.ClassNotFoundException: com.my.app.SoundMachine in loader dalvik.system.PathClassLoader[/mnt/asec/com.my.app-1/pkg.apk]
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
at android.app.ActivityThread.access$2300(ActivityThread.java:125)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:876)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:634)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: com.my.app.SoundMachine in loader dalvik.system.PathClassLoader[/mnt/asec/com.my.app-1/pkg.apk]
at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243)
at java.lang.ClassLoader.loadClass(ClassLoader.java:573)
at java.lang.ClassLoader.loadClass(ClassLoader.java:532)
at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
... 11 more
These are the first couple of lines from my activity:
public class SoundMachine extends Activity {
private SoundManager mSoundManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EDIT: This is the (almost) complete onCreate:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mSoundManager = new SoundManager();
mSoundManager.initSounds(getBaseContext());
int counter = 0;
for (Integer soundFile : soundFiles) {
counter++;
mSoundManager.addSound(counter, soundFile);
}
ImageButton SoundButton1 = (ImageButton) findViewById(R.id.sound1);
SoundButton1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mSoundManager.playSound(1);
}
});
SoundButton1.setOnLongClickListener(new OnLongClickListener() {
public boolean onLongClick(View v) {
saveSoundChoice(soundFiles[0], soundNames[0]);
return true;
}
});
(...more of this...)
Button StopButton = (Button) findViewById(R.id.stopbutton);
StopButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mSoundManager.stopAll();
}
});
}
And here's my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.my.app" android:installLocation="preferExternal"
android:versionCode="9" android:versionName="1.2">
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".SoundMachine" android:label="#string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-sdk android:minSdkVersion="3" android:targetSdkVersion="8" />
</manifest>
So all possible errors I already read about here and in some forums don't apply to my app.
The activity is present in the manifest.
The super-method is called in the overriden method.
The ContentView is set before accessing elements in the view.
I know it's hard to pinpoint the source of an error without being able to reproduce it, but maybe somebody has a bright idea and can help me out.
Some questions:
Do I need the "intent"-part in the manifest? Eclipse created it when I created the project. (Yes, according to Mayra)
Should the super-method be called where it is? (Yes, according to Mayra)
EDIT: The main question that remains now is: How come the path in PathClassLoader is different from my package-name? The page John J Smith posted seems to deal with the same problem, but I don't understand the fix that was applied there.
Thanks, Select0r
I solved this problems by selecting :
Project->properties->order and export
select the all external jar files.
clean and build it solved the issue
Since ADT update to revision 22 (May 2013) you have to check "Android Private Libraries" check box in Project -> Properties -> Java Build Path -> Order and Export in Eclipse for your older projects to get rid of this exception ...
I just got the same error (Unable to instantiate activity...) with Opera Mini. Opera Mini was on SD card (moved to SD card in the app setting). The error seems to be related to the fact that I swapped the SD card yesterday. The device was shutdown, I copied all data from the old card over to the new card (with cp -a) and then inserted the new card and started the device again. Everything seems to work as expected, but I see now that all apps on the SD card crashes with the same error.
Device: HTC Desire HD (Android 2.2)
Old SDHC card: SanDisk 8GB class 4
New SDHC card: Kingston 16GB class 4
So I would say that this is a an Android bug and not something that can be fixed by app developers.
Also see:
http://android-developers.blogspot.com/2010/07/apps-on-sd-card-details.html
It has always been the case that when you swap SD cards on an Android device, if you physically copy the contents of the old card to the new one, the system will use the data on the new card as if nothing had changed. This is also true of apps which have been installed on the SD card."
This seems to be incorrect.
This happened to me when I refactored one of my package names and the refactor tool removed the leading "." from all of my activity names. so in the AndroidManifest.xml, I had to change android:name="MyActivity" to android:name=".MyActivity"
hope this helps someone, I just wasted a bunch of time o
This doesn't apply to the OP's question, but it did to mine and it took me quite some time to figure it out: when using the Google Maps API, make sure you've included the library declaration in the application manifest.
For instance:
public class MyActivity extends MapActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
}
In AndroidManifest.xml:
<application>
<uses-library android:name="com.google.android.maps" />
<activity android:name="MyActivity" android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
I don't know why the path in the PathClassLoader is different to your package name but when testing on the emulator try forcing a close then run it again, as per this link
I had the same problem of you and, after hours of search, I discovered something interesting. I'll try to expose that as clearly as possible:
I created a project with a package called "myapp.sound" containing the activity. Program ran normally;
I renamed that package calling it "app.soundapp" and program still ran normally.
However, in the manifest.xml file of the program there was something strange: the name of package was the old "myapp.sound". I changed manifest with correct new name and, from that moment on, our error occured. I don't know why, but seems that the "package name changer" of Eclipse doesn't update all the dependencies. If it's not strictly necessary, don't rename the package containing activity.
Maybe, to solve your problem you have to create a new project and copy inside it all your java class.
Look at the package defined at the top of the manifiest file and make sure that it matches the package where you class is defined.
My problem was that I did not have matching package names.
Also enusre that you have a folder named "libs" with an 's'. Put all of you jar files that you added inside it and add to build path.
This problem can also occur if you have a constructor with one or more parameters in your activity class.
This problem might exist when you change the name of your class and update the manifest file and the manifest file is not updated on the emulator. Try uninstall the application from emulator and then reinstall it. This will work.
I was coming across this problem when I was including java Projects in my buildpath for my android project targeting JavaSE-1.7.
For some reason my emulator would not throw a class not found if the java project it was including was originally created targeting JavaSE-1.6. Eclipse would give me a warning "Build path specifies execution environment JavaSE-1.6. There are no JREs installed in the workspace that are strictly compatible with this environment." But the Android emulator would launch and I would not get a classnotfoundexception
So if you are including projects that target JavaSE-1.7, remake them targeting JavaSE-1.6 and this may solve your problem.
Good luck!
Similar to Bobf Cali, I first saw this error after renaming my base package to change the "example" section. To fix it, I had to delete my gen and bin directories, clean the project, and rebuild.
Note depending on what version of the eclipse android plugin you're using (if any), you may also have to update activity names in your AndroidManifest.xml
Saw the same error message after doing a simple upgrade of my app. Fixed it by doing this:
Project->Build automatically OFF
Project->Clean->Selcting my project
Then I did a new export of my signed app, and it worked.
Are you sure your package name is unique? I don't know what happen if the user has another app using the same package name, but maybe it can cause strange errors like this.
EDIT: I just saw this page, it remembers me I already had this problem when downloading an app from the Android market. The app crashed on startup, I tried a lot of times but I always ended with the same result. Then I tried to uninstall the app, reinstall it, and everything worked fine. I'm still using it today and the problem never happened again.
On my link, you can also see that they reproduced your error by making the app unreachable (unmount SD), so it's definitely not a problem with your code.
Check out this article: http://www.androidguys.com/2010/05/22/storing-apps-sd-froyo/ which explains the limitations of storing apps on SD cards. If your users have their SD card mounted by a computer, that might make the SoundMachine class invisible. And I wonder if the cp command fails (perja's attempt to fix) because it might change the ownership of the files such that the userid of the app and the ownership of the files don't match anymore.
I had the same issue in a recent Android project. The problem turned out to be pretty simple yet it was hard to locate. This happened to me then I refactored the package name of the entry point activity of the app. This created a conflict with the gen/.../R.java file, since the package there was not refactored. Eclipse did not complain, but at runtime i got the same error you posted: could not instantiate... classNotFoundException...
Lesson learned from this: do NOT refactor the package name that holds your main activity!
Hope this helps you or anyone breaking his/her head over this error!
I solved this and could locate the causes:
-The Manifest will be corrupt. Even if the package-structure is right and every single data was written down correctly the activity will not be found.
-R will be in the package-structure which was first declared before renaming.
-The run-configurations are setup with the wrong package of R. So the activity can't be found.
What we have tried:
-Manually editing the run-configs via export/import
-Manually renaming the package-structure
-Manually renaming the R-package-structure
-Deleting the run-config (it will be rebuild if you try to start the app)
Solution:
Try to setup a new project without reusing your manifest. I have tried to reuse it and got the same problems all over again. So after the main cause has to be the corrupt manifest.
I hope this helps!
Make sure your /src dir is listed in your projects>properties>java build path>source
Maybe it is too late to solve your problem but hopefully it will help someone else.
I had a similar problem and after many tries, I decided to delete R.java. That did the trick.
This error can also occur when you (at the project level) incorrectly Import > Android > Existing Android Code Into Workspace, via Eclipse. In my case, this resulted in an empty "src" folder, but then I noticed new folder starting with "java" at the root and continuing with the package path (i.e. com/zyzcorp/...), leading to the MainActivity.java file.
To test what I thought may fix the problem, I copied the com.*.MainActivity.java file into the src folder, refreshed, cleaned, and restarted Eclipse. I was able to build and run the app on the target device.
I don't see anything obviously wrong. All I can say is to try to test it in as many different configurations as possible.
Test it in the emulator for every possible SDK level, follow the guidelines for testing on different sized screens (although that doesn't seem to be your problem).
Try to test it on a phone from each of the major providers, if you can find friends that have them: HTC Sense, Motoblur, etc.
If you only get one report, it might just be something screwy with that guys device. See if you get other, similar reports that add more data.
You had renamed the package anytime? This normally happens if the package was renamed after creation. Following link should be helpfull in that case http://code.google.com/p/android/issues/detail?id=2824. If this is not the case,please post your complete manifest file.
I has the same problem but this fixed it. In my androidmanifest.xml i had this line called android:name = myappnameActivity. Although my class name was just myappname. Hence i took off the Activity part in the xml file and all was fine.
I was just having a problem with this myself, so I want to bring up what caused the problem for me. I had just included some new libraries setting up expansion APKs. The libraries are dependant on each other and I was only including one of them in my properties > android > libraries.
So this could happen if the user is missing a library on their phone that most users have.
It showed ClassNotFoundException on my main activity because it implements a class which was in the missing library.
I had 5 different packages. And for some reason the compiler was looking for the activity on the wrong package.
So I switched my activity and all the class that inherits the activity to the package that it was looking into.
I got the name of the package it was looking for in the beginning of the logcat.
I fix this problem by deleting "bin" and "gen" folder, and rebuilding project.
I had the same problem
I solved it by
uncheck the Android Dependencies from Project--> Properties-->Java builder Path-->android dependencies
Delete BIN and GEN folder files. Rebuild, everything should work. Check if theres another error below the "unable to instantiate", sometimes another error is firing this (activity cant load because of something even if its class has been found.
What I had to do is just re-do the building/exporting process with no modification to the code whatsoever. It worked for me, which I did was to export it two times. On my first export, the build APK has lower file size and the second export (with no any modification to the code/configuration) produced a slightly larger file size (about 200KB diff).
This bug in building is really costly, kills you in front of your manager, and should be really fixed by Android/Eclipse team. Kind of sucks
After spending 6 hours on this issue, found that it was a silly mistake. Apparently if you're defining your Application class in android manifest and you have enabled MultiDex enabled, you have to add that on Application Class. Here is example from my app.
It only gave me error on devices running on < Android 5.0
AndroidManifest.xml
......
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:name=".AppClass"
.........
AppClass.java
class AppClass : Application() {
override fun onCreate() {
super.onCreate()
}
override fun attachBaseContext(base: Context) {
super.attachBaseContext(base)
MultiDex.install(this) //Don't forget this !!!!
}
}

Categories

Resources