开发者

How to get rss feeds android?

开发者 https://www.devze.com 2023-01-22 18:19 出处:网络
I have this url here: http://www.webpronews.com/feeds Now i need开发者_开发技巧 to get the feeds and display it in android. Any clue?I use the lib xmlpull_1_1_3_4c.jar and for example read twitter fe

I have this url here: http://www.webpronews.com/feeds

Now i need开发者_开发技巧 to get the feeds and display it in android. Any clue?


I use the lib xmlpull_1_1_3_4c.jar and for example read twitter feeds (rss) like below.

XML Pull is open source. You just need to adjust the tags according to your feed. If you cannot find the jar online, I can email it to you. I don't remember where I got it from, it used to be at xmlpull.org, but not sure where it is now. I got it somewhere linked from http://www.ibm.com/developerworks/opensource/library/x-android/

import org.developerworks.android.FeedParser;
import org.developerworks.android.FeedParserFactory;
import org.developerworks.android.Message;
import org.developerworks.android.ParserType;
import org.xmlpull.v1.XmlSerializer;

....
loadFeed(ParserType.ANDROID_SAX);
....



private void loadFeed(ParserType type){
     try{
      Log.i("AndroidNews", "ParserType="+type.name());
      FeedParser parser = FeedParserFactory.getParser(type);
      long start = System.currentTimeMillis();
      messages = parser.parse();
      long duration = System.currentTimeMillis() - start;
      String xml = writeXml();      
      titles = new ArrayList<String>(messages.size());
      for (Message msg : messages){
       titles.add(msg.getTitle());
      }
     } catch (Throwable t){
      Log.e("AndroidNews",t.getMessage(),t);
     }
    }

private String writeXml() {


 XmlSerializer serializer = Xml.newSerializer();
  StringWriter writer = new StringWriter();
  try {
   serializer.setOutput(writer);
   serializer.startDocument("UTF-8", true);
   serializer.startTag("", "messages");
   serializer.attribute("", "number", String.valueOf(messages.size()));
   for (Message msg: messages){
    serializer.startTag("", "message");
    serializer.attribute("", "date", msg.getDate());
    serializer.startTag("", "title");
    serializer.text(msg.getTitle());
    serializer.endTag("", "title");
    serializer.startTag("", "url");
    serializer.text(msg.getLink().toExternalForm());
    serializer.endTag("", "url");
    serializer.startTag("", "body");
    serializer.text(msg.getDescription());
    serializer.endTag("", "body");
    serializer.endTag("", "message");
   }
   serializer.endTag("", "messages");
   serializer.endDocument();
   return writer.toString();
  } catch (Exception e) {
   throw new RuntimeException(e);
  }
 }

Edit:

This is the entire class that populates the feeds to a list view, using a ArrayAdapter, there's no cursor on any database though, since I don't store the feeds locally:

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.util.Xml;
import android.view.Gravity;
import android.view.View;
import android.widget.*;
import org.developerworks.android.FeedParser;
import org.developerworks.android.FeedParserFactory;
import org.developerworks.android.Message;
import org.developerworks.android.ParserType;
import org.xmlpull.v1.XmlSerializer;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

