RSS stands for rich site summary almost all website has it. It contains the latest information from that website for example if it is a news website then it’s RSS feeds can contain website basic information like title, description, link. Mostly RSS feeds are in the XML document. In Android, we can read this information in the XML document by using DOM (Document Object Model)  parsing. So in this post, we will build a simple android RSS feed reader application. So let’s get started.

Download project from below

Output video what we are going to build

Android RSS Feed Reader Application Development | loopwiki.com

1. Create new class Package name => ReadRss.java.  This is async task which will download and display RSS feeds from website. Paste below lines in it.

package com.loopwiki.rssredaer;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

/**
 * Created by rishabh on 31-01-2016.
 */
public class ReadRss extends AsyncTask<Void, Void, Void> {
    Context context;
    String address = "http://www.sciencemag.org/rss/news_current.xml";
    ProgressDialog progressDialog;
    ArrayList<FeedItem> feedItems;
    RecyclerView recyclerView;
    URL url;

    public ReadRss(Context context, RecyclerView recyclerView) {
        this.recyclerView = recyclerView;
        this.context = context;
        progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("Loading...");
    }

    //before fetching of rss statrs show progress to user
    @Override
    protected void onPreExecute() {
        progressDialog.show();
        super.onPreExecute();
    }


    //This method will execute in background so in this method download rss feeds
    @Override
    protected Void doInBackground(Void... params) {
        //call process xml method to process document we downloaded from getData() method
        ProcessXml(Getdata());

        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        progressDialog.dismiss();
        FeedsAdapter adapter = new FeedsAdapter(context, feedItems);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.addItemDecoration(new VerticalSpace(20));
        recyclerView.setAdapter(adapter);

    }

    // In this method we will process Rss feed  document we downloaded to parse useful information from it
    private void ProcessXml(Document data) {
        if (data != null) {
            feedItems = new ArrayList<>();
            Element root = data.getDocumentElement();
            Node channel = root.getChildNodes().item(1);
            NodeList items = channel.getChildNodes();
            for (int i = 0; i < items.getLength(); i++) {
                Node cureentchild = items.item(i);
                if (cureentchild.getNodeName().equalsIgnoreCase("item")) {
                    FeedItem item = new FeedItem();
                    NodeList itemchilds = cureentchild.getChildNodes();
                    for (int j = 0; j < itemchilds.getLength(); j++) {
                        Node cureent = itemchilds.item(j);
                        if (cureent.getNodeName().equalsIgnoreCase("title")) {
                            item.setTitle(cureent.getTextContent());
                        } else if (cureent.getNodeName().equalsIgnoreCase("description")) {
                            item.setDescription(cureent.getTextContent());
                        } else if (cureent.getNodeName().equalsIgnoreCase("pubDate")) {
                            item.setPubDate(cureent.getTextContent());
                        } else if (cureent.getNodeName().equalsIgnoreCase("link")) {
                            item.setLink(cureent.getTextContent());
                        } else if (cureent.getNodeName().equalsIgnoreCase("media:thumbnail")) {
                            //this will return us thumbnail url
                            String url = cureent.getAttributes().item(0).getTextContent();
                            item.setThumbnailUrl(url);
                        }
                    }
                    feedItems.add(item);


                }
            }
        }
    }

