I'm trying to load a file from my classpath in a static context in Android, and every similar question on SO suggests using MyClass.class.getClassLoader().getResourcesAsStream(<filepath>)
, but this causes my app to crash before it opens.
My target SDK is 19, min SDK level is 17 and I'm using a phone running Android Lollipop
This is the part of code where I'm trying to load the file "locations.xml":
public static final String LOCATIONS_FILE_PATH = "locations.xml";
public static ArrayList<City> getLocations(String locations_file_path) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
Document document = null;
try {
builder = factory.newDocumentBuilder();
document = builder.parse(
City.class.getClassLoader().getResourceAsStream(locations_file_path));
The file is located in the same package as the java classes that is referencing it.
The error given in logcat is an IllegalArgumentException
in DocumentBuilder.parse(...)
because City.class.getClassLoader().getResourceAsStream("locations.xml"))
returns null
.