android studio - 需要rss feed示例

时间:2016-07-12 08:15:28

标签: android listview android-studio android-fragments

我一直在尝试在Android上实现rss feed两天,并且无法在互联网上找到合适而简单的示例。我是使用WebView完成的,但它并不符合我的要求。任何人都可以给我一个简单的例子来获取诸如图像,标题,描述和日期之类的信息

这个应用程序没有加载任何我无法理解的问题

由于

    public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends ListFragment {

//        private TextView mRssFeed;

        public PlaceholderFragment() {
        }

//When I uncomment onCreateView it says unfortunately app has stopped

//        @Override
//        public View onCreateView(LayoutInflater inflater, ViewGroup container,
//                                 Bundle savedInstanceState) {
//            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
//            mRssFeed = (TextView) rootView.findViewById(R.id.rss_feed);
//            return rootView;
//        }

        @Override
        public void onStart() {
            super.onStart();
            new GetAndroidPitRssFeedTask().execute();
        }

    private String getAndroidPitRssFeed() throws IOException {
        InputStream in = null;
        String rssFeed = null;
            try {
                URL url = new URL("http://www.androidpit.com/feed/main.xml");
                HttpURLConnection conn = (HttpURLConnection)   url.openConnection();
                in = conn.getInputStream();
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                for (int count; (count = in.read(buffer)) != -1; ) {
                    out.write(buffer, 0, count);
                }
                byte[] response = out.toByteArray();
                rssFeed = new String(response, "UTF-8");
          }finally {
               if (in != null) {
                    in.close();
           }
         }
       return rssFeed;
    }

    private class GetAndroidPitRssFeedTask extends AsyncTask<Void, Void,    List<String>> {

            @Override
            protected List<String> doInBackground(Void... voids) {
                List<String> result = null;
                try {
                    String feed = getAndroidPitRssFeed();
                    result = parse(feed);
                } catch (XmlPullParserException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return result;
            }

            private List<String> parse(String rssFeed) throws XmlPullParserException, IOException {
                XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
                XmlPullParser xpp = factory.newPullParser();
                xpp.setInput(new StringReader(rssFeed));
                xpp.nextTag();
                return readRss(xpp);
            }

            private List<String> readRss(XmlPullParser parser)
                    throws XmlPullParserException, IOException {
                List<String> items = new ArrayList<>();
                parser.require(XmlPullParser.START_TAG, null, "rss");
                while (parser.next() != XmlPullParser.END_TAG) {
                    if (parser.getEventType() != XmlPullParser.START_TAG) {
                        continue;
                    }

                    String name = parser.getName();

                    if (name.equals("channel")) {
                        items.addAll(readChannel(parser));
                    } else {
                        skip(parser);
                    }
              }
              return items;
          }

          private List<String> readChannel(XmlPullParser parser)
                    throws IOException, XmlPullParserException {
                List<String> items = new ArrayList<>();
                parser.require(XmlPullParser.START_TAG, null, "channel");
                while (parser.next() != XmlPullParser.END_TAG) {
                    if (parser.getEventType() != XmlPullParser.START_TAG) {
                        continue;
                    }
                    String name = parser.getName();
                    if (name.equals("item")) {
                        items.add(readItem(parser));
                    } else {
                        skip(parser);
                    }
                }
                return items;
            }

            private String readItem(XmlPullParser parser) throws XmlPullParserException, IOException {
                String result = null;
                parser.require(XmlPullParser.START_TAG, null, "item");
                while (parser.next() != XmlPullParser.END_TAG) {
                    if (parser.getEventType() != XmlPullParser.START_TAG) {
                        continue;
                    }
                    String name = parser.getName();
                    if (name.equals("title")) {
                        result = readTitle(parser);
                    } else {
                        skip(parser);
                    }
                }


      return result;
        }

        // Processes title tags in the feed.
        private String readTitle(XmlPullParser parser)
                throws IOException, XmlPullParserException {
            parser.require(XmlPullParser.START_TAG, null, "title");
            String title = readText(parser);
            parser.require(XmlPullParser.END_TAG, null, "title");
            return title;
            }



 private String readText(XmlPullParser parser)
                throws IOException, XmlPullParserException {
            String result = "";
            if (parser.next() == XmlPullParser.TEXT) {
                result = parser.getText();
                parser.nextTag();
            }
            return result;
        }

            private void skip(XmlPullParser parser) throws XmlPullParserException, IOException {
                if (parser.getEventType() != XmlPullParser.START_TAG) {
                    throw new IllegalStateException();
                }
                int depth = 1;
                while (depth != 0) {
                    switch (parser.next()) {
                        case XmlPullParser.END_TAG:
                            depth--;
                            break;
                        case XmlPullParser.START_TAG:
                            depth++;
                            break;
                    }
                }
            }

            @Override
            protected void onPostExecute(List<String> rssFeed) {
                if (rssFeed != null) {
                    setListAdapter(new ArrayAdapter<>(
                            getActivity(),
                            android.R.layout.simple_list_item_1,
                            android.R.id.text1,
                            rssFeed));
                }
            }
        }
    }

这是fragment_main.xml包含relativelayout

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">


    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/rss_feed"
            android:text="@string/hello_world"
            android:paddingTop="@dimen/activity_vertical_margin"
            android:paddingBottom="@dimen/activity_vertical_margin"
            android:paddingLeft="@dimen/activity_horizontal_margin"
            android:paddingRight="@dimen/activity_horizontal_margin"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </ScrollView>
</RelativeLayout>

这是activity_main

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/container"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="arittek.com.androidpitrss.MainActivity"
    tools:showIn="@layout/activity_main">


</RelativeLayout>

2 个答案:

答案 0 :(得分:1)

我发现这两个项目很有用:

https://github.com/ShirwaM/Simplistic-RSS

https://github.com/matshofman/Android-RSS-Reader-Library

您可以下载它们并根据您的需求进行定制(ATOM / RSS /媒体等)

答案 1 :(得分:0)

它对我有用Simple-Rss2-Android

SimpleRss2Parser parser = new SimpleRss2Parser("http://pingeb.org/feed", 
    new SimpleRss2ParserCallback() {
        @Override
        public void onFeedParsed(List<RSSItem> items) {
            for(int i = 0; i < items.size(); i++){
                Log.d("SimpleRss2ParserDemo",items.get(i).getTitle());
            }
        }
        @Override
        public void onError(Exception ex) {
            Toast.makeText(mContext, ex.getMessage(), Toast.LENGTH_SHORT).show();
        }
    };
);
parser.parseAsync();