Android RSS Feed

时间:2012-03-23 12:35:03

标签: java android eclipse rss helper

我正在为我在大学的最后一年项目创建一个应用程序..我正在尝试让RSS工作正常工作..我现在的问题是我创建了一个项目(RSSActivity)并让RSS源工作。然后我将所有文件(5个类和2个布局)复制并粘贴到适当的位置。有一些错误:找不到R,但是通过将包更改为项目(football_app)可以很容易地解决这个问题。我要做的是能够点击一个名为“新闻”的按钮,然后出现新闻..我遇到的问题是,当我现在点击“新闻”按钮时,它会说'不幸的足球应用已停止'..我已经尝试了意图中的每一个类,并且适当地更改了意图活动名称..任何人都可以帮助我..下面的代码......

 /////////////// HttpFeedSource.java

    package com.julian.football_app;

    import java.util.ArrayList;
    import java.util.List;

    class HttpFeedSource implements FeedSource {

        protected static final String URL = "http://www.skysports.com/rss/0,20514,11661,00.xml";

        public List<RSSItem> getFeed() {
            List<RSSItem> itemList = new ArrayList<RSSItem>();

            NewsParser parser = new NewsParser(URL);
            parser.parse();
            NewsParser.RssFeed feed = parser.getFeed();

            for (NewsParser.Item i : feed.getItems()) {
                itemList.add(new RSSItem(i.getUrl(), i.getTitle(), i.getDescription(), i.getimageUrl()));
            }
            return itemList;
        }

    }


    ////////////////////// FeedSource.java

        package com.julian.football_app;

    import java.util.List;

    interface FeedSource {

        List<RSSItem> getFeed();

}






<code> 

/////////////////////////////////////////////// //////////////////////////////////////////// //MockFeedSource.java < / p>

包com.julian.football_app;

import java.util.ArrayList; import java.util.List;

类MockFeedSource实现FeedSource {

public List<RSSItem> getFeed() {

    RSSItem item;
    final List<RSSItem> items = new ArrayList<RSSItem>();
    item = new RSSItem("Android Workshop er gøy", "http://www.ap.no", " this is the desc", "");
    items.add(item);
    item = new RSSItem("Android Workshop er gøy 2", "http://www.ap.no", "this is the desc", "");
    items.add(item);
    item = new RSSItem("Android Workshop er gøy3", "http://www.ap.no", "this is the desc", "");
    items.add(item);
    return items;

}

}

</code>



