我正在尝试创建一个RSS阅读器,以便从Google新闻的RSS源中读取。这是我的代码:
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
public class ReadRss extends AsyncTask<Void, Void, Void> {
Context context;
String address = "https://news.google.co.uk/news?cf=all&hl=en&pz=1&ned=uk&output=rss";
ProgressDialog progressDialog;
URL url;
public ReadRss(Context context) {
this.context = context;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();
}
@Override
protected Void doInBackground(Void... params) {
ProcessXml(Getdata());
return null;
}
private void ProcessXml(Document data) {
if (data != null) {
ArrayList<FeedItem>feedItems=new ArrayList<>();
Element root = data.getDocumentElement();
Node channel = root.getChildNodes().item(1);
NodeList items = channel.getChildNodes();
for (int i = 0; i < items.getLength(); i++) {
Node cureentchild = items.item(i);
if (cureentchild.getNodeName().equalsIgnoreCase("item")) {
FeedItem item=new FeedItem();
NodeList itemchilds = cureentchild.getChildNodes();
for (int j = 0; j < itemchilds.getLength(); j++) {
Node cureent = itemchilds.item(j);
if (cureent.getNodeName().equalsIgnoreCase("title")){
item.setTitle(cureent.getTextContent());
}else if (cureent.getNodeName().equalsIgnoreCase("description")){
item.setDescription(cureent.getTextContent());
}else if (cureent.getNodeName().equalsIgnoreCase("pubDate")){
item.setPubDate(cureent.getTextContent());
}else if (cureent.getNodeName().equalsIgnoreCase("link")){
item.setLink(cureent.getTextContent());
}
}
feedItems.add(item);
Log.d("itemTitle", item.getTitle());
Log.d("itemDescription",item.getDescription());
Log.d("itemPubDate",item.getPubDate());
Log.d("itemLink",item.getLink());
}
}
}
}
public Document Getdata() {
try {
url = new URL(address);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStream inputStream = connection.getInputStream();
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDoc = builder.parse(inputStream);
return xmlDoc;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
但是当我尝试运行时,我收到此错误:
Attempt to invoke interface method 'org.w3c.dom.NodeList org.w3c.dom.Node.getChildNodes()' on a null object reference
我不知道为什么它是null。我是新手,所以非常感谢帮助。