当我在数组中使用第二个Feed时,我收到以上错误消息,其他Feed正常工作;只是那个抛出错误的特定饲料。
有人可以指出我正确的方向。
谢谢!
(Feed数组在rssRun()方法中,它是导致我错误的第二个Feed)
更新:
问题似乎是,有时候' doc'证明是空的,因此抛出一个错误。所以我只是在代码周围放了一个try catch方法,这似乎已经完成了诀窍....任何抛出错误的项目都会被跳过。
MainCode:
package com.androidhive.xmlparsing;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class AndroidXMLParsingActivity extends ListActivity {
// All static variables
//static final String URL = "http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=uk";
String[] URL = new String[3];
int count = 0;
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";
static final String KEY_LINK = "link";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rssRun();
}
public void rssRun()
{
URL[0] = "http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/football/teams/a/arsenal/rss.xml";
URL[1] = "http://www.skysports.com/rss/0,20514,11661,00.xml";
URL[2] = "http://www.football365.com/premier-league/rss";
//URL[3] = "http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=uk";
for (int f= 0;f < 3;f++)
{
count+=1;
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL[f]); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
//Log.e("XML", xml);
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
//Log.e("NODELIST", nl.toString());
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
//map.put(KEY_DESC, parser.getCharacterDataFromElement(e, KEY_DESC));
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_COST, parser.getValue(e, KEY_COST));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
map.put(KEY_LINK, parser.getValue(e, KEY_LINK));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_NAME, KEY_DESC, KEY_COST, KEY_LINK }, new int[] {
R.id.name, R.id.desciption, R.id.cost, R.id.link});
//if (count==3)
//{
setListAdapter(adapter);
//}
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_COST, cost);
in.putExtra(KEY_DESC, description);
startActivity(in);
}
});
}
}
public String getCharacterDataFromElement(Element e, String str) {
NodeList n = e.getElementsByTagName(str);
Element e1=(Element) n.item(0);
Node child = e1.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
}
XMLPARSER:
package com.androidhive.xmlparsing;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import android.util.Log;
public class XMLParser {
// constructor
public XMLParser() {
}
/**
* Getting XML from URL making HTTP request
* @param url string
* */
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
/**
* Getting XML DOM element
* @param XML string
* */
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
dbf.setCoalescing(true);
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return doc;
}
/** Getting node value
* @param elem element
*/
public final String getElementValue2( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
//if( child.getNodeType() == Node.TEXT_NODE ){
if( child.getNodeType() == Node.TEXT_NODE || child.getNodeType() == Node.CDATA_SECTION_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
//return elem.getTextContent();
}
/**
* Getting node value
* @param Element node
* @param key string
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue2(n.item(0));
}
}
错误日志:
08-27 11:32:42.327: E/Error:(5730): Expected a quoted string (position:DOCDECL @1:50 in java.io.StringReader@42c223e8)
08-27 11:32:42.337: D/AndroidRuntime(5730): Shutting down VM
08-27 11:32:42.337: W/dalvikvm(5730): threadid=1: thread exiting with uncaught exception (group=0x41966da0)
08-27 11:32:42.347: E/AndroidRuntime(5730): FATAL EXCEPTION: main
08-27 11:32:42.347: E/AndroidRuntime(5730): Process: com.androidhive.xmlparsing, PID: 5730
08-27 11:32:42.347: E/AndroidRuntime(5730): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.xmlparsing/com.androidhive.xmlparsing.AndroidXMLParsingActivity}: java.lang.NullPointerException
08-27 11:32:42.347: E/AndroidRuntime(5730): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
08-27 11:32:42.347: E/AndroidRuntime(5730): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
08-27 11:32:42.347: E/AndroidRuntime(5730): at android.app.ActivityThread.access$900(ActivityThread.java:161)
08-27 11:32:42.347: E/AndroidRuntime(5730): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
08-27 11:32:42.347: E/AndroidRuntime(5730): at android.os.Handler.dispatchMessage(Handler.java:102)
08-27 11:32:42.347: E/AndroidRuntime(5730): at android.os.Looper.loop(Looper.java:157)
08-27 11:32:42.347: E/AndroidRuntime(5730): at android.app.ActivityThread.main(ActivityThread.java:5356)
08-27 11:32:42.347: E/AndroidRuntime(5730): at java.lang.reflect.Method.invokeNative(Native Method)
08-27 11:32:42.347: E/AndroidRuntime(5730): at java.lang.reflect.Method.invoke(Method.java:515)
08-27 11:32:42.347: E/AndroidRuntime(5730): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
08-27 11:32:42.347: E/AndroidRuntime(5730): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
08-27 11:32:42.347: E/AndroidRuntime(5730): at dalvik.system.NativeStart.main(Native Method)
08-27 11:32:42.347: E/AndroidRuntime(5730): Caused by: java.lang.NullPointerException
08-27 11:32:42.347: E/AndroidRuntime(5730): at com.androidhive.xmlparsing.AndroidXMLParsingActivity.rssRun(AndroidXMLParsingActivity.java:71)
08-27 11:32:42.347: E/AndroidRuntime(5730): at com.androidhive.xmlparsing.AndroidXMLParsingActivity.onCreate(AndroidXMLParsingActivity.java:48)
08-27 11:32:42.347: E/AndroidRuntime(5730): at android.app.Activity.performCreate(Activity.java:5426)
08-27 11:32:42.347: E/AndroidRuntime(5730): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
08-27 11:32:42.347: E/AndroidRuntime(5730): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)