0

我是 android 开发应用程序的新手,我想将 rss url 解析为列表视图。代码正在运行,但我们想从 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;
}

}

监听器.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));
    }
}  
}
4

2 回答 2

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();
    }
}

虽然我的回答迟到了,但我希望它可以帮助别人

于 2016-07-01T17:48:52.643 回答
1

你正在重新发明轮子。您可以通过使用带有droidQuery的android-rss库来简化一切(最初发布在这里):

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.
                            }
                        }));
于 2013-10-20T14:44:03.350 回答