Rss reader android tutorial

Android — RSS Reader

RSS stands for Really Simple Syndication. RSS is an easy way to share your website updates and content with your users so that users might not have to visit your site daily for any kind of updates.

RSS Example

RSS is a document that is created by the website with .xml extension. You can easily parse this document and show it to the user in your application. An RSS document looks like this.

RSS Elements

An RSS document such as above has the following elements.

This element is used to describe the RSS feed

Defines the title of the channel

Defines the hyper link to the channel

Describes the channel

Parsing RSS

Parsing an RSS document is more like parsing XML. So now lets see how to parse an XML document.

For this, We will create XMLPullParser object , but in order to create that we will first create XmlPullParserFactory object and then call its newPullParser() method to create XMLPullParser. Its syntax is given below −

The next step involves specifying the file for XmlPullParser that contains XML. It could be a file or could be a Stream. In our case it is a stream.Its syntax is given below −

The last step is to parse the XML. An XML file consist of events , Name , Text , AttributesValue e.t.c. So XMLPullParser has a separate function for parsing each of the component of XML file. Its syntax is given below −

The method getEventType returns the type of event that happens. e.g: Document start, tag start e.t.c. The method getName returns the name of the tag and since we are only interested in temperature, so we just check in conditional statement that if we got a temperature tag, we call the method getAttributeValue to return us the value of temperature tag.

Apart from the these methods, there are other methods provided by this class for better parsing XML files. These methods are listed below −

Sr.No Component & description
1

This method just Returns the number of attributes of the current start tag.

This method returns the name of the attribute specified by the index value.

This method returns the Returns the current column number, starting from 0.

This method returns Returns the current depth of the element.

Returns the current line number, starting from 1.

This method returns the name space URI of the current element.

This method returns the prefix of the current element.

This method returns the name of the tag.

This method returns the text for that particular element.

This method checks whether the current TEXT event contains only white space characters.

Example

Here is an example demonstrating the use of XMLPullParser class. It creates a basic Parsing application that allows you to parse an RSS document present here at /android/sampleXML.xml and then show the result.

To experiment with this example, you can run this on an actual device or in an emulator.

Sr.No Method & description
1
Steps Description
1 You will use Android studio to create an Android application under a package com.example.sairamkrishna.myapplication.
2 Modify src/MainActivity.java file to add necessary code.
3 Modify the res/layout/activity_main to add respective XML components.
4 Create a new java file under src/HandleXML.java to fetch and parse XML data.
5 Create a new java file under src/second.java to display result of XML
5 Modify AndroidManifest.xml to add necessary internet permission.
6 Run the application and choose a running android device and install the application on it and verify the results.

Following is the content of the modified main activity file src/MainActivity.java.

Following is the content of the java file src/HandleXML.java.

Create a file and named as second.java file under directory java/second.java

Create a xml file at res/layout/second_activity.xml

Modify the content of res/layout/activity_main.xml to the following −

Modify the res/values/string.xml to the following

This is the default AndroidManifest.xml.

Let’s try to run your application. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project’s activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −

Just press the Fetch Feed button to fetch RSS feed. After pressing, following screen would appear which would show the RSS data.

Источник

Rss reader android tutorial

Пролог

Чтение RSS — одна из самых важных и широко используемых функций в мобильных приложениях, на веб сайтах.

Перед тем, как мы погрузимся в разработку RSS читалки, хотим сказать, что нельзя построить отличное здание на слабом фундаменте.

Поэтому сначала мы создадим очень простое приложение для изучения основ функции чтения RSS на Kotlin. В следующих статьях мы будем использовать MVVM для улучшения структуры кода и перепишим наш RSS Reader.

Во время нашего погружения в разработку, мы будем использовать несколько вспомогательных библиотек, таких как: CardView, RecyclerView, Glide, Jsoup.

Итак, давайте начнем разрабатывать. Возможно, Вам будет интересно, что мы собираемся разработать. Вот так будет выглядеть наше приложение.

