您好,我正在练习从XML中获取价值
我从教程中复制它但我总是进入catch区并将text设置为null
这是代码:
MainActivity.java
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
/* Create a new TextView to display the parsingresult later. */
TextView tv = new TextView(this);
try {
/* Create a URL we want to load some xml-data from. */
URL url = new URL("http://www.anddev.org/images/tut/basic/parsingxml/example.xml");
/* Get a SAXParser from the SAXPArserFactory. */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
/* Get the XMLReader of the SAXParser we created. */
XMLReader xr = sp.getXMLReader();
/* Create a new ContentHandler and apply it to the XML-Reader*/
ExampleHandler myExampleHandler = new ExampleHandler();
xr.setContentHandler(myExampleHandler);
/* Parse the xml-data from our URL. */
xr.parse(new InputSource(url.openStream()));
/* Parsing has finished. */
/* Our ExampleHandler now provides the parsed data to us. */
ParsedExampleDataSet parsedExampleDataSet =
myExampleHandler.getParsedData();
/* Set the result to be displayed in our GUI. */
tv.setText(parsedExampleDataSet.toString());
} catch (Exception e) {
/* Display any Error to the GUI. */
tv.setText("Error: " + e.getMessage());
}
/* Display the TextView. */
this.setContentView(tv);
}
}
这是Logcat:
11-13 12:02:40.689: W/System.err(1061): android.os.NetworkOnMainThreadException
11-13 12:02:40.749: W/System.err(1061): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
11-13 12:02:40.789: W/System.err(1061): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
11-13 12:02:40.789: W/System.err(1061): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
11-13 12:02:40.809: W/System.err(1061): at java.net.InetAddress.getAllByName(InetAddress.java:214)
11-13 12:02:40.859: W/System.err(1061): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
11-13 12:02:40.859: W/System.err(1061): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
11-13 12:02:40.879: W/System.err(1061): at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:341)
11-13 12:02:40.879: W/System.err(1061): at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
11-13 12:02:40.952: W/System.err(1061): at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
11-13 12:02:40.952: W/System.err(1061): at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
11-13 12:02:40.959: W/System.err(1061): at libcore.net.http.HttpEngine.connect(HttpEngine.java:310)
11-13 12:02:40.959: W/System.err(1061): at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
11-13 12:02:41.009: W/System.err(1061): at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
11-13 12:02:41.029: W/System.err(1061): at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273)
11-13 12:02:41.029: W/System.err(1061): at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168)
11-13 12:02:41.029: W/System.err(1061): at java.net.URL.openStream(URL.java:462)
11-13 12:02:41.099: W/System.err(1061): at com.example.xmltestfinal1_1.MainActivity.onCreate(MainActivity.java:38)
11-13 12:02:41.099: W/System.err(1061): at android.app.Activity.performCreate(Activity.java:5008)
11-13 12:02:41.152: W/System.err(1061): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
11-13 12:02:41.179: W/System.err(1061): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
11-13 12:02:41.179: W/System.err(1061): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
11-13 12:02:41.239: W/System.err(1061): at android.app.ActivityThread.access$600(ActivityThread.java:130)
11-13 12:02:41.289: W/System.err(1061): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
11-13 12:02:41.289: W/System.err(1061): at android.os.Handler.dispatchMessage(Handler.java:99)
11-13 12:02:41.299: W/System.err(1061): at android.os.Looper.loop(Looper.java:137)
11-13 12:02:41.359: W/System.err(1061): at android.app.ActivityThread.main(ActivityThread.java:4745)
11-13 12:02:41.359: W/System.err(1061): at java.lang.reflect.Method.invokeNative(Native Method)
11-13 12:02:41.399: W/System.err(1061): at java.lang.reflect.Method.invoke(Method.java:511)
11-13 12:02:41.409: W/System.err(1061): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-13 12:02:41.442: W/System.err(1061): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-13 12:02:41.449: W/System.err(1061): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:1)
您正在从应用的主(UI)线程访问网络,这在最新版本的Android中是不允许的。这就是Logcat输出中NetworkOnMainThreadException
的原因。如果网络运行缓慢,您的用户可能会看到“应用程序无响应”警告,结果您的应用程序可能会被杀死。
您需要使用AsyncTask在后台线程中下载和解析XML线程。这使得您的应用程序可以在后台线程处理XML数据时与用户进行交互。如果您需要更多详细信息,有很多关于SO的AsyncTask
教程可以提供帮助。
答案 1 :(得分:1)
在这一行
xr.parse(new InputSource(url.openStream()));
您正在 MAIN 主题
中执行网络操作长时间操作应该在后台线程中执行,如下所示
实现这一目标。您应该使用AsyncTask
您可以在onPostExecute()
另外,
如果要在后台线程的UI对象中设置数据,请使用Handler
对象
答案 2 :(得分:0)
`public void demoxml()
{
AssetManager manager = getAssets();
InputStream stream;
try {
XMLDOMParser parser = new XMLDOMParser();
stream = manager.open("game.xml");
Document doc = parser.getDocument(stream);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Log.i("DocumentBuilder--->", "Document Building is complete--> ready for parsing");
// Document doc = dBuilder.parse("http://myinfo.comuf.com/ram/game.xml");
doc.getDocumentElement().normalize();
Log.i("Document--('-')->","it is open");
//get all tabs
NodeList nodeList=doc.getElementsByTagName("string");
int lengthq = nodeList.getLength();
Log.i("Node length is ", ""+String.valueOf(lengthq));
NodeList nl = doc.getElementsByTagName("array");
int length = nl.getLength();
Log.i("Node length is ", ""+String.valueOf(length));
for(int i=0; i<length; i++ ){
Node currentNode = nl.item(i);
// RSSItem item = new RSSItem();
Log.i("Main Node-->"+i+"---",currentNode.toString());
NodeList nchild = currentNode.getChildNodes();
int clength = nchild.getLength();
//get the required element from each item
for(int j=1; j<clength; j=j+2){
Node thisNode = nchild.item(j);
String theString;
String nodeName = thisNode.getNodeName();
theString = nchild.item(j).getFirstChild().getNodeValue();
Log.i("('-')ChildNode--->"+nodeName+"="+j+"---",theString.toString());
}
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}`