Issue
My aim is to write an android Library that can list all the resources (layouts, drawables. ids, etc.) of the caller application. The caller application need to pass to the library, nothing more than App Name or the package namespace. E.g:
The MyLibrary function:
public void listDrawables(String namespace) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
String resourceNameSpace = namespace + ".R";
String drawableNamespace = resourceNameSpace + ".drawable";
final Class drawableClass = Class.forName(drawableNamespace);
Object drawableInstance = drawableClass.newInstance();
final Field[] fields = drawableClass.getDeclaredFields();
for (int i = 0, max = fields.length; i < max; i++) {
final int resourceId;
try {
resourceId = fields[i].getInt(drawableInstance);
// Use resourceId further
} catch (Exception e) {
continue;
}
}
The caller code (From the App Activity, say com.example.sample.MainActivity.java
)
mylibrary.listDrawables("com.example.sample");
I have setup the MyLibrary as a dependent android library for the Sample app.
When this is run, I get this exception inside library at the Class.forName
statement:
java.lang.ClassNotFoundException: com.example.sample.R.drawable
I am not able to understand fully, why library can't refer to the class. May be I missed a basic lesson in Java classpath and how build works, but isn't the class already loaded when library runs?
I would also like to know id there is any alternative way to list resources in an external library.
Solution
Since Drawable is a inner class, you need to access it by using $
.
String resourceNameSpace = namespace + ".R";
String drawableNamespace = resourceNameSpace + "$drawable";
Answered By - Abhigyan Raghav
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.