从rss feed中提取图像

时间:2013-10-20 11:49:18

标签: java android rss

我是Android开发应用程序的新手,我想将rss url解析为listview。代码正在运行但我们想从rss提取中提取图像并将其显示在列表视图中。

RssItem.java

public class RssItem {

// item title
private String title;
// item link
private String link;

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getLink() {
    return link;
}

public void setLink(String link) {
    this.link = link;
}

@Override
public String toString() {
    return title;
}

}

ListListener.java

public class ListListener implements OnItemClickListener {

// List item's reference
List<RssItem> listItems;
// Calling activity reference
Activity activity;

public ListListener(List<RssItem> aListItems, Activity anActivity) {
    listItems = aListItems;
    activity  = anActivity;
}

/**
 * Start a browser with url from the rss item.
 */
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
    Intent i = new Intent(Intent.ACTION_VIEW);
    i.setData(Uri.parse(listItems.get(pos).getLink()));

    activity.startActivity(i);

}

}

RssParseHandler.java

 public class RssParseHandler extends DefaultHandler {

private List<RssItem> rssItems;

// Used to reference item while parsing
private RssItem currentItem;

// Parsing title indicator
private boolean parsingTitle;
// Parsing link indicator
private boolean parsingLink;

public RssParseHandler() {
    rssItems = new ArrayList<RssItem>();
}

public List<RssItem> getItems() {
    return rssItems;
}

@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException 
{
    if ("item".equals(qName)) {
        currentItem = new RssItem();
    } else if ("title".equals(qName)) {
        parsingTitle = true;
    } else if ("link".equals(qName)) {
        parsingLink = true;
    }
}

@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
    if ("item".equals(qName)) {
        rssItems.add(currentItem);
        currentItem = null;
    } else if ("title".equals(qName)) {
        parsingTitle = false;
    } else if ("link".equals(qName)) {
        parsingLink = false;
    }
}

@Override
public void characters(char[] ch, int start, int length) throws SAXException {
    if (parsingTitle) {
        if (currentItem != null)
            currentItem.setTitle(new String(ch, start, length));
    } else if (parsingLink) {
        if (currentItem != null) {
            currentItem.setLink(new String(ch, start, length));
            parsingLink = false;
        }
    }
}

}

RssReader.java

  public class RssReader {

private String rssUrl;

/**
 * Constructor
 * 
 * @param rssUrl
 */
public RssReader(String rssUrl) {
    this.rssUrl = rssUrl;
}

/**
 * Get RSS items.
 * 
 * @return
 */
public List<RssItem> getItems() throws Exception {
    // SAX parse RSS data
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser saxParser = factory.newSAXParser();

    RssParseHandler handler = new RssParseHandler();

    saxParser.parse(rssUrl, handler);

    return handler.getItems();

}

}

ITCutiesReaderAppActivity.java

public class ITCutiesReaderAppActivity extends Activity {

// A reference to the local object
private ITCutiesReaderAppActivity local;

/**
 * This method creates main application view
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Set view
    setContentView(R.layout.main);

    // Set reference to this activity
    local = this;

    GetRSSDataTask task = new GetRSSDataTask();

    // Start download RSS task
    task.execute("http://www.itcuties.com/feed/#sthash.YI6YrEet.dpuf");

    // Debug the thread name
    Log.d("ITCRssReader", Thread.currentThread().getName());
}

public class GetRSSDataTask extends AsyncTask<String, Void, List<RssItem> > {
    @Override
    protected List<RssItem> doInBackground(String... urls) {

        // Debug the task thread name
        Log.d("ITCRssReader", Thread.currentThread().getName());

        try {
            // Create RSS reader
            RssReader rssReader = new RssReader(urls[0]);

            // Parse RSS, get items
            return rssReader.getItems();

        } catch (Exception e) {
            Log.e("ITCRssReader", e.getMessage());
        }

        return null;
    }

    @Override
    protected void onPostExecute(List<RssItem> result) {

        // Get a ListView from main view
        ListView itcItems = (ListView) findViewById(R.id.listMainView1);

        // Create a list adapter
        ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>  (local,android.R.layout.simple_list_item_1,     result);
        // Set list adapter for the ListView
        itcItems.setAdapter(adapter);

        // Set list view item click listener
        itcItems.setOnItemClickListener(new ListListener(result, local));
    }
}  
}

2 个答案:

答案 0 :(得分:2)

在线阅读了几个小时后,我得到了这个,最初代码没有解析图像,但在阅读了DOM元素的文档后(从Android Studio附带的文档中),我能够创建以下内容实际上有效的代码片段。我在控制台中测试了它。

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

/**
 * Created by user on 7/1/2016.
 */
public class FeedParser {
    // names of the XML tags
    static final String PUB_DATE = "pubDate";
    static final  String LINK = "link";
    static final  String TITLE = "title";
    static final  String ITEM = "item";
    static final  String IMAGE = "media:thumbnail";
    static final String AUTHOR = "author";

    final URL feedUrl;

    public FeedParser(String feedUrl){
        try {
            this.feedUrl = new URL(feedUrl);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }

    public InputStream getInputStream() {
        try {
            return feedUrl.openConnection().getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void parse() {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document dom = builder.parse(this.getInputStream());
            Element root = dom.getDocumentElement();
            NodeList items = root.getElementsByTagName(ITEM);
            for (int i=0;i<items.getLength();i++){

                Node item = items.item(i);
                NodeList properties = item.getChildNodes();
                for (int j=0;j<properties.getLength();j++){
                    Node property = properties.item(j);
                    String name = property.getNodeName();
                    if (name.equalsIgnoreCase(TITLE)){
                        System.out.println(property.getFirstChild().getNodeValue());
                    } else if (name.equalsIgnoreCase(LINK)){
                        System.out.println(property.getFirstChild().getNodeValue());
                    } else if (name.equalsIgnoreCase(AUTHOR)){
                        StringBuilder text = new StringBuilder();
                        NodeList chars = property.getChildNodes();
                        for (int k=0;k<chars.getLength();k++){
                            text.append(chars.item(k).getNodeValue());
                        }
                        System.out.println(text.toString());
                    } else if (name.equalsIgnoreCase(PUB_DATE)){
                        System.out.println(property.getFirstChild().getNodeValue());
                    }
                    else if (name.equalsIgnoreCase(IMAGE)){
                        System.out.println(property.getAttributes().getNamedItem("url").getNodeValue());
                    }
                }

            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public static void main(String[] aeg){
    new FeedParser("http://www.pcworld.com/index.rss").parse();
    }
}

虽然我的回答很晚,但我希望它可以帮助其他人

答案 1 :(得分:1)

你正在重新发明轮子。您可以使用android-rssdroidQuery(最初发布here)来简化所有内容:

final RSSHandler handler = new RSSHandler(new RSSConfig());
$.ajax(new AjaxOptions().url(options.url())
                        .type("GET")
                        .dataType("XML")
                        .context(this)
                        .SAXContentHandler(handler)
                        .success(new Function() {
                            @Override
                            public void invoke($ droidQuery, Object... params) {
                                RSSFeed feed = handler.feed();
                                List<RSSItem> = feed.getItems();
                                //use this list to update your list adapter, then call the method "getThumbnails()" to get the images associated with the feed item.
                            }
                        }));