How to load assets (text files) from a Android Library (AAR)?

Viewed 1093

I created an Android Library (AAR) with some text files inside the src/main/assets folder. The text files are used only in the library and not in the application that uses the library, which is in the same Android Studio project. It should be simple to access these text files, but I can't do it.

Each text file contains many lines that are to be parsed into a list which will only be used by the library. Using a Context object, it should be easy; however I try to load the files in a static context and I don't have access to any Context object. Here is some code I tried:

static {

    InputStream is = null;
    try {

        is = Resources.getSystem().getAssets().open("assets/stopwords.txt");

        Request.stopwords = new ArrayList<>();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String stopword;

        while ((stopword = reader.readLine()) != null) {
            Request.stopwords.add(stopword);
        }
    }
    catch (IOException e) {

        logger.error("Could not open input stream");
        logger.error("Exception: {}", e.getMessage());
    }
    catch (Exception e) {

        logger.error("Input stream opened but something else happened");
        logger.error("Exception: {}", e.getMessage());
    }
    finally {

        try {
            is.close();
        } catch (Exception e) {

            logger.error("Could not close input stream");
            logger.error("Exception: {}", e.getMessage());
        }
    }
}

All my assets are in src/main/assets. Here is the library's build.gradle:

apply plugin: 'com.android.library'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"

    defaultConfig {
        minSdkVersion 24
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    sourceSets {
        main {
            assets.srcDirs = ['src/main/assets']
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'sk.baka.slf4j:slf4j-handroid:1.7.25-3'
    compile 'org.ejml:ejml-all:0.31'
}

I guess my question is: how can I bundle the assets into the AAR file and then access them from the library? The application that uses the library doesn't even need to know that these resources exist because they are internal to the library. Thanks!

0 Answers
Related