我试图在android中创建XML解析器,xml文件在我的localhost服务器上。我将URL设置为localhost-ed xml文件时出现NullPointerException错误,但是当我将xml文件上传到dropbox时,我的解析器正在工作。
错误消息:
...
Caused by: java.lang.NullPointerException
at java.io.StringReader.<init>(StringReader.java:47)
at com.learn.dhemas.franchise.XMLParser.getDomElement(XMLParser.java:74)
at com.learn.dhemas.franchise.fragmentLowongan$getDataOrder.doInBackground(fragmentLowongan.java:72)
...
XMLParser的,JAVA:
public class XMLParser {
// constructor
public XMLParser() {
}
/**
* Getting XML from URL making HTTP request
* @param url string
* */
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
/**
* Getting XML DOM element
* @param XML string
* */
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return doc;
}
/** Getting node value
* @param elem element
*/
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
/**
* Getting node value
* @param Element node
* @param key string
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}
和我的活动代码行(片段类):
...
@Override
protected Void doInBackground(Void... params) {
//Call parser
XMLParser parser = new XMLParser();
//String xml = parser.getXmlFromUrl("https://drive.google.com/uc?export=download&id=0B5bM7szIFKrpY2lPRHdCUUNscjA");
String xml = parser.getXmlFromUrl("http://localhost/GetData.xml");
Document doc = parser.getDomElement(xml);
...
任何帮助都将是apreciated
答案 0 :(得分:0)
所以问题是,当我从应用程序指向localhost时,它将是模拟器上的localhost,而不是我的Web服务器中的localhost。要解决这个问题,我只需要创建一个虚拟本地网络,并为我的计算机提供一个IP地址,这样我就可以从模拟器访问IP。
答案 1 :(得分:-2)
您可以尝试在浏览器中打开网址:http://localhost/GetData.xml