Skip to content

Instantly share code, notes, and snippets.

@luthfihariz
Created December 30, 2012 02:59
Show Gist options
  • Save luthfihariz/4410728 to your computer and use it in GitHub Desktop.
Save luthfihariz/4410728 to your computer and use it in GitHub Desktop.
Loading newsfeed in background
package com.ideaplay.sharee.utility;
import java.util.ArrayList;
public class ListItem {
private String contributorImageUrl;
private String itemTitle;
private String itemContent;
private String itemContributor;
private String itemPubDate;
private String itemSummary;
private String itemLink;
private String category;
private ArrayList<String> listCategory = new ArrayList<String>();
public ListItem() {
listCategory = new ArrayList<String>();
}
public ListItem(String itemTitle, String itemPubDate, String itemSummary) {
listCategory = new ArrayList<String>();
this.itemTitle = itemTitle;
this.itemPubDate = itemPubDate;
this.itemSummary = itemSummary;
}
public ListItem(String contributorImageUrl, String itemTitle,
String itemContributor, String itemPubDate, String itemSummary) {
listCategory = new ArrayList<String>();
this.contributorImageUrl = contributorImageUrl;
this.itemTitle = itemTitle;
this.itemContributor = itemContributor;
this.itemPubDate = itemPubDate;
this.itemSummary = itemSummary;
}
public String getContributorImageUrl() {
return contributorImageUrl;
}
public void setContributorImageUrl(String contributorImageUrl) {
this.contributorImageUrl = contributorImageUrl;
}
public String getItemTitle() {
return itemTitle;
}
public void setItemTitle(String itemTitle) {
this.itemTitle = itemTitle;
}
public String getItemContent() {
return itemContent;
}
public void setItemContent(String itemContent) {
this.itemContent = itemContent;
}
public String getItemContributor() {
return itemContributor;
}
public void setItemContributor(String itemContributor) {
this.itemContributor = itemContributor;
}
public String getItemPubDate() {
return itemPubDate;
}
public void setItemPubDate(String itemPubDate) {
this.itemPubDate = itemPubDate;
}
public String getItemSummary() {
return itemSummary;
}
public void setItemSummary(String itemSummary) {
this.itemSummary = itemSummary;
}
public String getItemLink() {
return itemLink;
}
public void setItemLink(String itemLink) {
this.itemLink = itemLink;
}
public void setItemCategory(String itemCategory) {
listCategory.add(itemCategory);
}
public ArrayList<String> getListCategory() {
return listCategory;
}
public void setListCategory(ArrayList<String> listCategory) {
this.listCategory = listCategory;
}
public String listCategoryToString(){
String result = "";
for(int i=0;i<listCategory.size();i++){
if(i==listCategory.size()-1){
result += listCategory.get(i);
}else{
result += listCategory.get(i)+", ";
}
}
return result;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
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.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.ideaplay.sharee.MenuListFragment;
import com.ideaplay.sharee.R;
import com.ideaplay.sharee.ShareeApplication;
import com.ideaplay.sharee.SlidingSherlockFragmentActivity;
import com.ideaplay.sharee.utility.ListItem;
import com.ideaplay.sharee.utility.Utility;
public class NewsFeedActivity extends SlidingSherlockFragmentActivity {
private static String RSS_URL = "http://ib.eramuslim.com//feed";
private static String RSS_XML_FILE = "iblifestyle.xml";
private com.actionbarsherlock.view.MenuItem refreshItem = null;
private ArrayList<ListItem> newsListItem;
private ListView newsListView;
private ParseXMLTask pXMLTask;
private ShareeApplication app;
public void onCreate(android.os.Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newslist_activity);
setBehindContentView(R.layout.slidingmenu_frame);
newsListView = (ListView) findViewById(R.id.postList);
// Initiate Sliding Menu
FragmentTransaction t = getSupportFragmentManager().beginTransaction();
t.add(R.id.frame, new MenuListFragment());
t.commit();
// Customize Sliding Menu
this.setSlidingActionBarEnabled(false);
getSlidingMenu().setShadowWidthRes(R.dimen.shadow_width);
getSlidingMenu().setShadowDrawable(R.drawable.shadow);
getSlidingMenu().setBehindOffsetRes(R.dimen.actionbar_home_width);
getSlidingMenu().setBehindScrollScale(0.25f);
// Customize Action Bar
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle("Update Berita");
pXMLTask = new ParseXMLTask();
newsListView
.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Intent intent = new Intent(NewsFeedActivity.this,
NewsArticleActivity.class);
intent.putExtra("Title", newsListItem.get(position)
.getItemTitle());
intent.putExtra("Description",
newsListItem.get(position).getItemSummary());
intent.putExtra("Content", newsListItem.get(position)
.getItemContent());
intent.putExtra("PubDate", newsListItem.get(position)
.getItemPubDate());
intent.putExtra("Author", newsListItem.get(position)
.getItemContributor());
intent.putExtra("Link", newsListItem.get(position)
.getItemLink());
startActivity(intent);
}
});
}
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
try {
pXMLTask.execute();
} catch (IllegalStateException e) {
}
}
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getSupportMenuInflater().inflate(R.menu.feed_menu, menu);
refreshItem = menu.findItem(R.id.refresh);
app = (ShareeApplication) getApplication();
Boolean newsLoaded = (Boolean) app.getAppData("newsLoaded");
if (!newsLoaded) {
refresh();
app.setAppData("newsLoaded", true);
}
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
toggle();
return true;
case R.id.refresh:
refresh();
return true;
}
return super.onOptionsItemSelected(item);
}
private void refresh() {
LayoutInflater inflater = (LayoutInflater) NewsFeedActivity.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ImageView iv = (ImageView) inflater.inflate(
R.layout.refresh_action_view, null);
Animation rotation = AnimationUtils.loadAnimation(
NewsFeedActivity.this, R.drawable.refresh_animation);
rotation.setRepeatCount(Animation.INFINITE);
iv.startAnimation(rotation);
refreshItem.setActionView(iv);
new DownloadXMLTask().execute();
}
private void completeRefresh() {
if (refreshItem != null && refreshItem.getActionView() != null) {
refreshItem.getActionView().clearAnimation();
refreshItem.setActionView(null);
}
}
class DownloadXMLTask extends AsyncTask<String, Void, Void> {
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
try {
Utility.downloadFromUrl(RSS_URL, RSS_XML_FILE);
} catch (IOException e) {
e.printStackTrace();
NewsFeedActivity.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(NewsFeedActivity.this,
"Gagal Perbarui Berita", Toast.LENGTH_SHORT)
.show();
}
});
}
return null;
}
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
new ParseXMLTask().execute();
completeRefresh();
}
}
class ParseXMLTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
newsListItem = new ArrayList<ListItem>();
InputStream is = null;
try {
is = new FileInputStream(new File(
android.os.Environment.getExternalStorageDirectory()
+ "/sharee", RSS_XML_FILE));
new NewsFeedHandler().parseContent(is);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
NewsListAdapter adapter = new NewsListAdapter(
NewsFeedActivity.this, newsListItem);
newsListView.setAdapter(adapter);
}
}
class NewsFeedHandler extends DefaultHandler {
StringBuffer chars = new StringBuffer();
boolean insideItem = false;
ListItem listItem;
public void parseContent(InputStream is) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setContentHandler(this);
InputSource inputSource = new InputSource(is);
xmlReader.parse(inputSource);
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
}
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
chars = new StringBuffer();
if (localName.equalsIgnoreCase("item")) {
listItem = new ListItem();
insideItem = true;
}
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (insideItem) {
if (localName.equalsIgnoreCase("title")
&& listItem.getItemTitle() == null) {
listItem.setItemTitle(chars.toString());
}
if (localName.equalsIgnoreCase("description")
&& listItem.getItemSummary() == null) {
listItem.setItemSummary(chars.toString());
}
if (localName.equalsIgnoreCase("link")
&& listItem.getItemLink() == null) {
listItem.setItemLink(chars.toString());
}
if (localName.equalsIgnoreCase("pubDate")
&& listItem.getItemPubDate() == null) {
String pubDate = chars.toString().replace("+0000", "");
listItem.setItemPubDate(pubDate);
}
if (localName.equalsIgnoreCase("category")
&& listItem.getCategory() == null) {
listItem.setCategory(chars.toString());
}
if (localName.equalsIgnoreCase("encoded")
&& listItem.getItemContent() == null) {
listItem.setItemContent(chars.toString());
}
if (localName.equalsIgnoreCase("creator")
&& listItem.getItemContributor() == null) {
listItem.setItemContributor(chars.toString());
}
if (localName.equalsIgnoreCase("item")) {
newsListItem.add(listItem);
}
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
chars.append(new String(ch, start, length));
}
}
}
package com.ideaplay.sharee.newsfeed;
import java.util.List;
import android.content.Context;
import android.graphics.Typeface;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.ideaplay.sharee.R;
import com.ideaplay.sharee.utility.ListItem;
public class NewsListAdapter extends ArrayAdapter<ListItem> {
ViewHolder holder;
public NewsListAdapter(Context context, List<ListItem> objects) {
super(context, 0, objects);
// TODO Auto-generated constructor stub
}
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
ListItem listItem = getItem(position);
if (rowView == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
rowView = vi.inflate(R.layout.row, null);
holder = new ViewHolder();
holder.title = (TextView) rowView
.findViewById(R.id.newslistitem_title);
holder.pubDate = (TextView) rowView
.findViewById(R.id.newslistitem_pubdate);
Typeface tf = Typeface.createFromAsset(getContext().getAssets(),
"fonts/Roboto-Regular.ttf");
holder.title.setTypeface(tf, 1);
holder.pubDate.setTypeface(tf);
rowView.setTag(holder);
} else {
holder = (ViewHolder) rowView.getTag();
}
holder.title.setText(Html.fromHtml(listItem.getItemTitle()));
holder.pubDate.setText(listItem.getItemPubDate());
return rowView;
}
static class ViewHolder {
TextView title;
TextView pubDate;
}
}
//here code before..
public static void downloadFromUrl(String downloadUrl, String fileName)
throws IOException {
File root = android.os.Environment.getExternalStorageDirectory(); // path
// ke
// sdcard
File dir = new File(root.getAbsolutePath() + "/sharee"); // path ke
// folder
if (dir.exists() == false) { // cek folder eksistensi
dir.mkdirs(); // kalau belum ada, dibuat
}
URL url = new URL(downloadUrl); // you can write here any link
File file = new File(dir, fileName);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(5000);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
}
//here code after...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment