Home » Android » Accessing resources from Android library project?

Accessing resources from Android library project?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am trying to build a library. I have an Android library project and some resources under the res directory that I want to access in the library project’s code. The Android docs says:

source code in the library module can access its own resources through its R class

But I just can’t figure out how to do this. Because it’s a library and intended to be used from other applications, not run itself, I have no Activity, so I can’t get a Context to use getResources(). How can I access these resources explicitly without a context?

How to&Answers:

Without an Activity, it doesn’t seem possible to use the R class. If you have a test application within your library, the test application will be able to access R, but not from the lib itself.

Still, you can access the resources by name.
For instance, I have a class like this inside my library,

public class MyContext extends ContextWrapper {
  public MyContext(Context base) {
    super(base);
  }

  public int getResourceId(String resourceName) {
    try{
        // I only access resources inside the "raw" folder
        int resId = getResources().getIdentifier(resourceName, "raw", getPackageName());
        return resId;
    } catch(Exception e){
        Log.e("MyContext","getResourceId: " + resourceName);
        e.printStackTrace();
    }
    return 0;
  }
}

(See https://stackoverflow.com/a/24972256/1765629 for more information about ContextWrappers)

And the constructor of an object in the library takes that context wrapper,

public class MyLibClass {
  public MyLibClass(MyContext context) {
    int resId = context.getResourceId("a_file_inside_my_lib_res");
  }
}

Then, from the app that uses the lib, I have to pass the context,

public class MyActivity extends AppCompatActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    MyLibClass a = new MyLibClass(new MyContext(this));
  }
}

MyContext, MyLibClass, and a_file_inside_my_lib_res, they all live inside the library project.

I hope it helps.