/////////////////////////////////////////////////////////////////////////////////////////// NewsParser.java

    package com.julian.football_app;

    import org.xml.sax.Attributes;
    import org.xml.sax.InputSource;
    import org.xml.sax.helpers.DefaultHandler;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    import java.io.InputStream;
    import java.net.URL;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.Locale;


    class NewsParser extends DefaultHandler {

        public static SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH);
        private String urlString;
        private RssFeed rssFeed;
        private StringBuilder text;
        private Item item;
        private boolean imgStatus;

        public NewsParser(String url) {
            this.urlString = url;
            this.text = new StringBuilder();
        }

        public void parse() {

            InputStream urlInputStream = null;
            SAXParserFactory spf;
            SAXParser sp;

            try {
                URL url = new URL(this.urlString);
                urlInputStream = url.openConnection().getInputStream();
                InputSource is = new InputSource(urlInputStream);
                is.setEncoding("ISO-8859-1");

                spf = SAXParserFactory.newInstance();
                if (spf != null) {
                    sp = spf.newSAXParser();
                    sp.parse(is, this);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                try {
                    if (urlInputStream != null) urlInputStream.close();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }

        public RssFeed getFeed() {
            return (this.rssFeed);
        }

        public void startElement(String uri, String localName, String qName,
                                 Attributes attributes) {
            if (qName.equalsIgnoreCase("channel"))
                this.rssFeed = new RssFeed();
            else if (qName.equalsIgnoreCase("item") && (this.rssFeed != null)) {
                this.item = new Item();
                this.rssFeed.addItem(this.item);
            } else if (qName.equalsIgnoreCase("image") && (this.rssFeed != null))
                this.imgStatus = true;
        }

        public void endElement(String uri, String localName, String qName) {
            if (this.rssFeed == null)
                return;

            if (qName.equalsIgnoreCase("item"))
                this.item = null;

            else if (qName.equalsIgnoreCase("image"))
                this.imgStatus = false;

            else if (qName.equalsIgnoreCase("title")) {
                if (this.item != null) this.item.title = this.text.toString().trim();
                else if (this.imgStatus) this.rssFeed.imageTitle = this.text.toString().trim();
                else this.rssFeed.title = this.text.toString().trim();
            } else if (qName.equalsIgnoreCase("link")) {
                if (this.item != null) this.item.link = this.text.toString().trim();
                else if (this.imgStatus) this.rssFeed.imageLink = this.text.toString().trim();
                else this.rssFeed.link = this.text.toString().trim();
            } else if (qName.equalsIgnoreCase("description")) {
                if (this.item != null) this.item.description = this.text.toString().trim();
                else this.rssFeed.description = this.text.toString().trim();
            } else if (qName.equalsIgnoreCase("url") && this.imgStatus)
                this.rssFeed.imageUrl = this.text.toString().trim();

            else if (qName.equalsIgnoreCase("language"))
                this.rssFeed.language = this.text.toString().trim();

            else if (qName.equalsIgnoreCase("generator"))
                this.rssFeed.generator = this.text.toString().trim();

            else if (qName.equalsIgnoreCase("copyright"))
                this.rssFeed.copyright = this.text.toString().trim();

            else if (qName.equalsIgnoreCase("pubDate") && (this.item != null)) {
                try {
                    this.item.pubDate = sdf.parse(this.text.toString().trim());
                } catch (ParseException e) {
                    throw new RuntimeException();
                }
            } else if (qName.equalsIgnoreCase("category") && (this.item != null))
                this.rssFeed.addItem(this.text.toString().trim(), this.item);

            this.text.setLength(0);
        }

        public void characters(char[] ch, int start, int length) {
            this.text.append(ch, start, length);
        }

        public static class RssFeed {
            public String title;
            public String description;
            public String link;
            public String language;
            public String generator;
            public String copyright;
            public String imageUrl;
            public String imageTitle;
            public String imageLink;

            private ArrayList<Item> items;
            private HashMap<String, ArrayList<Item>> category;

            public void addItem(Item item) {
                if (this.items == null)
                    this.items = new ArrayList<Item>();
                this.items.add(item);
            }

            public void addItem(String category, Item item) {
                if (this.category == null)
                    this.category = new HashMap<String, ArrayList<Item>>();
                if (!this.category.containsKey(category))
                    this.category.put(category, new ArrayList<Item>());
                this.category.get(category).add(item);
            }

            public ArrayList<Item> getItems() {
                return items;
            }
        }

        public static class Item implements Comparable<Item> {
            public String title;
            public String description;
            public String link;
            public Date pubDate;
            private String url;
            private String imageUrl;

            public String toString() {
                return (this.title + ": ");
            }

            public int compareTo(Item o) {
                return (int) (o.pubDate.getTime() - pubDate.getTime());
            }

            public Date getPubDate() {
                return pubDate;
            }

            public String getDescription() {
                return description;
            }


            public String getTitle() {
                return title;
            }

            public String getUrl() {
                return url;
            }

            public String getimageUrl() {
                return imageUrl;
            }


        }
    }





package com.julian.football_app;

import com.julian.football_app.R;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;

public class RSSActivity extends Activity {
    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main2);

        ListView rssItemList = (ListView) findViewById(R.id.rssListview);
        FeedSource feedSource = new HttpFeedSource();
        RSSItemAdapter adapter = new RSSItemAdapter(this, R.layout.rssitem, feedSource.getFeed());
        rssItemList.setAdapter(adapter);
    }


}

/////////RssItem

    package com.julian.football_app;

    import java.util.Date;

    class RSSItem {

        private String url;
        private String title;
        private String description;
        private String imageUrl;
        private Date pubDate;

        public RSSItem() {
        }

        public RSSItem(String url, String title, String description, String imageUrl) {
            this.url = url;
            this.title = title;
            this.description = description;
            this.imageUrl = imageUrl;

        }


        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public String getTitle() {
            return title;
        }

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

        public String getDescription() {
            return description;
        }

        public void setDesc(String description) {
            this.description = description;
        }

        public void setImageUrl(String imageUrl) {
            this.imageUrl = imageUrl;
        }
        public String getimageUrl() {
            return imageUrl;
        }
        public void setpubDate(Date pubDate){
            this.pubDate = pubDate;
        }
        public Date getpubDate(){
            return pubDate;
        }

    }

