使用 Android Studio 阅读 Web XML
Read Web XML using Android Studio
我正在开发一个应用程序来从网络读取 XML 文件并将其解析为文本。
我尝试了以下代码,它与 eclipse 上的普通项目完美配合(对 Android Studio 进行了细微更改):
package ali.androidtest;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void getData(View v)throws IOException
{
System.out.println("hello");
URL xmlUrl = new URL("http://api.openweathermap.org/data/2.5/weather?q=dallas%20ga&units=metric&mode=xml");
System.out.println("hi");
InputStream in = xmlUrl.openStream();
Document doc = parse(in);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("temperature");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("Temperature: " + eElement.getAttribute("value"));
}
}
}
public static Document parse (InputStream is) {
Document ret = null;
DocumentBuilderFactory domFactory;
DocumentBuilder builder;
try {
domFactory = DocumentBuilderFactory.newInstance();
domFactory.setValidating(false);
domFactory.setNamespaceAware(false);
builder = domFactory.newDocumentBuilder();
ret = builder.parse(is);
}
catch (Exception ex) {
System.err.println("unable to load XML: " + ex);
}
return ret;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
getData 是 link 一个按钮。
当我在 android studio 中使用此代码进行开发时出现错误:
02-12 23:39:15.757 22930-22930/ali.androidtest I/ViewRootImpl﹕ ViewRoot's Touch Event : ACTION_DOWN
02-12 23:39:15.811 22930-22930/ali.androidtest I/ViewRootImpl﹕ ViewRoot's Touch Event : ACTION_UP
02-12 23:39:15.816 22930-22930/ali.androidtest I/System.out﹕ hello
02-12 23:39:15.827 22930-22930/ali.androidtest I/System.out﹕ hi
02-12 23:39:15.840 22930-22930/ali.androidtest D/libc-netbsd﹕ [getaddrinfo]: hostname=xxxxx; servname=(null); cache_mode=(null), netid=0; mark=0
02-12 23:39:15.840 22930-22930/ali.androidtest D/libc﹕ getaddrinfo called from pid =22930
02-12 23:39:15.840 22930-22930/ali.androidtest D/libc-netbsd﹕ [getaddrinfo]: ai_addrlen=0; ai_canonname=xxxxx; ai_flags=4; ai_family=0
02-12 23:39:15.852 22930-22930/ali.androidtest D/AndroidRuntime﹕ Shutting down VM
02-12 23:39:15.866 22930-22930/ali.androidtest E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: ali.androidtest, PID: 22930
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View.onClick(View.java:4015)
at android.view.View.performClick(View.java:4764)
at android.view.View$PerformClick.run(View.java:19833)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5292)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View.onClick(View.java:4010)
at android.view.View.performClick(View.java:4764)
at android.view.View$PerformClick.run(View.java:19833)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5292)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at java.net.InetAddress.lookupHostByName(InetAddress.java:426)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:255)
at java.net.InetAddress.getAllByName(InetAddress.java:218)
at com.android.okhttp.HostResolver.getAllByName(HostResolver.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:373)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:323)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:190)
at java.net.URL.openStream(URL.java:470)
at ali.androidtest.MainActivity.getData(MainActivity.java:32)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View.onClick(View.java:4010)
at android.view.View.performClick(View.java:4764)
at android.view.View$PerformClick.run(View.java:19833)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5292)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ali.androidtest" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
已修复使用异步获取数据的问题。
我正在开发一个应用程序来从网络读取 XML 文件并将其解析为文本。 我尝试了以下代码,它与 eclipse 上的普通项目完美配合(对 Android Studio 进行了细微更改):
package ali.androidtest;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void getData(View v)throws IOException
{
System.out.println("hello");
URL xmlUrl = new URL("http://api.openweathermap.org/data/2.5/weather?q=dallas%20ga&units=metric&mode=xml");
System.out.println("hi");
InputStream in = xmlUrl.openStream();
Document doc = parse(in);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("temperature");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("Temperature: " + eElement.getAttribute("value"));
}
}
}
public static Document parse (InputStream is) {
Document ret = null;
DocumentBuilderFactory domFactory;
DocumentBuilder builder;
try {
domFactory = DocumentBuilderFactory.newInstance();
domFactory.setValidating(false);
domFactory.setNamespaceAware(false);
builder = domFactory.newDocumentBuilder();
ret = builder.parse(is);
}
catch (Exception ex) {
System.err.println("unable to load XML: " + ex);
}
return ret;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
getData 是 link 一个按钮。 当我在 android studio 中使用此代码进行开发时出现错误:
02-12 23:39:15.757 22930-22930/ali.androidtest I/ViewRootImpl﹕ ViewRoot's Touch Event : ACTION_DOWN
02-12 23:39:15.811 22930-22930/ali.androidtest I/ViewRootImpl﹕ ViewRoot's Touch Event : ACTION_UP
02-12 23:39:15.816 22930-22930/ali.androidtest I/System.out﹕ hello
02-12 23:39:15.827 22930-22930/ali.androidtest I/System.out﹕ hi
02-12 23:39:15.840 22930-22930/ali.androidtest D/libc-netbsd﹕ [getaddrinfo]: hostname=xxxxx; servname=(null); cache_mode=(null), netid=0; mark=0
02-12 23:39:15.840 22930-22930/ali.androidtest D/libc﹕ getaddrinfo called from pid =22930
02-12 23:39:15.840 22930-22930/ali.androidtest D/libc-netbsd﹕ [getaddrinfo]: ai_addrlen=0; ai_canonname=xxxxx; ai_flags=4; ai_family=0
02-12 23:39:15.852 22930-22930/ali.androidtest D/AndroidRuntime﹕ Shutting down VM
02-12 23:39:15.866 22930-22930/ali.androidtest E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: ali.androidtest, PID: 22930
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View.onClick(View.java:4015)
at android.view.View.performClick(View.java:4764)
at android.view.View$PerformClick.run(View.java:19833)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5292)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View.onClick(View.java:4010)
at android.view.View.performClick(View.java:4764)
at android.view.View$PerformClick.run(View.java:19833)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5292)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at java.net.InetAddress.lookupHostByName(InetAddress.java:426)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:255)
at java.net.InetAddress.getAllByName(InetAddress.java:218)
at com.android.okhttp.HostResolver.getAllByName(HostResolver.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:373)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:323)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:190)
at java.net.URL.openStream(URL.java:470)
at ali.androidtest.MainActivity.getData(MainActivity.java:32)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View.onClick(View.java:4010)
at android.view.View.performClick(View.java:4764)
at android.view.View$PerformClick.run(View.java:19833)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5292)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ali.androidtest" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
已修复使用异步获取数据的问题。