2011-04-25 53 views
0

我目前正在嘗試使用動態解析來自xml的數據。所以我試圖通過不同的標籤檢索數據,並使用SimpleAdapter將它們插入到不同的文本視圖中。但在我看來,它的失敗,它應該工作。請幫我弄清楚這一點。解析XML數據意外失敗

這是我SearchResults.java

public class SearchResult extends ListActivity{ 

String set_number; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.list); 

    ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>(); 

    //retrieve text passed from previous activity 
    Bundle bundle = getIntent().getExtras(); 
    String searchItems = bundle.getString("searchItems"); 

    //get the xml data using retrieve text from previous activity  
    String xmlSetNo = XMLFunctions.getSetNoXML(searchItems); 
    Document docSetNo = XMLFunctions.XMLfromString(xmlSetNo);//change xml data to doc format 

    NodeList nodeSetNo = docSetNo.getElementsByTagName("find"); 

    for (int i = 0; i < nodeSetNo.getLength(); i++) {       
     Element e = (Element)nodeSetNo.item(i); 
     set_number = XMLFunctions.getValue(e, "set_number"); 
    }  

    String xmlRecords = XMLFunctions.getRecordsXML(set_number); 
    Document docRecords = XMLFunctions.XMLfromString(xmlRecords); 

    NodeList nodeRecords = docRecords.getElementsByTagName("metadata"); 

    for(int i = 0; i < nodeRecords.getLength(); i++) { 
     HashMap<String, String> map = new HashMap<String, String>();  

     Element e = (Element)nodeRecords.item(i); 

     //map.put("cover_image", getTagValue("varfield id='20'", e)); 
     map.put("title", getTagValue("varfield id='245'", e)); 
     map.put("author", getTagValue("varfield id='100'", e)); 
     map.put("format", getTagValue("fixfield id='FMT'", e)); 
     map.put("call_number", getTagValue("varfield id='099'", e)); 
     /* 
     map.put("set_number", XMLFunctions.getValue(e, "set_number")); 
     map.put("no_records", "No. of Records:" + XMLFunctions.getValue(e, "no_records")); 
     map.put("no_entries", "No. of Entries: " + XMLFunctions.getValue(e, "no_entries")); 
     mylist.add(map); 
     */ 
    } 

    ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.search_result_display_list, 
        new String[] { "cover_image","title","author","format","call_number"}, 
        new int[] {R.id.cover_image, R.id.item_title, R.id.item_author,R.id.item_format,R.id.item_call_number }); 

    setListAdapter(adapter); 

    final ListView lv = getListView(); 
    lv.setTextFilterEnabled(true); 
    /*lv.setOnItemClickListener(new OnItemClickListener() { 
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) {    
      @SuppressWarnings("unchecked") 
      HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);     
      Toast.makeText(SearchResult.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_LONG).show(); 

     } 
    });*/ 
} 

private static String getTagValue(String sTag, Element eElement){ 
     NodeList nlList= eElement.getElementsByTagName(sTag).item(0).getChildNodes(); 
     Node nValue = (Node) nlList.item(0); 

     return nValue.getNodeValue();  
    } 
} 

這是我XMLFunctions.java,我分析我的XML數據:

