2011-06-20 34 views
0

我正在做一個應用程序,我必須做XML解析。如何檢查數據是否在android中返回?

我必須檢查用戶是否能夠訪問新數據,然後我必須刪除數據庫中的舊數據。

對於上面我使用下面的代碼:

try{ 
     URL url = new URL(address); 
     /* 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 */ 
     xr.setContentHandler(this); 
     /* Parse the xml-data from our URL. */ 
     InputSource is = new InputSource(url.openStream()); 
     //once data is obtained then delete the table. 
     hb.executeSql("DELETE FROM Products,Category"); 
     xr.parse(is); 
} 
catch{ 
    e.printstacktrace(); 
} 

如果輸入流,那麼一個異常將被拋出這我趕上一個錯誤,並刪除表中的代碼將永遠不會被執行。

邏輯是否正確?

回答

0

你幾乎在那裏,如果url.OpenStream()拋出一個異常,你會趕上它。但是,要完全安全起見,你需要把

xr.parse(is); 

hb.exequteSql("Delete..."); 

因爲xr.parse會拋出一個IO或SAX異常,即使出現這種情況你的代碼將刪除。

的API,請參閱

http://download.oracle.com/javase/1.5.0/docs/api/org/xml/sax/XMLReader.html#parse(org.xml.sax.InputSource

此外,我會建議你趕上,IO和SAX異常seperately。它可以幫助您輕鬆調試。

0

你的catch塊是錯誤的。請參閱處理java中的異常。

語法是:

try{ 
// do your logic here. 

}catch (Exception e){ 
e.printStackTrace(); 
} 
finally{ 
// do something if there is or isnt an exception 
} 

如果有異常就會跳到捕捉代碼,這意味着您可以將您的代碼刪除舊數據作爲catch塊之前的最後一行,然後,如果一切在它上面運行時,你的代碼將不會執行異常,否則在異常點它會跳過所有的catch塊,然後當catch完成時它會轉到finally塊並離開try-catch。

0

使用tbelow功能這個函數返回boolean值。

public boolean parseResultantXml(String handlerType,String inputXml){ 
     boolean result = false; 
     SAXParserFactory spf = SAXParserFactory.newInstance(); 
     SAXParser sp; 
     XMLReader xr = null; 
     try { 
      sp = spf.newSAXParser(); 

      xr = sp.getXMLReader(); 
     } catch (ParserConfigurationException e) { 
      e.printStackTrace(); 
     } catch (SAXException e) { 
      e.printStackTrace(); 
     } 

     SAXParsersUtil saxParserUtil = new SAXParsersUtil(); 

     RequiredParser rp = saxParserUtil.getParser(handlerType); 
     xr.setContentHandler(rp); 
     InputStream in = null; 
     try { 
      in = new ByteArrayInputStream(
        ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + inputXml) 
          .getBytes("UTF-8")); 
     } catch (IOException e) { 
      e.printStackTrace(); 
      result = false; 
     } 
     try { 
      xr.parse(new InputSource(in)); 
      result = true; 
     } catch (IOException e) { 
      e.printStackTrace(); 
      result = false; 
     } catch (SAXException e) { 
      e.printStackTrace(); 
      result = false; 
     } 
     return result; 
    } 
相關問題