Разработка RSS Reader

Итак, наш проект состоит из:

  • Активити MainActivity
  • Фрагмента под названием RSSFragment (тип фрагмента список — «Fragment (List)»);
  • Адаптера Recyclerview с названием MyItemRecylcerviewAdapter;
  • Модель с названием класса RSSItem для хранения определенных данных элемента RSS;
  • Класс парсера для разбора входящих потоков;
  • Класс AppGlideModule, необходимый для Glide.

Ниже приведен код для каждого из файлов, мы рассмотрим их один за другим.

MainActivity.kt

В методе onCreate вызываем RSSFragment.

Распределение кода по фрагментам.

Фрагменты — это легкие, повторно используемые компоненты пользовательского интерфейса, которые можно использовать в разработке пользовательского интерфейса в Android. Вызовы активити — тяжелый процесс для ОС Android по сравнению с фрагментом. ОС Android может отклонять действия, вызывающие запросы приложения.

Вы, должно быть, сталкивались с описанным выше в реальной жизни, когда ваше приложение перестает реагировать на сенсорные события на экране. Причем виновата здесь не только активити.

Согласно официальной документации Android:

Вы можете думать о фрагменте, как о модульном разделе действий, который имеет свой собственный жизненный цикл, получает свои собственные входные события и который вы можете добавлять или удалять во время выполнения действия (что-то вроде «вспомогательного действия», которое вы можно повторно использовать в различных действиях).

Поэтому мы будем использовать фрагменты в нашем приложении.

Изучив выше код, Вы обнаружите, что это очень просто. Никаких сложных задач не происходит.

В методе onActivityCreated мы вызываем AsyncTask, чтобы запросить данные RSS-канала из сети, чтобы поток пользовательского интерфейса оставался свободным для выполнения некоторых вещей, таких как показ анимации. Более конкретно, ниже представлен класс asynctask.

Ничего сложного здесь нет, мы просто делаем запрос на получение потока с заданного URL. Убедитесь, что вы предоставили необходимые разрешения в Android Manifest.xml для доступа в Интернет.

В приведенном выше коде мы получаем поток c сервера при переходе по данной ссылке RSS. Чтобы упростить понимание кода, мы здесь не игнорируем состояния сетевых ошибок.

Как только мы получаем поток ввода, мы передаем его нашему классу парсера

Наш парсер RSS основан на XMLPullparser в android.

Итак, теперь вызов RSSParser будет анализировать входной поток и помещать все элементы в ArrayList. Если мы сосредоточимся на методе синтаксического анализа, мы увидим, что XMLPullparser вызвал события для начального и конечного тегов XML, присутствующих в RSS-канале.

Наконец, вот файлы Gradle, которые показывают зависимости, используемые в нашем приложении. Ниже файл Gradle корневого уровня.

Файл Gradle

Улучшение кода с использованием MVVM будет объяснено в следующей статье нашего блога.

Источник

Building a simple RSS reader — full tutorial with code

For this Android developer tutorial, we are going to create a simple RSS reader app. This app would fetch RSS feeds from a single, user specified internet address, and display the contents using a RecyclerView. If you aren’t familiar with the RecyclerView widget, check out our previous tutorial on using a RecyclerView.

RSS, or Rich Site Summary, is an easy and efficient way to share snippets of frequently updated information such as blog entries or news items with subscribers. Almost every news website today has an RSS feed, and these feeds can be accessed through dedicated readers or through your favorite browser. An RSS feed usually contains a summary of the new content, rather than the entire news (or blog) article. To answer your question, yes, Android Authority has an RSS feed, available at http://feed.androidauthority.com/, and you should subscribe, if you haven’t already. 😀

Sample RSS Feed

An RSS feed is a plain text document, formatted in XML. Being XML, it is relatively easy for humans to read, and also not difficult for programs to parse. A sample XML document is shown below.

We can see from the sample above, the feed has a title, a description, link, last build date, a publish date and a time to live. For this tutorial, we are only interested in the title, description and link.