    //This method will download rss feed document from specified url
    public Document Getdata() {
        try {
            url = new URL(address);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            InputStream inputStream = connection.getInputStream();
            DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = builderFactory.newDocumentBuilder();
            Document xmlDoc = builder.parse(inputStream);
            return xmlDoc;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

2.Create new class Package name => FeedItem.java. This class is the model of our single RSS feed. Add following lines in it

package com.loopwiki.rssredaer;

/**
 * Created by rishabh on 24-02-2016.
 */
public class FeedItem {
    String title;
    String link;
    String description;
    String pubDate;
    String thumbnailUrl;

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

    public String getDescription() {
        return description;
    }

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

    public String getPubDate() {
        return pubDate;
    }

    public void setPubDate(String pubDate) {
        this.pubDate = pubDate;
    }

    public String getThumbnailUrl() {
        return thumbnailUrl;
    }

    public void setThumbnailUrl(String thumbnailUrl) {
        this.thumbnailUrl = thumbnailUrl;
    }
}

3. Now we are using Recyclerview so we have to create Adapter to feed.  Create new class Package name => FeedsAdapter.java.  Add following lines in it.

package com.loopwiki.rssredaer;

import android.content.Context;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;

/**
 * Created by rishabh on 26-02-2016.
 */
public class FeedsAdapter extends RecyclerView.Adapter<FeedsAdapter.MyViewHolder> {
    ArrayList<FeedItem>feedItems;
    Context context;
    public FeedsAdapter(Context context, ArrayList<FeedItem>feedItems){
        this.feedItems=feedItems;
        this.context=context;
    }
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(context).inflate(R.layout.custum_row_news_item,parent,false);
        MyViewHolder holder=new MyViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        YoYo.with(Techniques.FadeIn).playOn(holder.cardView);
        FeedItem current=feedItems.get(position);
        holder.Title.setText(current.getTitle());
        holder.Description.setText(current.getDescription());
        holder.Date.setText(current.getPubDate());
        Picasso.with(context).load(current.getThumbnailUrl()).into(holder.Thumbnail);

    }



    @Override
    public int getItemCount() {
        return feedItems.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        TextView Title,Description,Date;
        ImageView Thumbnail;
        CardView cardView;
        public MyViewHolder(View itemView) {
            super(itemView);
            Title= (TextView) itemView.findViewById(R.id.title_text);
            Description= (TextView) itemView.findViewById(R.id.description_text);
            Date= (TextView) itemView.findViewById(R.id.date_text);
            Thumbnail= (ImageView) itemView.findViewById(R.id.thumb_img);
            cardView= (CardView) itemView.findViewById(R.id.cardview);
        }
    }
}

4. Create new layout file layout=>custum_row_news_item.xml which will be a design of our single recyclerview item. Add following lines to it.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:id="@+id/cardview"
    app:cardElevation="2dp"
    app:cardCornerRadius="2dp">

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

        <TextView
            android:id="@+id/date_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:layout_margin="@dimen/activity_horizontal_margin"
            android:textAppearance="?android:attr/textAppearanceSmall" />

        <ImageView
            android:id="@+id/thumb_img"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:layout_below="@+id/date_text"
            android:layout_centerHorizontal="true" />

        <TextView
            android:ellipsize="end"
            android:id="@+id/title_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/thumb_img"
            android:layout_centerHorizontal="true"
            android:background="#80000000"
            android:padding="8dp"
            android:gravity="center"
            android:lines="1"
            android:textAppearance="?android:attr/textAppearanceLargeInverse" />

        <TextView
            android:ellipsize="end"
            android:id="@+id/description_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="16dp"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:layout_marginTop="14dp"
            android:layout_below="@+id/thumb_img"
            android:layout_alignRight="@+id/date_text"
            android:layout_alignEnd="@+id/date_text" />
    </RelativeLayout>


</android.support.v7.widget.CardView>

5. Now we want to add some space between recyclerview items. So to do that we will create new item decoration class Package name => VerticalSpace.java.

package com.loopwiki.rssredaer;

import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
 * Created by rishabh on 01-03-2016.
 */
public class VerticalSpace extends RecyclerView.ItemDecoration {
    int Space;
    public VerticalSpace(int Space){
        this.Space=Space;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        outRect.left=Space;
        outRect.bottom=Space;
        outRect.right=Space;
        if (parent.getChildLayoutPosition(view)==0){
            outRect.top=Space;
        }
    }
}

6. Now we have to create an activity to add recyclerview in its layout and we can call our ReadRss async task from there. So create new class Package name => MainActivity.java.  Add following lines in it.

package com.loopwiki.rssredaer;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {
    RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        //Call Read rss asyntask to fetch rss
        ReadRss readRss = new ReadRss(this, recyclerView);
        readRss.execute();
    }

}

Create new layout file layout=>activity_main.xml. Add following lines to it.

<?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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/activity_main">

    <android.support.v7.widget.RecyclerView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/recyclerview"
        />
</RelativeLayout>

7.Inside manifest.xml paste below lines

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.loopwiki.rssredaer">

    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:screenOrientation="portrait"
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>


</manifest>

8.Inside values=>colors.xml paste below lines

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
</resources>

9.Inside values=>styles.xml paste below lines

<resources>

    <! – Base application theme. – >
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <! – Customize your theme here. – >
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

</resources>

10.Inside values=>strings.xml

<resources>
    <string name="app_name">RssReader</string>
    <string name="action_settings">Settings</string>
</resources>

10. Now run your application and see the results If you still have any queries, please post them in the comments section below, I will be happy to help you.

Author

Hello there, My name is Amardeep founder of loopwiki.com. I have experience in many technologies like Android, Java, Php, etc. In this variety of technologies, I love Android App Development. If you have any idea and you want me to develop for you then let's have chat Conatct

38 Comments

