현재 XML을 동적으로 사용하여 데이터를 구문 분석하려고합니다. 그래서 다른 태그를 통해 데이터를 검색하고 SimpleAdapter를 사용하여 다른 textviews에 삽입하려고합니다. 그러나 그것이 나의 관점에서 실패 할 때, 그것은 일하기로되어있다. 이 점을 이해하도록 도와주세요.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 : ERROR/AndroidRuntime (418) : java.lang.RuntimeException : 활동을 시작할 수 없습니다. ComponentInfo {joel.TPLibrary/joel.TPLibrary.SearchResult} : java.lang.NullPointerException
04-25 10:20:15.932 : ERROR/AndroidRuntime (418) : android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2663))
10월 4일부터 25일까지 : 20 : 15.932 : ERROR/AndroidRuntime (418) : 20 :
10월 4일에서 25일까지 android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:2679)로 15.932 : ERROR/AndroidRuntime (418) : android.app.ActivityThread.access $ 2300 (ActivityThread.java:125)
04-25 10 : 20 : 15.932 : ERROR/그리고 roidRuntime (418) : android.app.ActivityThread $ H.handleMessage (ActivityThread.java:2033)
04-25 10 : 20 : 15.932 : ERROR/AndroidRuntime (418) : android.os.Handler.dispatchMessage (Handler .java : 99)
04-25 10 : 20 : 15.932 : ERROR/AndroidRuntime (418) : android.os.Looper.loop (Looper.java:123)
04-25 10 : 20 : 15.932 : ERROR/AndroidRuntime (418) : android.app.ActivityThread.main (ActivityThread.java:4627)
04-25 10 : 20 : 15.932 : ERROR/AndroidRuntime (418) : java.lang.reflect.Method.invokeNative에서 네이티브 메소드)
04-25 10 : 20 : 15.932 : ERROR/AndroidRuntime (418) : 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)
04-25 10 : 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 (기본 메소드)
04-25 10:20 : 15.932 : ERROR/AndroidRuntime (418) : 원인 : java.lang.NullPointerException 04-25 10 : 20 : 15.932 : ERROR/AndroidRuntime (418) : joel.TPLibrary.SearchResult.getTagValue (SearchResult.java:89))
04-25 10:20:15.932 : ERROR/AndroidRuntime (418) : joel.TPLibrary.SearchResult.onCreate (SearchResult.java:58)
04-25 10 : 20 : 15.9 32 : ERROR/AndroidRuntime (418) : android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1047)
04-25 10 : 20 : 15.932 : ERROR/AndroidRuntime (418) : android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2627)
04-25 10 : 20 : 15.932 : ERROR/AndroidRuntime (418) : ...11 이상
안녕하세요, 저는 XML에서 데이터를 읽는 중이므로 SAX 파서를 사용해야 할 때 DOM 파서를 사용하고 있다는 것을 알고 있습니다. 그래서 SAX Parser로 바꿨지 만 현재 단일 태그 아래에서 모든 데이터를 검색하는 방법에 문제가 있습니다. –