Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.NoClassDefFoundError with all R classess when using android library

I downloaded a source code from a library for android, compiled it and I got a .jar file, I included into my project and I tried to use it but I always get a java.lang.NoClassDefFoundError, I noticed that in the jar file there are not R$XXX files, I read this post: Android Library Import delete R and tried the solutions but none worked for me.

I made my own simple library and I saw that either, the R files are not included in the jar, I have to add the .class files manually using winrar but I think I am missing something simple, I am using eclipse with ADT.

Thanks to everyone

like image 211
oware Avatar asked Apr 25 '12 01:04

oware


1 Answers

If you are creating jar files then you should not include r.java,manifeast file in the jar file.

Because the jar wont get complied during compliation and wont create any static integer during compliation time.

In android we have Android LIbrary which is similar to android project but can be included in other projects.

And if still you need to have jar file then just keep class files in jar include all your resource contain in application and from java files you can use the below code to refer the resources during runtime.

That you must use getResourseIdByName(getPackageName(), "drawable", "icon") instead of R.drawable.icon in your code. Below is the code for getResourceIdByName::

public int getResourseIdByName(String packageName, String className, String name) {
            int id = 0;
        try {
            for (int i = 0; i < Class.forName(packageName + ".R").getClasses().length; i++) {
                if(Class.forName(packageName + ".R").getClasses()[i].getName().split("\\$")[1].equals(className)) {
                    if(Class.forName(packageName + ".R").getClasses()[i] != null)
                        id = Class.forName(packageName + ".R").getClasses()[i].getField(name).getInt(Class.forName(packageName + ".R").getClasses()[i]);
                    break;
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        return id;
    }
like image 188
Shankar Agarwal Avatar answered Nov 15 '22 00:11

Shankar Agarwal