为了重复从服务器获取 XML 数据,我尝试按照Mark Murphy 的建议使用 AsyncTask 和 Timer 。
我收到以下错误:
01-07 16:11:26.705: ERROR/AndroidRuntime(729):
Caused by: java.lang.RuntimeException:
Can't create handler inside thread that has not
called Looper.prepare()
我在 Windows 上使用带有 Eclipse 的 SDK 1.5。
我查看了文档、StackOverflow 和 Android 开发人员组,但我不清楚是什么导致了错误或如何修复它。
我可以一次获取数据——即没有异步和计时器——并通过 SAX 解析它而不会出现问题。
完整的应用程序代码如下。
请原谅任何天真的错误:我对 Android 很陌生。
package com.foo.bar.myactivity;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;
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.AsyncTask;
import android.os.Bundle;
import android.util.Log;
public class MyActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Timer timer;
timer = new Timer();
timer.schedule(new MyTimerTask(), 0, 1000);
}
public class MyAsyncTask extends AsyncTask<String, Integer, MyData> {
protected MyData doInBackground(String... string) {
MyData myData = new MyData();
try {
URL url = new URL("http://www.example.com/my.xml");
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
MyHandler myHandler = new MyHandler();
xr.setContentHandler(myHandler);
System.setProperty("http.proxyHost", "www-cache.example.com");
System.setProperty("http.proxyPort", "80");
xr.parse(new InputSource(url.openStream()));
myData = myHandler.getParsedData();
return myData;
} catch (Exception e) {
Log.e(">>>>>>>>>>>> Error getting myData: ", e.getMessage(), e);
return myData;
}
}
protected void onProgressUpdate(Integer... progress) {
// setProgressPercent(progress[0]);
}
protected void onPostExecute(MyData myData) {
Log.d(">>>>>>>>>>>>>My data: ", myData.toString());
}
}
public class MyTimerTask extends TimerTask {
public void run() {
try {
new MyAsyncTask().execute("");
} catch (Exception e) {
Log.e(">>>>>>>>>>>> Error executing MyAsyncTask: ", e.getMessage(), e);
}
}
}
}