如何从库项目中获取 AssetManager

How to get AssetManager from a library project

我试图在 Android 库项目中获取 AssetManager 形式的 class,但出现错误:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference

我是这样称呼它的:

public class RevPluginLoader extends AppCompatActivity {

    private List<String> copyPlugins() {
        AssetManager assetManager = getAssets();  // This is where it all fails
    }
}

如何获得 AssetManager

我认为你有 onCreateView

public class RevPluginLoader extends AppCompatActivity {

    private Context mContext = null; //declare a context here
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext  = this; //assign class object to context
    }

    private List<String> copyPlugins() {
        AssetManager assetManager = mContext.getAssets(); //use context here
    }
}

检查注释行

这可能会解决您的问题

我们无法在 lib 模块中添加资产文件夹

Library modules cannot include raw assets The tools do not support the use of raw asset files (saved in the assets/ directory) in a library module. Any asset resources used by an app must be stored in the assets/ directory of the app module itself.

更多详情,您可以refer here