如何使用 AsyncTask 和 Timer 获取 XML? [英] How to get XML using AsyncTask and Timer?

查看:8
本文介绍了如何使用 AsyncTask 和 Timer 获取 XML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了重复从服务器获取 XML 数据,我尝试按照 马克墨菲的建议.

In order to get XML data from a server repeatedly, I'm attempting to use AsyncTask and Timer as per Mark Murphy's suggestion.

我收到以下错误:

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.

I'm using SDK 1.5 with Eclipse on Windows.

我查看了文档、StackOverflow 和 Android 开发人员组,但不清楚是什么导致了错误或如何修复它.

I've looked in documentation, on StackOverflow and in the Android Developers group, but I'm not clear what's causing the error or how to fix it.

我可以获取一次数据——即没有 Async 和 Timer——并且通过 SAX 解析它没有问题.

I can get the data once -- i.e. without Async and Timer -- and parse it via SAX without problems.

完整的应用代码如下.

请原谅任何幼稚的错误:我是 Android 新手.

Please excuse any naive errors: I'm quite new to 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);
            }
        }
    }

}

推荐答案

问题出在TimerTask的使用上.TimerTask 运行应该发送到处理程序,如下所示:

The problem is in the use of TimerTask. TimerTask run should post to a handler, something like this:

private Handler mHandler = new Handler(); 

public class MyTimerTask extends TimerTask {
    public void run() {
        mHandler.post(
            new Runnable() { 
                public void run() { 
                    new MyAsyncTask().execute("");
                } 
            };     
        )
    }
}

当然这有点难看,所以建议去掉匿名类.

Of course this is getting a bit ugly, so would recommend taking out the anonymous class.

这篇关于如何使用 AsyncTask 和 Timer 获取 XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