There are also two items in the feed, and each has a title, a description and a link, along with a guid (globally unique identifier) and publish date. Most feed items have other tags, but, for our simple RSS reader, we are only concerned with the title, description and link.

Источник

Building an RSS Reader for Android

Join the DZone community and get the full member experience.

This tutorial will walk through building an RSS reader on the Android platform (focusing on 3.0 + as it will be using Fragments). All the code is available as a complete, working Android app that you can fork/download and fire up straight away on a compatible Android device/emulator. So feel free to go grab that from GitHub before continuing.

It is not an unusual requirement for mobile apps these days to be able to consume an RSS feed from another site (or many) to aggregate the content — Or maybe you just want to build your own Android app now that Google has announced it will be retiring Reader.

Those of you who have worked with RSS in other JVM languages will know that there are plenty of libraries available that can handle parsing RSS — however, because the android platform doesn’t actually contain all the core java classes, almost all of the RSS libraries have not been supported.

Fear not though, as Java’s SAX parser is available, so with a bit of code we can get a custom RSS parser up and running in no time!

This walk through will cover off the basics of getting an RSS reader app up and running quickly and will also cover some details of Android’s fragment system for tablet optimization as well as some things to watch out for (such as changes in the platform that mean network operations cannot be run in the main thread, which requires some tweaking if you have worked on earlier versions).

All the code for the app is also available on our GitHub so feel free to fork that and try loading it up on your Android device/emulator.

Источник

Building an RSS Reader for Android (RIP Google Reader)

Join the DZone community and get the full member experience.

This tutorial will walk through building an RSS reader on the Android platform (focusing on 3.0 + as it will be using Fragments). All the code is available as a complete, working Android app that you can fork/download and fire up straight away on a compatible Android device/emulator. So feel free to go grab that from GitHub before continuing.

It is not an unusual requirement for mobile apps these days to be able to consume an RSS feed from another site (or many) to aggregate the content — Or maybe you just want to build your own Android app now that Google has announced it will be retiring Reader.

Those of you who have worked with RSS in other JVM languages will know that there are plenty of libraries available that can handle parsing RSS — however, because the android platform doesn’t actually contain all the core java classes, almost all of the RSS libraries have not been supported.

Parsing an RSS Feed:

  • startElement() — This is called by the parser every time a new XML node is found
  • endElement() — This is called by the parser every time an XML node is closed (e.g.

Let’s take a look at what our helpful RSS service is doing for us.

The first thing to note is that this class is extending Android’s AsyncTask- The reason for this is that since Android 3.0, you are no longer able to perform network operations in the main application thread, so being as our class is going to have to fetch some RSS feeds we are going to have to spin off a new thread.

As you can see, the constructor just sets some context info that we will use later on, and then builds a progress dialogue — this is then displayed in the onPreExecute() method — This lets us show a «loading» spinning disk whilst we fetch the data.

Android’s AsyncTask’s primary method that handles the actual work that you want to do asynchronously is called «doInBackground()» — In our case, this is simple — we just invoke our SAX RSS parser and fetch our feed data:

Finally, we will override the «onPostExecute()» method of the async class to use our newly fetched list to populate our ListFragment. You note how when we overrode the doInBackground() method earlier we set the return to List of Articles (where Article is my simple POJO containing my RSS blog post info) — well this must correspond to the argument of the «onPostExecute()» method, which looks like this:

Actually, all we really needed to do in this method would be pass our new List or articles to the ListFragment and notify it of the change as below:

However, in our application we have added a bit more sugar on the app — and we have actually backed the app with a simple DB that records the unique IDs of the posts and tracks whether or not they have been read to provide a nicer highlighting of listed blog posts.

So that’s it — there’s plenty more you can add to your RSS reader app, such as storing posts for reading later, and supporting multiple feeds/feed types — but feel free to fork the code on GitHub, or just download on to your android device to enjoy all our NerdAbility updates!

Источник

Читайте также:  Сделать apps для андроид
Оцените статью