////////////////// RssItemAdaptor

    package com.julian.football_app;

    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.TextView;
    import java.util.List;

    import com.julian.football_app.R;

    class RSSItemAdapter extends ArrayAdapter<RSSItem> {

        private final Context context;

        public RSSItemAdapter(Context context, int textViewResourceId,
                List<RSSItem> items) {
            super(context, textViewResourceId, items);
            this.context = context;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;
            if (v == null) {
                LayoutInflater vi = (LayoutInflater) context
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = vi.inflate(R.layout.rssitem, null);
            }
            final RSSItem item = getItem(position);
            TextView title = (TextView) v.findViewById(R.id.title);
            TextView desc = (TextView) v.findViewById(R.id.description);
            TextView url = (TextView) v.findViewById(R.id.url);

            // this is what is viewed
            title.setText(item.getTitle());
            desc.setText(item.getDescription());
            url.setText(item.getimageUrl());
            return v;

        }

    }

///This is the button i want to display the Rss Feed
package com.julian.football_app;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

    public class Menu extends Activity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.menu);

            //setting the buttons
            Button btnews1 = (Button) findViewById(R.id.news_1);
            btnews1.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Intent news1intent = new Intent(Menu.this, news_1.class);
                    Menu.this.startActivity(news1intent);   
                }
            });

感谢您查看我的代码...如果有人可以帮助我,我将非常感激:)(我知道它在意图中说news_1.class ..它唯一因为我尝试了一切并回到原始状态..)

这些是LogCat中出现的错误:

03-23 13:54:16.118: E/AndroidRuntime(553): FATAL EXCEPTION: main
03-23 13:54:16.118: E/AndroidRuntime(553):  at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1508)
03-23 13:54:16.118: E/AndroidRuntime(553):  at android.app.Instrumentation.execStartActivity(Instrumentation.java:1384)
03-23 13:54:16.118: E/AndroidRuntime(553):  at android.app.Activity.startActivityForResult(Activity.java:3190)
03-23 13:54:16.118: E/AndroidRuntime(553):  at android.app.Activity.startActivity(Activity.java:3297)
03-23 13:54:16.118: E/AndroidRuntime(553):  at com.julian.football_app.Menu$1.onClick(Menu.java:24)
03-23 13:54:16.118: E/AndroidRuntime(553):  at android.view.View.performClick(View.java:3460)
03-23 13:54:16.118: E/AndroidRuntime(553):  at android.view.View$PerformClick.run(View.java:13955)
03-23 13:54:16.118: E/AndroidRuntime(553):  at android.os.Handler.handleCallback(Handler.java:605)
03-23 13:54:16.118: E/AndroidRuntime(553):  at android.os.Handler.dispatchMessage(Handler.java:92)
03-23 13:54:16.118: E/AndroidRuntime(553):  at android.os.Looper.loop(Looper.java:137)
03-23 13:54:16.118: E/AndroidRuntime(553):  at android.app.ActivityThread.main(ActivityThread.java:4340)
03-23 13:54:16.118: E/AndroidRuntime(553):  at java.lang.reflect.Method.invokeNative(Native Method)
03-23 13:54:16.118: E/AndroidRuntime(553):  at java.lang.reflect.Method.invoke(Method.java:511)
03-23 13:54:16.118: E/AndroidRuntime(553):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
03-23 13:54:16.118: E/AndroidRuntime(553):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
03-23 13:54:16.118: E/AndroidRuntime(553):  at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:2)

听起来该应用正在遇到异常。要查找原因,您需要使用LogCat查看异常详细信息,这将显示代码中存在问题的位置。

答案 1 :(得分:0)

了解您的应用程序如何脱轨:

E/AndroidRuntime(553): at android.app.Activity.startActivity(Activity.java:3297) 03-23 13:54:16.118: 
E/AndroidRuntime(553): at com.julian.football_app.Menu$1.onClick(Menu.java:24) 03-23 13:54:16.118: 

我的感觉是,这根本不是关于RSS的。我认为您需要修复应用程序中的活动之间的Intent导航。您可以尝试阻止活动中的所有行为(注释掉onCreate()或其他有趣的部分),并确保您可以在活动之间平滑导航。然后重新启用活动并确保它们在您输入时不会爆炸。

另请参阅MH关于检查所有活动是否在您的清单中的评论。

然后拿出那句话说:

import com.julian.football_app.R;

如果您无法在不包含.R的情况下编译代码,那么您就会做错事。尝试保存所有源文件,删除gen目录的内容,然后选择Project > Clean