没有RSS数据出现

时间:2015-09-02 06:14:01

标签: java android rss

我正在Techiedreams.com关注本教程。我想在http://feeds.feedburner.com/TwitterRssFeedXML将RSS的URL更改为我自己的URL。这是我的代码:

SplashActivity.Java

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;


public class SplashActivty extends Activity {

String RSSFEEDURL = "http://feeds.feedburner.com/androidcentral?format=xml";
//wanted http://feeds.feedburner.com/TwitterRssFeedXML instead
RSSFeed feed;
String fileName;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.splash);

    fileName = "TDRSSFeed.td";

    File feedFile = getBaseContext().getFileStreamPath(fileName);

    ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    if (conMgr.getActiveNetworkInfo() == null) {

        // No connectivity. Check if feed File exists
        if (!feedFile.exists()) {

            // No connectivity & Feed file doesn't exist: Show alert to exit
            // & check for connectivity
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage(
                    "Unable to reach server, \nPlease check your connectivity.")
                    .setTitle("TD RSS Reader")
                    .setCancelable(false)
                    .setPositiveButton("Exit",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int id) {
                                    finish();
                                }
                            });

            AlertDialog alert = builder.create();
            alert.show();
        } else {

            // No connectivty and file exists: Read feed from the File
            Toast toast = Toast.makeText(this,
                    "No connectivity! Reading last update...",
                    Toast.LENGTH_LONG);
            toast.show();
            feed = ReadFeed(fileName);
            startLisActivity(feed);
        }

    } else {

        // Connected - Start parsing
        new AsyncLoadXMLFeed().execute();

    }

}

private void startLisActivity(RSSFeed feed) {

    Bundle bundle = new Bundle();
    bundle.putSerializable("feed", feed);

    // launch List activity
    Intent intent = new Intent(SplashActivty.this, List_Activity.class);
    intent.putExtras(bundle);
    startActivity(intent);

    // kill this activity
    finish();

}

private class AsyncLoadXMLFeed extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {

        // Obtain feed
        DOMParser myParser = new DOMParser();
        feed = myParser.parseXml(RSSFEEDURL);
        if (feed != null && feed.getItemCount() > 0)
            WriteFeed(feed);
        return null;

    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);

        startLisActivity(feed);
    }

}

// Method to write the feed to the File
private void WriteFeed(RSSFeed data) {

    FileOutputStream fOut = null;
    ObjectOutputStream osw = null;

    try {
        fOut = openFileOutput(fileName, MODE_PRIVATE);
        osw = new ObjectOutputStream(fOut);
        osw.writeObject(data);
        osw.flush();
    }

    catch (Exception e) {
        e.printStackTrace();
    }

    finally {
        try {
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

// Method to read the feed from the File
private RSSFeed ReadFeed(String fName) {

    FileInputStream fIn = null;
    ObjectInputStream isr = null;

    RSSFeed _feed = null;
    File feedFile = getBaseContext().getFileStreamPath(fileName);
    if (!feedFile.exists())
        return null;

    try {
        fIn = openFileInput(fName);
        isr = new ObjectInputStream(fIn);

        _feed = (RSSFeed) isr.readObject();
    }

    catch (Exception e) {
        e.printStackTrace();
    }

    finally {
        try {
            fIn.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return _feed;

}

}

RSSItem.Java:

package com.example.samsung.feedrss;

import java.io.Serializable;

public class RSSItem implements Serializable {

private static final long serialVersionUID = 1L;
private String _title = null;
private String _description = null;
private String _date = null;
private String _image = null;

void setTitle(String title) {
    _title = title;
}

void setDescription(String description) {
    _description = description;
}

void setDate(String pubdate) {
    _date = pubdate;
}

void setImage(String image) {
    _image = image;
}

public String getTitle() {
    return _title;
}

public String getDescription() {
    return _description;
}

public String getDate() {
    return _date;
}

public String getImage() {
    return _image;
}

}

的DOMParser:

public class DOMParser {

private RSSFeed _feed = new RSSFeed();

public RSSFeed parseXml(String xml) {

    // _feed.clearList();

    URL url = null;
    try {
        url = new URL(xml);
    } catch (MalformedURLException e1) {
        e1.printStackTrace();
    }

    try {
        // Create required instances
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();

        // Parse the xml
        Document doc = db.parse(new InputSource(url.openStream()));
        doc.getDocumentElement().normalize();

        // Get all <item> tags.
        NodeList nl = doc.getElementsByTagName("item");
        int length = nl.getLength();

        for (int i = 0; i < length; i++) {
            Node currentNode = nl.item(i);
            RSSItem _item = new RSSItem();

            NodeList nchild = currentNode.getChildNodes();
            int clength = nchild.getLength();

            // Get the required elements from each Item
            for (int j = 0; j < clength; j = j + 1) {

                Node thisNode = nchild.item(j);
                String theString = null;
                String nodeName = thisNode.getNodeName();

                theString = nchild.item(j).getFirstChild().getNodeValue();

                if (theString != null) {
                    if ("title".equals(nodeName)) {
                        // Node name is equals to 'title' so set the Node
                        // value to the Title in the RSSItem.
                        _item.setTitle(theString);
                    }

                    else if ("description".equals(nodeName)) {
                        _item.setDescription(theString);

                        // Parse the html description to get the image url
                        String html = theString;
                        org.jsoup.nodes.Document docHtml = Jsoup
                                .parse(html);
                        Elements imgEle = docHtml.select("img");
                        _item.setImage(imgEle.attr("src"));
                    }

                    else if ("pubDate".equals(nodeName)) {

                        // We replace the plus and zero's in the date with
                        // empty string
                        String formatedDate = theString.replace(" +0000",
                                "");
                        _item.setDate(formatedDate);
                    }

                }
            }

            // add item to the list
            _feed.addItem(_item);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    // Return the final feed once all the Items are added to the RSSFeed
    // Object(_feed).
    return _feed;
}

}

问题是我的个人网址不起作用,但原始网址不起作用。有人可以解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

好的,经过一段时间的工作,我找到了解决方案。只需调整feedburner.com中的一些设置,确保激活SmartFeed下的Optimize,您就可以了。如果单独SmartFeed不起作用,请务必检查任何其他设置。