Wednesday, October 24, 2012

Android AsyncTask Example


Android AsyncTask Example

AsyncTask class provide easy to manipulate UI thread. This class perform Doinbackgroud operation  and update UI with using Thread or Handler.
AsyncTask Having Four Methods.
1.onPreExecute()
2.doInBackground
3.onProgressUpdate
4.onPostExcute

1.onPreExecute
This method for display for progress dialog.

@Override
 protected void onPreExecute() {
       Dialog = new ProgressDialog(AndroidMADQAActivity.this);
       Dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
       Dialog.setMessage("Loading android tutorial...");
       Dialog.setCancelable(false);
       Dialog.show();
       }

2.doInBackground
This method for do some backgroud operation. For ex. Read RSS feed reader.
@Override
protected String doInBackground(String... urls) {
                       try {
                              String myBlogFeedfeed = "http://feeds.feedburner.com/iamvijayakumar/androidtutorial";
                             XmlHandler rh = new XmlHandler();
                             rssStr = rh.getLatestArticles(myBlogFeedfeed); 
                             response ="Success";
                             }
                       catch (Exception e) {
                                    response ="Failed";
                             }
                     return response;
              }
3.onProgressUpdate
This method for how much task completed . It will update on progress or else.
4.onPostExcute
This method for once doinbackgroud operation completed then data will appear in user interface.
@Override
protected void onPostExecute(String result) {
       Dialog.dismiss();
      Dialog = null;
        if(rssStr != null && response.equalsIgnoreCase("Success")){
        _adapter = new RssReaderListAdapter(AndroidMADQAActivity.this,rssStr);
       _rssFeedListView.setAdapter(_adapter);
                       }
                       else{
                             Toast.makeText(AndroidMADQAActivity.this, "Sorry Unable to retrive data. Please try again later", Toast.LENGTH_LONG).show();
                       }
                    
              }



Below i wrote the code for simple RSS feed reader using async task.
 private class AsyncTaskExample extends AsyncTask<String, Void, String> {
              // private String Content;
              private ProgressDialog Dialog;
              String response = "";

              @Override
              protected void onPreExecute() {
                     Dialog = new ProgressDialog(AndroidMADQAActivity.this);
                     Dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                     Dialog.setMessage("Loading android tutorial...");
                     Dialog.setCancelable(false);
                     Dialog.show();
             
              }
              @Override
              protected String doInBackground(String... urls) {
                       try {
                             String myBlogFeedfeed = "http://feeds.feedburner.com/iamvijayakumar/androidtutorial";
                             XmlHandler rh = new XmlHandler();
                             rssStr = rh.getLatestArticles(myBlogFeedfeed); 
                             response ="Success";
                             }
                       catch (Exception e) {
                                    response ="Failed";
                             }
                     return response;
              }
              @Override
              protected void onPostExecute(String result) {
                Dialog.dismiss();
                Dialog = null;
                       if(rssStr != null && response.equalsIgnoreCase("Success")){
                         _adapter = new RssReaderListAdapter(AndroidMADQAActivity.this,rssStr);
                      _rssFeedListView.setAdapter(_adapter);
                       }
                       else{
                             Toast.makeText(AndroidMADQAActivity.this, "Sorry Unable to retrive data. Please try again later", Toast.LENGTH_LONG).show();
                       }
                    
              }
       }



Screen Shot


Compelete Soure Code

import java.util.List;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Window;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
/**
 *
 * @author vijayakumar
 *
 */
public class AndroidMADQAActivity extends Activity  {
     TextView textView = null;
     Activity act;
    ListView _rssFeedListView;
       List<RssFeedStructure> rssStr ;
       private RssReaderListAdapter _adapter;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
          setContentView(R.layout.rssfeedreaderactivity);
          _rssFeedListView = (ListView)findViewById(R.id.rssfeed_listview);
          AsyncTaskExample asyncTask = new AsyncTaskExample();
          asyncTask.execute();
    }
    private class AsyncTaskExample extends AsyncTask<String, Void, String> {
              // private String Content;
              private ProgressDialog Dialog;
              String response = "";

              @Override
              protected void onPreExecute() {
                     Dialog = new ProgressDialog(AndroidMADQAActivity.this);
                     Dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                     Dialog.setMessage("Loading android tutorial...");
                     Dialog.setCancelable(false);
                     Dialog.show();
             
              }
              @Override
              protected String doInBackground(String... urls) {
                       try {
                             String myBlogFeedfeed = "http://feeds.feedburner.com/iamvijayakumar/androidtutorial";
                             XmlHandler rh = new XmlHandler();
                             rssStr = rh.getLatestArticles(myBlogFeedfeed); 
                             response ="Success";
                             }
                       catch (Exception e) {
                                    response ="Failed";
                             }
                     return response;
              }
              @Override
              protected void onPostExecute(String result) {
                Dialog.dismiss();
                Dialog = null;
                       if(rssStr != null && response.equalsIgnoreCase("Success")){
                         _adapter = new RssReaderListAdapter(AndroidMADQAActivity.this,rssStr);
                      _rssFeedListView.setAdapter(_adapter);
                       }
                       else{
                             Toast.makeText(AndroidMADQAActivity.this, "Sorry Unable to retrive data. Please try again later", Toast.LENGTH_LONG).show();
                       }
                    
              }
       }
   
}