  1. Great tutorial thanks for this. I have downloaded the project migrated to AndroidX but i take the bellow error:
    java.lang.NullPointerException: Attempt to invoke virtual method ‘int java.util.ArrayList.size()’ on a null object reference
    at com.loopwiki.rssredaer.FeedsAdapter.getItemCount(FeedsAdapter.java:52).
    Please help me.

  2. I just change url to test.But App can’t open sir.It’s keep stopping.
    Then I download the apk from the link and it’s also can’t open.

  3. i tried to log in for downloading source code. i cant logged by all three platforms.please share the source code.

  4. sir pls help me ,how I make detailActivity? I have tried 2 days but I cant success 🙁 pls help me ,can you share code of detail activity making pls, thank you

    • Just create an Activity that has a webView in the Layout, pass the url of the seleted news from the List , then set the on the webview and thats all.

  5. Yadav sir, haven’t u put source code of main activity and am showing an error in main activity while creating just an simple object why is it so like “cannot resolve symbol”

  6. Sonam Bhadouria Reply

    i have follow your tutorial point to point but not getting data .getting error set adapter? help me out.

  7. I noticed that whenever I refresh the Feed, the width of the display shrinks. What could bee the problem? How can i retain the width = match_parent , Hight = match_parent?

      • sir can you plss help me out in my problem,plsss my problem is as shown below
        “Yadav sir, haven’t u put source code of main activity and am showing an error in main activity while creating just an simple object why is it so like “cannot resolve symbol””

      • Hi I am getting the same issue. How did you fix it? Ive tried hard coding the size but it seems like its a problem on the RecyclerView end. Thanks in advance!

        • @David, sorry for replying late. What I did was to always check if the adapter contains data each time I fetch new items :

          if (recyclerView.getAdapter() == null || recyclerView.getAdapter().getItemCount() < 1){
          adapter = new FeedsAdapter(context, feedItems);
          recyclerView.setLayoutManager(new LinearLayoutManager(context));
          recyclerView.addItemDecoration(new VerticalSpace(20));
          recyclerView.setAdapter(adapter);
          }else {
          adapter = (FeedsAdapter)recyclerView.getAdapter();
          adapter.setItems(feedItems);
          adapter.notifyDataSetChanged();
          }

          This solved it.
          Note : If you are not using CardView, you dont need the item Decoration.

    • This is due to item decoration we have added due to that it’s shrinking on every refresh. Make sure you are calling adding of decoration only once on recyclerview.

  8. help me i stuck in here : Cannot resolve method ‘with(android.content.Context)’

  9. ahmad ibrahim Reply

    good tutorial hanks, please if your finish your tutorial show the screenshot of application developped

  10. harsh Lata Reply

    Can you please tell me how to get image url from tags and also from tag which has img tag inside of it. please

    • You can observe following part of above code it’s already parsing images from the feed

      else if (cureent.getNodeName().equalsIgnoreCase(“media:thumbnail”)) {
      //this will return us thumbnail url
      String url = cureent.getAttributes().item(0).getTextContent();
      item.setThumbnailUrl(url);
      }

    • Mate it’s simple to make details activity just set onclick listener on layout of recyclerview pass url of the feed using intent extras then inside details activity get that url and load it inside webview that’s all 🙂

      • Mohsin Shehzad Reply

        Sir my name is Mohsin Shehzad Sir I Try other news website link like new york times and other BBc like news provider
        on other sites it works well but cannot display picture or images can you have any solution to that problem please reply me as soon as possible

        • All feeds do not follow a specific pattern in display of information. What you have to do is to study the feed, maybe open it on a browser, and see how the nodes are arranged, then you will discover how to address the link that contains the images.

      • Please help me with this code. I am new to android programming but I need this code quickly, I promise you I will make myself butter, just help me?

  11. How to run new activity contains news details(full news description) when I click on it

    • else if (cureent.getNodeName().equalsIgnoreCase(“media:thumbnail”)) {
      //this will return us thumbnail url
      String url = cureent.getAttributes().item(0).getTextContent();
      item.setThumbnailUrl(url);
      }

      Debug this part of code you will find solution

  12. Hi, I followed your tutorial and it was just great, it’s all working as I wanted. But there’s one thing that’s left and I’m asking for, How can I activate the links so when I click an article it’s going to a browser and read the content of the news? I’m not sure if you already added this functionality or not but on my app it’s not working.
    Thanks alot for this great tutorial again

  13. Phani Raaj Reply

    Hello, My name is raaj and been trying to create a rss feed in my android using your source code. the problem is it works fine with your default rss feed url in the code but when i change the url. it displays plain xml code and no pictures either. What should i do? please help me im stuck here

    • Hii raaj , you have to see how information is distributed in the structure and modify readRss () method according to feed structure.

Write A Comment