Wednesday, August 10, 2011

Importance of intent flag FLAG_ACTIVITY_REORDER_TO_FRONT in Android?

Today i was studying a lot about Task affinities and Back Stack and trying to understand them clearly as i am running into a situation where i launched an activity two times. Look at this scenario i have a menu with five options say A , B , C , D and E which are different activities meant for different purposes. I launched B activity then A activity then C activity and again A activity and i pressed back key now A activity is finished C is displayed again i pressed back key as per my imagination it should display B activity but i was surprised to see A activity.
B -> A -> C -> A on pressing back key it should be A -> C-> B
It seems that it maintains the back stack without reordering and i came across an useful flag in Intents class FLAG_ACTIVITY_REORDER_TO_FRONT which will solve this kind of issues when intent resolves to the activity in the current task it moves this activity to the top of the stack in this way.
B->A->C->A will be reordered as B->C->A

So the code will be as follows
Intent intent = new Intent();
intent.setClass(...., ....);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);

Happy coding .....

Monday, August 8, 2011

How to save images from img tags and css from stylesheet tags using Regular Expression in Android?

Regular Expressions are the best way to use for search a particular pattern using special syntax. Even though it looks complex to understand it simplifies searching and replacing in text processing and parsing the text. Most of the editors commonly use regex for searching and replacing so its usage is common across any programming languages. I used it for html parsing for an Android applications mainly img tags and css tags which i need to store it in local file system for offline usage.

The following regex pattern is used to retrieve the css path from the html page
".*?(\"text\\/css\").*?((?:\\/[\\w\\.\\-]+)+)" So the code snippet will be like this
Pattern p = Pattern.compile(regex);
Matcher m = p.match(fileName) //fileName is the document we want to parse;
if(m.find())
{
String word = m.group(1); // this gives the exact word ex: text/css
String path =m.group(2); // this gives the relative path like /css/xyz.css
}
Many people suggest to use parses like jsoup neckohtml etc which are under GPL but if the requirement is just parsing few search terms it will be easier to use Regex since we dont need to include external jar files.

Happy coding........