RssFeedStructure.Class

package com.madqa;

import java.net.URL;
public class RssFeedStructure {
private long articleId;
private long feedId;
private String title;
private String description;
private String imgLink;
private String pubDate;
private URL url;
private String encodedContent;
public long getArticleId() {
return articleId;
}

public void setArticleId(long articleId) {
this.articleId = articleId;
}
public long getFeedId() {
return feedId;
}
/**
* @param feedId the feedId to set
*/
public void setFeedId(long feedId) {
this.feedId = feedId;
}
/**
* @return the title
*/
public String getTitle() {
return title;
}
/**
* @param title the title to set
*/
public void setTitle(String title) {
this.title = title;
}
/**
* @return the url
*/
public URL getUrl() {
return url;
}
/**
* @param url the url to set
*/
public void setUrl(URL url) {
this.url = url;
}
/**
* @param description the description to set
*/
public void setDescription(String description) {
this.description = description;


if (description.contains("<img ")){
String img = description.substring(description.indexOf("<img "));
String cleanUp = img.substring(0, img.indexOf(">")+1);
img = img.substring(img.indexOf("src=") + 5);
int indexOf = img.indexOf("'");
if (indexOf==-1){
indexOf = img.indexOf("\"");
}
img = img.substring(0, indexOf);

//setImgLink(img);

this.description = this.description.replace(cleanUp, "");
}
}
/**
* @return the description
*/
public String getDescription() {
return description;
}
/**
* @param pubDate the pubDate to set
*/
public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
/**
* @return the pubDate
*/
public String getPubDate() {
return pubDate;
}
/**
* @param encodedContent the encodedContent to set
*/
public void setEncodedContent(String encodedContent) {
this.encodedContent = encodedContent;
}
/**
* @return the encodedContent
*/
public String getEncodedContent() {
return encodedContent;
}
/**
* @param imgLink the imgLink to set
*/
public void setImgLink(String imgLink) {
this.imgLink = imgLink;
}
/**
* @return the imgLink
*/
public String getImgLink() {
return imgLink;
}

}



RssReaderListAdapter.Class
package com.madqa;

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 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.ic_launcher);
             }
                     }
             
        } catch (MalformedURLException e) {
      
        }
        catch (IOException e) {
       
        }

return rowView;

}

}

XmlHandler.class

package com.madqa;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;
public class XmlHandler extends DefaultHandler {
private RssFeedStructure feedStr = new RssFeedStructure();
private List<RssFeedStructure> rssList = new ArrayList<RssFeedStructure>();
private int articlesAdded = 0;
// Number of articles to download
private static final int ARTICLES_LIMIT = 25;

StringBuffer chars = new StringBuffer();

public void startElement(String uri, String localName, String qName, Attributes atts) {
chars = new StringBuffer();

 if (qName.equalsIgnoreCase("media:content"))
      
{
        if(!atts.getValue("url").toString().equalsIgnoreCase("null")){
        feedStr.setImgLink(atts.getValue("url").toString());
        }
        else{
               feedStr.setImgLink("");
        }
}

}
public void endElement(String uri, String localName, String qName) throws SAXException {
if (localName.equalsIgnoreCase("title"))
{
       feedStr.setTitle(chars.toString());
}
else if (localName.equalsIgnoreCase("description"))
{

       feedStr.setDescription(chars.toString());
}
else if (localName.equalsIgnoreCase("pubDate"))
{

       feedStr.setPubDate(chars.toString());
}
else if (localName.equalsIgnoreCase("encoded"))
{

       feedStr.setEncodedContent(chars.toString());
}
else if (qName.equalsIgnoreCase("media:content"))
      
{
      
}
else if (localName.equalsIgnoreCase("link"))
{

}
if (localName.equalsIgnoreCase("item")) {
rssList.add(feedStr);

feedStr = new RssFeedStructure();
articlesAdded++;
if (articlesAdded >= ARTICLES_LIMIT)
{
throw new SAXException();
}
}
}
public void characters(char ch[], int start, int length) {
chars.append(new String(ch, start, length));
}
public List<RssFeedStructure> getLatestArticles(String feedUrl) {
URL url = null;
try {

SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
url = new URL(feedUrl);
xr.setContentHandler(this);
xr.parse(new InputSource(url.openStream()));
} catch (IOException e) {
} catch (SAXException e) {

} catch (ParserConfigurationException e) {

}

return rssList;
}

Check out this may be help you

Related Posts Plugin for WordPress, Blogger...