RSS Reading Series in Android : One

Dear Friends

Now we have become an android programmer who can play with android tech. You know Various news sites eg NDTV, ZEE NEWS , AAJ TAK release their RSS feeds.

We access these RSS Feeds , parse them and show their content in our mobile application. News sites or many of other sites release their RSS feeds free of cost and don’t even charge when we integrate RSS feed to android/IOS mobile application. So now the question is why even site owners bother to release RSS feed. ??

[Pause].

Because accessing content via RSS Feeds increases web traffic count of site. Which in turns increase the probability of the site to appear in organic search result and this thing directly increases the probability of getting new business.

Anyways if we go deeper into that we might miss our blog path.

Please have a look at below code for android application

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

import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import android.widget.Button;
import android.widget.EditText;

import com.ct.app.freewithads.R;
import com.pharmaguideline.app.pojo.IRSSItem;
import com.pharmaguideline.app.pojo.RSSItem;

import java.util.ArrayList;

public class RSSMainActivity extends Activity {
    EditText title,link,description;

    ArrayList mList;

    Button b1,b2;
    private String finalUrl="http://www.relsellglobal.in/category/android-development/feed/";
    private RSSHandleXml obj;

    Handler mHandlerForRSSData = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what == 1) {
                IRSSItem localObj = mList.get(0);   /// here we are getting the first element
                title.setText(localObj.getTitle());
                link.setText(localObj.getLink());
                description.setText(((RSSItem)localObj).getDescription());
            }

        }
    };



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

        mList = new ArrayList();

        title = (EditText) findViewById(R.id.editText);
        link = (EditText) findViewById(R.id.editText2);
        description = (EditText) findViewById(R.id.editText3);

        b1=(Button)findViewById(R.id.button);
        b2=(Button)findViewById(R.id.button2);
        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                obj = new RSSHandleXml(finalUrl,mList,mHandlerForRSSData);
                obj.fetchXML();

            }
        });

        b2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Intent in=new Intent(RSSMainActivity.this,second.class);
                //startActivity(in);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @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();

        //noinspection SimplifiableIfStatement
        //if (id == R.id.action_settings) {
          //  return true;
        //}
        return super.onOptionsItemSelected(item);
    }
}

There a few code snippets in the above code I would like to describe about.

 Handler mHandlerForRSSData = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what == 1) {
                IRSSItem localObj = mList.get(0);   /// here we are getting the first element
                title.setText(localObj.getTitle());
                link.setText(localObj.getLink());
                description.setText(((RSSItem)localObj).getDescription());
            }

        }
    };

So handlers are the object provided by android OS which help in transferring message Objects from one thread to another. Most of the time from Asynctask to UIthread.

For more information regarding handler please study my another blog post

Also you can visit link

Now back to our RSS Activity

b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                obj = new RSSHandleXml(finalUrl,mList,mHandlerForRSSData);
                obj.fetchXML();

            }
        });

In this code we are calling RSSHandleXml Parser passing its some parameters. and then getting results wrapped in a Object.

public class RSSHandleXml implements IRSSHandler{
    private String title = "title";
    private String link = "link";
    private String description = "description";
    private String urlString = null;

    private RSSItem item;
    private boolean itemInitialized;
    String text=null;
    private ArrayList mItemList;


    private XmlPullParserFactory xmlFactoryObject;
    public volatile boolean parsingComplete = true;

    private Handler forRSS;

    public RSSHandleXml(String url,ArrayList list,Handler handler){
        this.urlString = url;
        this.mItemList = list;
        this.forRSS = handler;
    }

    public String getTitle(){
        return title;
    }

    public String getLink(){
        return link;
    }

    public String getDescription(){
        return description;
    }

    public void parseXMLAndStoreIt(XmlPullParser myParser) {
        int event;


        try {
            event = myParser.getEventType();

            while (event != XmlPullParser.END_DOCUMENT) {
                String name=myParser.getName();

                switch (event){
                    case XmlPullParser.START_TAG:
                        if(name.equals("item")){
                            item = new RSSItem();
                            itemInitialized = true;
                        }

                        break;

                    case XmlPullParser.TEXT:
                        text = myParser.getText();
                        break;

                    case XmlPullParser.END_TAG:
                        if(name.equals("item")){
                            itemInitialized = false;
                            mItemList.add(item);
                        } else if (name.equals("title") && itemInitialized) {
                            title = Html.fromHtml(text).toString();
                            item.setTitle(title);
                        } else if (name.equals("link") && itemInitialized) {
                            link = Html.fromHtml(text).toString();
                            item.setLink(link);
                        } else if (name.equals("description") && itemInitialized) {
                            description = text;
                            item.setDescription(description);
                        } else if (name.equals("pubDate") && itemInitialized) {
                            item.setPubDate(Html.fromHtml(text).toString());
                        }
                        break;
                }

                event = myParser.next();
            }

            parsingComplete = false;
        }

        catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void fetchXML(){
        Thread thread = new Thread(new Runnable(){
            @Override
            public void run() {

                try {
                    URL url = new URL(urlString);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

                    conn.setReadTimeout(10000 /* milliseconds */);
                    conn.setConnectTimeout(15000 /* milliseconds */);
                    conn.setRequestMethod("GET");
                    conn.setRequestProperty("Content-type","application/rss+xml");
                    conn.setDoInput(true);

                    // Starts the query
                    conn.connect();
                    InputStream stream = conn.getInputStream();



                    /*InputStreamReader inputStreamReader = new InputStreamReader(stream,"UTF-8");
                    BufferedReader r = new BufferedReader(inputStreamReader);

                    StringBuilder total = new StringBuilder();
                    String line;
                    Log.v("Input = ", "start reading");
                    while ((line = r.readLine()) != null) {
                        Log.v("Input = ","\n");
                        Log.v("Input = ",line);
                    }*/



                    xmlFactoryObject = XmlPullParserFactory.newInstance();
                    XmlPullParser myparser = xmlFactoryObject.newPullParser();

                    myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);

                    myparser.setInput(stream,null);
                    parseXMLAndStoreIt(myparser);
                    stream.close();
                    Message msg = new Message();
                    msg.what = 1;
                    forRSS.sendMessage(msg);

                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
    }
}

and thats how we will able to get RSS feed content in our android application. There is more to it but we will discuss that in Part Two. [ To be released soon ].

Code for the project is at Github link.

 

 

 

 

 

Thanks