我尝试在Android中的静态上下文中加载我的类路径中的文件,而SO上的每个类似问题都建议使用MyClass.class.getClassLoader().getResourcesAsStream(<filepath>)
,但这会导致我的应用在打开之前崩溃。
我的目标SDK是19,最低SDK级别是17,我使用运行Android Lollipop的手机
这是我尝试加载文件的代码部分&#34; locations.xml&#34;:
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));
该文件与引用它的java类位于同一个包中。
logcat中给出的错误是IllegalArgumentException
中的DocumentBuilder.parse(...)
,因为City.class.getClassLoader().getResourceAsStream("locations.xml"))
会返回null
。
答案 0 :(得分:1)
我认为您需要验证在最终的apk文件中,xml文件实际上包含在您认为的位置。
Android更常见的模式是将文件放在'assets'目录中,然后使用Activity的getAssets()方法从那里加载它。
答案 1 :(得分:0)
作为getResourceAsStream
的替代方法,您可以FileInputStream
FileInputStream
请注意如果null
也返回import java.io.FileInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class DocumentBuilderDemo {
public static void main(String[] args) {
// create a new DocumentBuilderFactory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
// use the factory to create a documentbuilder
DocumentBuilder builder = factory.newDocumentBuilder();
// create a new document from input stream
FileInputStream fis = new FileInputStream("Student.xml");
Document doc = builder.parse(fis);
// get the first element
Element element = doc.getDocumentElement();
// get all child nodes
NodeList nodes = element.getChildNodes();
// print the text content of each child
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println("" + nodes.item(i).getTextContent());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
,那么很有可能正如@GreyBeardedGeek所说,xml文件实际上并未包含在您的位置期待它在最终的apk文件中。
相关代码:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<student id="10">
<age>12</age>
<name>Malik</name>
</student>
Student.xml(在您的情况下,locations.xml)
{{1}}