2011-03-27 47 views

回答

1

让服务器端脚本获取服务器上的数据并将其作为XML返回。然后下载页面并将其加载到您的应用程序中。

使用此代码,您可以从联机数据库获取xml文件,并将其解析为Android中的xml文档。

Document xmlDocument = fromString(downloadPage("http://example.com/data.php"); 

这是应该下载一个网页并返回一个字符串

public String downloadPage(String targetUrl) 
{ 
    BufferedReader in = null; 
    try 
    { 
     // Create a URL for the desired page 
     URL url = new URL(targetUrl); 

     // Read all the text returned by the server 
     in = new BufferedReader(new InputStreamReader(url.openStream())); 
     String str; 
     String output = ""; 
     while ((str = in.readLine()) != null) 
     { 
      // str is one line of text; readLine() strips the newline 
      // character(s) 
      output += "\n"; 
      output += str; 
     } 
     return output.substring(1); 
    } 
    catch (MalformedURLException e) 
    {} 
    catch (IOException e) 
    {} 
    finally 
    { 
     try 
     { 
      if (in != null) in.close(); 
     } 
     catch (IOException e) 
     { 

     } 
    } 
    return null; 
} 

这是一个简单的DOM解析器解析字符串转换成文档对象的简短的脚本。

public static Document fromString(String xml) 
{ 
    if (xml == null) 
     throw new NullPointerException("The xml string passed in is null"); 

    // from http://www.rgagnon.com/javadetails/java-0573.html 
    try 
    { 
     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder db = dbf.newDocumentBuilder(); 
     InputSource is = new InputSource(); 
     is.setCharacterStream(new StringReader(xml)); 

     Document doc = db.parse(is); 

     return doc; 
    } 
    catch (SAXException e) 
    { 
     return null; 
    } 
    catch(Exception e) 
    { 
     CustomExceptionHandler han = new CustomExceptionHandler(); 
     han.uncaughtException(Thread.currentThread(), e); 
     return null; 
    } 
} 
相关问题