如何在xml Sax Parser中使用AsyncTask?

时间:2011-11-06 20:22:40

标签: android

我使用xml sax解析器从web读取xml,它在android 2.3中运行。 但现在我希望它能在Android 3.0上运行。 因为我在主线程中读取文件,我得到错误:

  

android.os.NetworkOnMainThreadException

我尝试使用AsyncTask但我无法使其工作。 请告诉我如何在我的情况下实现AsyncTask。这是我的原始代码:

ListView lw = (ListView)findViewById(R.id.listView1);
final ArrayList<String> list = new ArrayList<String>();
final ArrayAdapter<String> aa = new ArrayAdapter<String>(this,      android.R.layout.simple_list_item_1, list);
lw.setAdapter(aa);

try {
        /* Create a URL we want to load some xml-data from. */
        URL url = new URL("http://www.bnr.ro/nbrfxrates.xml");
        //aded to verify link
        URI uri = new URI(url.toString());
        HttpGet httpget = new HttpGet(uri);
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = httpclient.execute(httpget);
        if (response.getStatusLine().getStatusCode()==200) {
           url = new URL("http://www.visual-efx.net/nbrfxrates.xml");
        }
        //aded to verify link
        /* 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. */

        for (int i=1; i<=31; i++){
           list.add(myExampleHandler.valuta[i] + " = " + myExampleHandler.pret[i] + " lei");
           aa.notifyDataSetChanged();
        }

} catch (Exception e) {
        /* Display any Error to the GUI. */
        Log.e(MY_DEBUG_TAG, "Error", e);
}

1 个答案:

答案 0 :(得分:2)

在这种情况下,您实际应该使用AsyncTaskLoader。它会让事情变得更容易。只需创建自己的类,扩展AsyncTaskLoader,让它只有一个方法loadInBackground()。在loadInBackground()方法中,将用于解析xml的代码放在这样的:

public List<String> loadInBackground(){
  ArrayList toReturn = new ArrayList<String>();

  try {
    URL url = new URL("http://www.bnr.ro/nbrfxrates.xml");

    URI uri = new URI(url.toString());
    HttpGet httpget = new HttpGet(uri);
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = httpclient.execute(httpget);
    if (response.getStatusLine().getStatusCode()==200) {
       url = new URL("http://www.visual-efx.net/nbrfxrates.xml")
    }
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser sp = spf.newSAXParser();


    XMLReader xr = sp.getXMLReader();

    ExampleHandler myExampleHandler = new ExampleHandler();
    xr.setContentHandler(myExampleHandler);


    xr.parse(new InputSource(url.openStream()));


    for (int i=1; i<=31; i++){
      toReturn.add(myExampleHandler.valuta[i] + " = " + myExampleHandler.pret[i] + " lei");
    }

  } catch (Exception e) {

    Log.e(MY_DEBUG_TAG, "Error", e);
  }

  return toReturn;
}

然后,在您显示列表的活动中,让您的Activity实现LoaderManager.LoaderCallbacks界面,就像这样

public YourActivity implements LoaderManager.LoaderCallbacks<List<String>>

然后实现回调方法。例如,您的onLoadFinished()方法看起来就像这样:

public void onLoadFinished(Loader<List<String>>, List<String> data){
   aa.setData(data);
}

有关装载机的更多信息,请结帐this documentation。请注意,如果您的目标API低于3.0,则需要使用Android Support Package