Search code examples
androidandroid-resources

Cannot resolve symbol raw when the folder is empty


Why is it giving me "cannot resolve symbol raw" when i try to access the folder with the following code Field[]fields=R.raw.class.getFields();

The same code works when i add any file to the raw folder. The folder is in "res" directory.

Note: I have tried using the complete package name also.


Solution

  • When you create an Android resource folder such as layout, drawable, mipmap, etc.. The android will create a file named R.java. You can find it in

    app\build\generated\source\r\degug\your\app\package\name\R.java.

    It basically a normal java file which has been generated by android automatically for referring resources by ids in our code.

    R.java

    public final class R {
        public static final class layout{
            public static final int main_activity=0x7f0a0000;
            public static final int login_activity=0x7f0a0001;
        }
        public static final class drawable{
            public static final int ic_add=0x7f0a0000;
            public static final int ic_edit=0x7f0a0001;
        }
        public static final class mimap{
            public static final int ic_launcher=0x7f0b0000;
        }
    }
    

    From Android official site:

    Resources are the additional files and static content that your code uses, such as bitmaps, layout definitions, user interface strings, animation instructions, and more.

    It means res folder is read-only and you cannot modify (add, update, delete) the content side.

    Back to your problem, when you create raw folder but do not put any files inside and android know that in the runtime you cannot modify this folder as well, so why we need to create a refer to the raw resources anymore. It does not make sense. Because there is no raw class in R.java so your compiler display the error.

    cannot resolve symbol raw
    

    But if you create a file and put into raw folder, then after build process, a class raw will be created in R.java file.

    public final class R {
        public static final class layout{
            public static final int main_activity=0x7f0a0000;
            public static final int login_activity=0x7f0a0001;
        }
        public static final class drawable{
            public static final int ic_add=0x7f0a0000;
            public static final int ic_edit=0x7f0a0001;
        }
        public static final class mimap{
            public static final int ic_launcher=0x7f0b0000;
        }
    
        public static final class raw {
            public static final int sound=0x7f0b0000;
        }
    }
    

    And now the error gone.