我正在尝试从远程server解析xml
。
我的3个java
计划的代码如下:
的 1。 BillScreen.java:
package cc3012n.kalrashid;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class BillScreen extends Activity implements OnClickListener {
String baseURL = "http://www.connectingtomorrow.co.uk/xmlFiles/accounts.xml";
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button) findViewById (R.id.bGo);
tv = (TextView) findViewById (R.id.tvXML);
b.setOnClickListener(this);
}
@Override
public void onClick(View v) {
try {
URL website = new URL(baseURL);
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
HandlingXMLStuff doingWork = new HandlingXMLStuff();
xr.setContentHandler(doingWork);
xr.parse(new InputSource(website.openStream()));
String information = doingWork.getInformation();
tv.setText(information);
} catch(Exception e){
tv.setText("error");
}
}
}
2。处理XML资料:
package cc3012n.kalrashid;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class HandlingXMLStuff extends DefaultHandler {
XMLDataCollected info = new XMLDataCollected();
public String getInformation() {
return info.dataToString();
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
if (localName.equals("customer_id")) {
String customer = attributes.getValue("data");
info.setCustomer(customer);
} else if (localName.equals("table_id")) {
String table = attributes.getValue("data");
info.setTable(table);
}
}
}
第3。 XMLDataCollected.java:
public class XMLDataCollected {
String customer = null;
String table = null;
public void setCustomer (String ac){
customer = ac;
}
public void setTable(String tbl){
table = tbl;
}
public String dataToString(){
return customer + " In table Number " +table;
}
}
但是它返回了一个错误..所以它无法读取xml
文件..你能不能告诉我我做错了什么?
非常感谢提前。
答案 0 :(得分:0)
我想您忘了添加互联网访问权限。 尝试在AndroidManifest.xml
中添加以下行<uses-permission android:name="android.permission.INTERNET" />