Wednesday 20 February 2013

Android RssFeed with Async Task example

In this blog i will show you how to how to parse Rss Feed. I am going to use Async Task which is very useful to do network operation.

We can do network operation with the help of Thread and Handler  but Async Task is more effective and optimal.

Screen Shots.























Create a project called AndroidRssFeed.
Step1)
Create a Activity named RssReaderActivity.java

package com.amit.rssfeed;

import java.util.List;
import com.amit.Utility.Utility;
import com.amit.adapter.RssReaderListAdapter;
import com.amit.data.AsyncTaskCompletionListener;
import com.amit.data.RssFeedStructure;
import com.amit.network.RssFeedAsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ListView;
import android.widget.Toast;

public class RssReaderActivity extends Activity implements AsyncTaskCompletionListener{
    private ListView listview;
   

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rss_reader);
        listview=(ListView)findViewById(R.id.rssfeed_listview);
        if(Utility.determineConnectivity(this))
        new RssFeedAsyncTask(this).execute(Utility.url);
        else
            Toast.makeText(this, "No Internet Connection", Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.rss_reader, menu);
        return true;
    }

    @Override
    public void onTaskComplete(List<RssFeedStructure> result) {
        RssReaderListAdapter _adapter= new RssReaderListAdapter(RssReaderActivity.this,
                result);
        listview.setAdapter(_adapter);
    }

}

Step 2)
/layout/rss_reader.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".RssReaderActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />

    <ListView
        android:id="@+id/rssfeed_listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#5D5C5C"
        android:cacheColorHint="#00000000"
        android:divider="#000000"
        android:dividerHeight="1dip"
        android:transcriptMode="alwaysScroll" >
    </ListView>

</RelativeLayout>

Step 3)
/layout/rssfeedadapter_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/feed_image"
        android:layout_width="60dip"
        android:layout_height="60dip"
        android:layout_gravity="center_vertical"
        android:background="@drawable/im"
        android:contentDescription="@string/app_name"
        android:padding="7dp" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/feed_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="10dip"
            android:paddingLeft="8dip"
            android:paddingRight="8dip"
            android:paddingTop="5dip"
            android:textColor="#FFFFFF" />

        <TextView
            android:id="@+id/feed_updatetime"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="3dip"
            android:paddingLeft="8dip"
            android:paddingRight="8dip"
            android:paddingTop="3dip"
            android:textColor="#F6B207"
            android:textSize="10sp" />
    </LinearLayout>

</LinearLayout>


Step 4) Create RssFeedAsyncTask.java class

package com.amit.network;

import java.util.List;
import com.amit.data.AsyncTaskCompletionListener;
import com.amit.data.RssFeedStructure;
import com.amit.data.XmlHandler;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;

public class RssFeedAsyncTask extends
        AsyncTask<String, Void, List<RssFeedStructure>> {
    private ProgressDialog Dialog;
    String response = "";
    List<RssFeedStructure> rssStr;
    Activity _context;
    private AsyncTaskCompletionListener callback;

    public RssFeedAsyncTask(Activity _context) {
        this._context = _context;
        this.callback = (AsyncTaskCompletionListener) _context;
    }

    @Override
    protected void onPreExecute() {
        Dialog = new ProgressDialog(_context);
        Dialog.setMessage("Loading...");
        Dialog.show();

    }

    @Override
    protected List<RssFeedStructure> doInBackground(String... urls) {
        try {
            String feed = urls[0];
            XmlHandler rh = new XmlHandler();
            rssStr = rh.getLatestArticles(feed);
        } catch (Exception e) {
        }
        return rssStr;

    }

    @Override
    protected void onPostExecute(List<RssFeedStructure> result) {
        Dialog.dismiss();
        callback.onTaskComplete(result);

    }

}







Step 5) Create RssReaderListAdapter.java class

package com.amit.adapter;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import com.amit.data.RssFeedStructure;
import com.amit.rssfeed.R;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.SpannableString;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class RssReaderListAdapter extends ArrayAdapter<RssFeedStructure> {
    List<RssFeedStructure> imageAndTexts1 = null;

    public RssReaderListAdapter(Activity activity,
            List<RssFeedStructure> imageAndTexts) {
        super(activity, 0, imageAndTexts);
        imageAndTexts1 = imageAndTexts;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        Activity activity = (Activity) getContext();
        LayoutInflater inflater = activity.getLayoutInflater();

        View rowView = inflater.inflate(R.layout.rssfeedadapter_layout, null);
        TextView textView = (TextView) rowView.findViewById(R.id.feed_text);
        TextView timeFeedText = (TextView) rowView
                .findViewById(R.id.feed_updatetime);
        ImageView imageView = (ImageView) rowView.findViewById(R.id.feed_image);
        try {

            Log.d("rssfeed", "imageAndTexts1.get(position).getImgLink() :: "
                    + imageAndTexts1.get(position).getImgLink() + " :: "
                    + imageAndTexts1.get(position).getTitle());
            textView.setText(imageAndTexts1.get(position).getTitle());
            SpannableString content = new SpannableString(imageAndTexts1.get(
                    position).getPubDate());
            content.setSpan(new UnderlineSpan(), 0, 13, 0);

            timeFeedText.setText(content);
            if (imageAndTexts1.get(position).getImgLink() != null) {

                URL feedImage = new URL(imageAndTexts1.get(position)
                        .getImgLink().toString());
                if (!feedImage.toString().equalsIgnoreCase("null")) {
                    HttpURLConnection conn = (HttpURLConnection) feedImage
                            .openConnection();
                    InputStream is = conn.getInputStream();
                    Bitmap img = BitmapFactory.decodeStream(is);
                    imageView.setImageBitmap(img);
                } else {
                    imageView.setBackgroundResource(R.drawable.im);
                }
            }

        } catch (MalformedURLException e) {

        } catch (IOException e) {

        }

        return rowView;

    }

}

Step 5) manifest.xml
Add this permission

 <uses-permission android:name="android.permission.INTERNET" />

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


For Download full Source Code click Here

8 comments:

  1. thank u very much for the example...
    how to implement an onclick listener for the list view, to open a link for the description, i am a new Bee

    ReplyDelete
  2. i am getting error

    package com.amit.adapter;

    import com.amit.data.RssFeedStructure;
    import com.amit.rssfeed.R;

    import com.amit.Utility.Utility;
    import com.amit.adapter.RssReaderListAdapter;
    import com.amit.data.AsyncTaskCompletionListener;
    import com.amit.data.RssFeedStructure;
    import com.amit.network.RssFeedAsyncTask;

    import com.amit.data.AsyncTaskCompletionListener;
    import com.amit.data.RssFeedStructure;
    import com.amit.data.XmlHandler;

    cannot be resolved... please help. i am new to android development.

    ReplyDelete
    Replies
    1. CTRL+SHIFT+O that should solve your problem..........:-)

      Delete
  3. How to get content:encoded ..if i click the title ..will please help me [wt i ill add in OnItemClickListner]

    ReplyDelete
  4. Hello Amit,

    Thanks for this!! its working perfect!!!

    but can you add one more functionality for me to open that particular clicked url in browser?

    thanks in Advanced!!!

    ReplyDelete
  5. sunsini..........check this link it will help you to add onclick. http://www.cogninotech.com/2014/06/creating-android-rss-application-in.html

    ReplyDelete
  6. http://www.cogninotech.com/2014/06/creating-android-rss-application-in.html. for onclick

    ReplyDelete
  7. These blog contents are needed.
    Kate

    ReplyDelete