public class XMLFunctions { 

public final static Document XMLfromString(String xml){ 

    Document doc = null; 

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
    try { 

     DocumentBuilder db = dbf.newDocumentBuilder(); 

     InputSource is = new InputSource(); 
     is.setCharacterStream(new StringReader(xml)); 
     doc = db.parse(is); 

    } catch (ParserConfigurationException e) { 
     System.out.println("XML parse error: " + e.getMessage()); 
     return null; 
    } catch (SAXException e) { 
     System.out.println("Wrong XML file structure: " + e.getMessage()); 
     return null; 
    } catch (IOException e) { 
     System.out.println("I/O exeption: " + e.getMessage()); 
     return null; 
    } 

    return doc; 

} 

/** Returns element value 
    * @param elem element (it is XML tag) 
    * @return Element value otherwise empty String 
    */ 
public final static String getElementValue(Node elem) { 
    Node kid; 
    if(elem != null){ 
     if (elem.hasChildNodes()){ 
      for(kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling()){ 
       if(kid.getNodeType() == Node.TEXT_NODE ){ 
        return kid.getNodeValue(); 
       } 
      } 
     } 
    } 
    return ""; 
} 

public static String getSetNoXML(String searchItems){ 
     String line = null; 

     try { 

      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      //request for item's set_number 
      HttpGet requestSetNumber = new HttpGet("http://spark.opac.tp.edu.sg/X?op=find&scan_code=find_wrd&request="+ searchItems +"&base=tpl01"); 

      HttpResponse httpResponse = httpClient.execute(requestSetNumber); 
      HttpEntity httpEntity = httpResponse.getEntity(); 
      line = EntityUtils.toString(httpEntity); 

     } catch (UnsupportedEncodingException e) { 
      line = "<find status=\"error\"><msg>Can't connect to server</msg></find>"; 
     } catch (MalformedURLException e) { 
      line = "<find status=\"error\"><msg>Can't connect to server</msg></find>"; 
     } catch (IOException e) { 
      line = "<find status=\"error\"><msg>Can't connect to server</msg></find>"; 
     } 
     return line; 
} 

public static String getRecordsXML(String setNumber){ 
     String line = null; 

     try { 

      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      //request records via set_number 
      HttpGet requestRecords = new HttpGet("http://spark.opac.tp.edu.sg/X?op=present&set_no="+ setNumber +"&set_entry=000000001,000000002,000000003," + 
        "000000004,000000005,000000006,000000007,000000008,000000009,000000010&format=marc"); 


      HttpResponse httpResponse = httpClient.execute(requestRecords); 
      HttpEntity httpEntity = httpResponse.getEntity(); 
      line = EntityUtils.toString(httpEntity); 

     } catch (UnsupportedEncodingException e) { 
      line = "<find status=\"error\"><msg>Can't connect to server</msg></find>"; 
     } catch (MalformedURLException e) { 
      line = "<find status=\"error\"><msg>Can't connect to server</msg></find>"; 
     } catch (IOException e) { 
      line = "<find status=\"error\"><msg>Can't connect to server</msg></find>"; 
     } 
     return line; 
} 

public static int numResults(Document doc){  
    Node results = doc.getDocumentElement(); 
    int res = -1; 

    try{ 
     res = Integer.valueOf(results.getAttributes().getNamedItem("find").getNodeValue()); 
    }catch(Exception e){ 
     res = -1; 
    } 

    return res; 
} 

public static String getValue(Element item, String str) {  
    NodeList n = item.getElementsByTagName(str);   
    return XMLFunctions.getElementValue(n.item(0)); 
} 
} 

最後,這是從輸出logcat的

04-25 10:20:15.932:ERROR/AndroidRuntime(418):致命異常:主
04-25 10:20:15.932:錯誤/ AndroidRuntime(418):java.lang.RuntimeException:無法啓動活動ComponentInfo {joel.TPLibrary/joel.TPLibrary.SearchResult}:java.lang.NullPointerException
04-25 10:20:15.932:ERROR/AndroidRuntime(418):at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663 )
04-25 10:20:15.932:ERROR/AndroidRuntime(418):at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
04-25 10:20:15.932:ERROR/AndroidRuntime(418) ):在android.app.ActivityThread.access $ 2300(ActivityThread.java:125)
10月4日至25日:20:15.932:ERROR/AND roidRuntime(418):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:2033)
10月4日至25日:20:15.932:ERROR/AndroidRuntime(418):在android.os.Handler.dispatchMessage(處理程序.java:99)
04-25 10:20:15.932:ERROR/AndroidRuntime(418):at android.os.Looper.loop(Looper.java:123)
04-25 10:20:15.932:ERROR/AndroidRuntime(418):在android.app.ActivityThread.main(ActivityThread.java:4627)
10月4日至25日:20:15.932:ERROR/AndroidRuntime(418):在java.lang.reflect.Method.invokeNative( Native Method)
04-25 10:20:15.932:ERROR/AndroidRuntime(418):at java.lang.reflect.Method.invoke(Method.java:521)
04-25 10:20:15.932:ERROR/AndroidRun時間(418):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:868)
10月4日至25日:20:15.932:ERROR/AndroidRuntime(418):在com.android.internal .os.ZygoteInit.main(ZygoteInit.java:626) 04-25 10:20:15.932:ERROR/AndroidRuntime(418):at dalvik.system.NativeStart.main(Native Method)
04-25 10:20 :15.932:ERROR/AndroidRuntime(418):由於:java.lang.NullPointerException 04-25 10:20:15.932:ERROR/AndroidRuntime(418):at joel.TPLibrary.SearchResult.getTagValue(SearchResult.java:89 )
04-25 10:20:15.932:ERROR/AndroidRuntime(418):at joel.TPLibrary.SearchResult.onCreate(SearchResult.java:58)

04-25 10:20:15.9 32:ERROR/AndroidRuntime(418):at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-25 10:20:15.932:ERROR/AndroidRuntime(418):at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2627)
04-25 10:20:15.932:ERROR/AndroidRuntime(418):...11更多

回答

1

我認爲你要解決在android中以錯誤的方式解析XML。坦率地說,代碼看起來比它需要的更混亂。

相反,我會建議使用基於註解的XML框架Simple這將幫助您輕鬆地編寫和輸出XML:我非常喜歡I even wrote a blog post about how to include it in your Android projects

如果你提供了一些XML示例,那麼我可以給你更多關於錯誤的信息。

+0

嗨,我意識到我使用DOM解析器時,我應該使用SAX解析器,因爲我只是從XML讀取數據。所以我更改爲SAX Parser,但目前面臨着如何在單個標籤下檢索所有數據的問題。 – 2011-04-26 02:43:54