public class Twitter extends BaseActivity implements
        AdapterView.OnItemClickListener {

    private List<Message> messages;
    private List<String> titles;

    //TweetsAdapter ta = new TweetsAdapter(this);
    public ListView lstTweets = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.twitter);

        // set header title
        ((TextView)findViewById(R.id.txtHeaderTitle)).setText( Html.fromHtml("<b>" + getResources().getString(R.string.activity_title_twitter) +"</b>"));

        // highlight icon
        ImageButton btn = (ImageButton)findViewById(R.id.btnTwitter);
        btn.setBackgroundResource(R.drawable.menu_icon_twitter_active);

        // load list of tweets
        lstTweets = (ListView)findViewById(R.id.lstTweets);
        lstTweets.setOnItemClickListener(this);

        new AsyncTask<Void, Void, Void>() {

            ProgressDialog p;
            boolean success = false;

            @Override
            protected void onPostExecute(Void aVoid) {
                p.dismiss();
                if (!success) {

                    Twitter.this.runOnUiThread(new Runnable() {
                        public void run() {
                            Toast toast = Toast.makeText(Twitter.this, "Sorry, could not connect to Twitter.", Toast.LENGTH_LONG);
                            toast.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL, 0, 0);
                            toast.show();
                        }
                    });

                } else {
                    ArrayAdapter<String> adapter =
                        new ArrayAdapter<String>(Twitter.this, R.layout.twitter_list_row,titles);
                    lstTweets.setAdapter(adapter);
                }
            }

            @Override
            protected void onPreExecute() {
                p  = ProgressDialog.show(Twitter.this,"Loading...","...please wait a moment.");
            }

            @Override
            protected Void doInBackground(Void... params) {
                try {
                    loadFeed(ParserType.ANDROID_SAX);
                    if (messages!=null&&messages.size()>0) success = true;
                } catch (RuntimeException e) {}
                catch (Exception e) {}
                return null;
            }
        }.execute();



    }


    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
  Intent viewMessage = new Intent(Intent.ACTION_VIEW,
    Uri.parse(messages.get(position).getLink().toExternalForm()));
  this.startActivity(viewMessage);
    }


 private void loadFeed(ParserType type){
     try{
      Log.i("AndroidNews", "ParserType="+type.name());
      FeedParser parser = FeedParserFactory.getParser(type);
      long start = System.currentTimeMillis();
      messages = parser.parse();
      long duration = System.currentTimeMillis() - start;
      String xml = writeXml();      
      titles = new ArrayList<String>(messages.size());
      for (Message msg : messages){
       titles.add(msg.getTitle());
      }
     } catch (Throwable t){
      Log.e("AndroidNews",t.getMessage(),t);
     }
    }

    private String writeXml(){
  XmlSerializer serializer = Xml.newSerializer();
  StringWriter writer = new StringWriter();
  try {
   serializer.setOutput(writer);
   serializer.startDocument("UTF-8", true);
   serializer.startTag("", "messages");
   serializer.attribute("", "number", String.valueOf(messages.size()));
   for (Message msg: messages){
    serializer.startTag("", "message");
    serializer.attribute("", "date", msg.getDate());
    serializer.startTag("", "title");
    serializer.text(msg.getTitle());
    serializer.endTag("", "title");
    serializer.startTag("", "url");
    serializer.text(msg.getLink().toExternalForm());
    serializer.endTag("", "url");
    serializer.startTag("", "body");
    serializer.text(msg.getDescription());
    serializer.endTag("", "body");
    serializer.endTag("", "message");
   }
   serializer.endTag("", "messages");
   serializer.endDocument();
   return writer.toString();
  } catch (Exception e) {
   throw new RuntimeException(e);
  }
 }
}


That's not simple to implement.

A RSS file is an XML file which structure complies to a standard (fixed tag names).

In your application, you would need to:

  • Download the RSS feed: use HttpClient, services...
  • Extract the data out of XML: use a XML parser, some are provided
  • Store the data: the best solution is a SQLite database
  • Display the data: ListView with CursorAdapter pointing to the database


DavLink, is right. RSS parsing is not trivial.

It's fairly easy to setup an implementation of a SAX parser but the hard part is to be able to parse any and every feed under the sun.

You need to cater to all formats RSS 1, RSS 2, Atom etc. Even then you will have to contend with poorly formatted feeds.

I had faced similar problems in the past so decided to do my feed parsing on a server and just get the parsed contents. This allows me to run more complex libraries and parser which I can modify without pushing out updates for my app.

I have the following service running on AppEngine which allows for a much simpler XML / JSON parsing at your end. There is a fixed and simple structure to the response. You can use this for parsing

http://evecal.appspot.com/feedParser

You can send both POST and GET requests with the following parameters.

feedLink : The URL of the RSS feed response : JSON or XML as the response format

Examples:

For a POST request

curl --data-urlencode "feedLink=http://feeds.bbci.co.uk/news/world/rss.xml" --data-urlencode "response=json" http://evecal.appspot.com/feedParser

For GET request

evecal.appspot.com/feedParser?feedLink=http://feeds.nytimes.com/nyt/rss/HomePage&response=xml

My android app "NewsSpeak" uses this too.

After you get your information, you can use a simple listview with an arrayadapter having your array of items.

0

精彩评论

暂无评论...
验证码 换一张
取 消