TL;DR, if you get the error "package R does not exist", possible reasons are
- some error in the XML resource files
-> fix XML errors
- the current package is different from the
R
package (see package
attribute in AndroidManifest.xml)
-> import R
class, e.g. import com.example.android.R;
-> or use the appropriate package in your source, e.g. package com.example.android;
-> or change the package attribute in AndroidManifest.xml to
<manifest xmlns:android="..." package="com.example.android" ...>
, if that's appropriate
- the used
R
ids are from the system resources
-> do not import android.R
, but prefix the offending ids with android.
, e.g. android.R.layout.simple_list_item_2
You may import android.R
instead of prefixing the ids of course, but then you cannot import the application R
class anymore and must prefix the application ids, e.g. com.example.android.R.id.main_menu
.
The R
class is generated automatically from the application's
resources. It contains the id
s for these resources and is contained
in the package named in the
<manifest>
tag in the corresponding AndroidManifest.xml
file.
If there are no errors in the resource XML files, the R.java
source
will be generated in a package subdirectory below gen/
and compiled.
There is another R
class located in the android
package. This android.R
class contains some nested classes, which in turn contain id
s and other values for system resources.
To use a class in Java, you must name the class with the whole
package, e.g.
java.util.List<Object> list = new java.util.ArrayList<Object>();
or import the class and then use it without package
import java.util.List;
import java.util.ArrayList;
List<Object> list = new ArrayList<Object>();
You can also use a class without naming the package, if both the
current class and the used class are in the same package, e.g.
package com.example.android;
public class A {
/* ... */
}
package com.example.android;
public class B {
public void useA() {
A a = new A();
}
}