В настоящее время я пытаюсь проанализировать данные из XML с использованием динамически.Поэтому я пытаюсь получить данные через разные теги и вставить их в разные текстовые представления с помощью SimpleAdapter.Но его неудача, когда, на мой взгляд, должна работать.Пожалуйста, помогите мне разобраться.
Это мой 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: ОШИБКА / AndroidRuntime (418): ИСКЛЮЧИТЕЛЬНОЕ ИСКЛЮЧЕНИЕ: main
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: ОШИБКА / AndroidRuntime (418): в android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2663)
04-25 10: 20: 15.932:ОШИБКА / AndroidRuntime (418): в android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:2679)
04-25 10: 20: 15.932: ОШИБКА / AndroidRuntime (418): в android.app.ActivityThread.access $ 2300(ActivityThread.java:125)
04-25 10: 20: 15.932: ОШИБКА / AndroidRuntime (418): на android.app.ActivityThread $ H.handleMessage (ActivityThread.java:2033)
04-25 10: 20: 15.932: ОШИБКА / AndroidRuntime (418): на android.os.Handler.dispatchMessage (Handler.java:99)
04-25 10:20: 15.932: ОШИБКА / AndroidRuntime (418): на android.os.Looper.loop (Looper.java:123)
04-25 10: 20: 15.932: ОШИБКА / AndroidRuntime (418): на android.app.ActivityThread.main (ActivityThread.java:4627)
04-25 10: 20: 15.932: ОШИБКА / AndroidRuntime (418): в java.lang.reflect.Method.invokeNative (собственный метод)
04-25 10: 20: 15.932: ОШИБКА / AndroidRuntime (418): в java.lang.reflect.Method.invoke (Method.java:521)
04-25 10: 20: 15.932: ОШИБКА / AndroidRuntime (418): в com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run (ZygoteInit.java:868)
04-25 10: 20: 15.932: ОШИБКА / AndroidRuntime (418): на com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 04-25 10: 20: 15.932: ОШИБКА / AndroidRuntime (418): в dalvik.system.NativeStart.main (собственный метод)
04-25 10: 20: 15.932: ОШИБКА / AndroidRuntime(418): вызвано: java.lang.NullPointerException 04-25 10: 20: 15.932: ОШИБКА / AndroidRuntime (418): в joel.TPLibrary.SearchResult.getTagValue (SearchResult.java:89)
04-25 10: 20: 15.932: ОШИБКА / AndroidRuntime(418): at joel.TPLibrary.SearchResult.onCreate (SearchResult.java:58)
04-25 10: 20: 15.932: ОШИБКА / AndroidRuntime (418): на android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1047)
04-25 10: 20: 15.932: ОШИБКА / AndroidRuntime (418): на android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2627)
04-25 10:20:15.932: ОШИБКА / AndroidRuntime (418): ... еще 11