Monday, July 25, 2016

சாஃப்ட் ட்ரிங்க்ஸ் (கலர் குளிர் பானங்கள்) எனப்படும் நச்சு தன்மையுள்ள விஷம்

தற்போது சென்னையில் அதிக இடங்களில் சாஃப்ட் ட்ரிங்க்ஸ் எனப்படும் ரசாயன கலர் குளிர் பணம் விறகப்படுகிறது. இந்த கலர் குளிர் பாணங்களால் உடலுக்கு ஏதேனும் நன்மை கிடைக்கிறதா என்றால் நிச்சயமாக இல்லை. அது மற்றும் இல்லாமல் அவற்றினுள் அடங்கியுள்ள தீங்கு விளைவிக்கும் பொருட்கள் உடலுக்கு கேடு செய்கின்றன என்ற எச்சரிக்கையாவது இருக்கிறதா என்றால் அதுவும் இல்லை.


இதனால் ஏற்படும் பாதிப்புகள் என்னென்ன என்பதை பார்ப்போம்
பற்களுக்கு தீங்கு விளைவிக்கின்றன.

சொல்லப்போனால் அனைத்து விதமான குளிர் பானங்களும் அமிலச்சுவையுடன் இருக்கின்றன. இதில் கலந்துள்ள அமிலங்கள் பற்களின் எனாமலைப் பதம் பார்த்து கரைத்து விடுகின்றன. அதுமட்டுமில்லாமல் அதிலுள்ள சருக்கரை சத்து, பற்களை தாக்கும் பாக்டீரியாவை வளர்க்க உதவுகிறது.

சிலவற்றை தவிர அனைத்து விதமான குளிர் பானங்களும் குறிப்பிடப்பட்ட அளவை விட நச்சு கலந்த  தீங்கு பொருட்கள் அதிகம்  இருக்கின்றன என 2003-ம்  ஆண்டு அறிவியல் சுற்று சூழல் மையம் அறிக்கை வெளியிட்டது. இதை பற்றி யாரும் கவலை கொள்ளாமல் அலட்சியப் படுத்த பட்டு இன்றும் சுத்தமான பொருளாக விளம்பரமாகவும் சந்தையிலும் அறிமுகப்படுத்தப்பட்டு வருகிறது.  குளிர்பானங்களால் எந்த விதமான ஊட்டச்சத்தும் இல்லை என்பதே உண்மை. அளவுக்கு மீறிய ரசாயனமும், உடலுக்கு தீங்கு ஏற்படும் நச்சு பொருளும்தான் அதிகம் உள்ளது என்பதே உண்மை. தேவைக்கு அதிகமான சர்க்க்கரை இரத்தத்தில் கலந்தால் அது கொலஸ்ட்ராலை அதிகரிக்க செய்யும். அதன் பிறகு, நீரிழிவு நோய், இரத்த அழுத்தம் , இதய நோய், பக்க வாதம் எல்லாம் ஒன்றன் பின் ஒன்றாக நம் உடலில் வந்து தங்கும்.

குளிர்பானங்களில் சேர்க்க படும் ஆபத்தான ரசாயனங்கள்

Aspartame:
 "Light:" அல்லது "Diat"  குளிர்பானங்களில்  சர்க்கரைக்கு பதிலாக  aspartame  எனப்படும் செயற்கை இனிப்பூட்டி ரசாயனம் சேர்க்கப்பட்டுகிறது. இது கலோரி தருவதல்ல ஆனாலும் இது தாகத்தை தணிப்பதற்கு பதில் பசியையும்  தாகத்தையும் அதிகரிக்க செய்யும்.  2010ல் நடைபெற்ற ஆய்வில்  இது ஈரல், நுரையீரல் மற்றும் மூளையில் ட்யூமர் கட்டிகள் உருவாக்க கூடும் என கண்டறியப்பட்டது.

 இந்த aspartame  சிதைவுற்று மெத்தனால் ஆக மாறுகிறது. இது சுற்று சூழலுக்கு கேடு விளவிக்கும் ஒரு காரணியாகும்.
 மனித உடலில் இந்த மெத்தனால் மேலும் சிதைவுற்று formic acid மற்றும் formaldehyde ஆக மாறுகிறது.இது நரம்பு மண்டலத்தை தாக்கும் ஒரு விஷப்பொருள். இதனால் மைக்ரேன் எனும் ஒற்றைத் தலைவலி, மந்தம் ,பார்வைக்குறைபாடு மற்றும் மறதியை இந்த செயற்கை ரசாயனம் உருவாக்கும்.

Caramel:
         கோலா பானங்களின் பிரவுன் நிறத்திற்காக இந்த ரசாயனப் பொருள் சேர்க்கப்படுகிறது.இதில் உள்ள  ammonia மற்றும் sulphite  ஈரல் மற்றும் நுரையீரல் புற்று நோயை உருவாக்குகிறது.  மேலும் தைராய்ட், லூக்கேமியா போன்ற நோய்க்கு காரணமாவதாக CSPI U.S. research institute தெரிவிக்கிறது.

Phosphoric acid:
       சிட்ரிக் ஆசிட்டுக்கு பதிலாக கோலா பானங்களில் சேர்க்கப்படும் இந்த ரசாயனம் சிறுநீரக செயலிழப்பு மற்றும் Osteoporosis எலும்பு உடைதல் நோய்க்குக் காரணமாக இருக்கிறது.

Benzoic acid:
குளிர் பானங்கள் நெடு நாட்கள் கெட்டுப் போகாமல் இருக்க இந்த அமிலம் பயன்படுத்தப்படுகிறது. இது ஆஸ்துமா, பரு, தோலில் கட்டி, வெடிப்பு முதலியவற்றை உண்டாக்குகிறது. கூடவே எதிலும் குற்றம் கண்டுபிடிக்கும் மனப்பான்மையையும் உண்டாக்குகிறது.

Sulphur Dioxide
       எலுமிச்சை பானங்கள் கருப்பு நிறமாக மாறி விடாமல் இருக்க சல்ஃபர் டையாக்ஸைடு சேர்க்கப்படுகிறது. இது பானங்களில் உள்ள நறுமணம் போய்விடாமல் பாதுகாக்கிறது. இந்த  சல்ஃபர் டையாக்ஸைடு, ஒரு நச்சு முறிவு மருந்துதான். நலமாக உள்ள ஒருவர் தொடர்ந்து கலர் அருந்தியதும் மந்தநிலை, தெளிவற்ற பார்வை, தோலில் வெடிப்பு, வீக்கம், சோர்வு, இதயத்தில் ஓருவித இறுக்கம், அதிர்ச்சி, திடீர்க் கோபம், அதிர்ச்சியில் இறப்பு போன்றவை ஏற்படுகின்றன. அப்படி இருந்தால் ஆரோக்கியமான உடலில் கலர்  மூலம் சேர்ந்த  சல்பர் டையாக்ஸைடே காரணம்.

Caffine
         பானங்கள் நறுமணமாக இருக்க, இவை சேர்க்கப்படுகிறது. காஃபைன், உண்மையில் போதை தரும் ஒரு மருந்து. இது அதிகமானால் மத்திய நரம்பு மண்டலம் அடிக்கடி ஊக்குவிக்கப் படுவதால் விரைவில் தளர்ச்சியும் வந்துவிடுகிறது. இதனால் தூக்கமின்மை, நரம்புக் கோளாறு, எரிச்சல், வயிற்றுப் பொருமல், மனக்குழப்பம், இதயம் வேக வேகமாகத் துடித்து ஒரு விதப் பதட்டம் முதலியன ஏற்படுகின்றன. சிறுநீர்ப் பைகள், வயிறு முதலியவற்றில் புற்றுநோய், இரத்தக்கொதிப்பு, மேலும் ஆறு விதமான புற்றுநோய்கள் அடிக்கடி கலர் அருந்துகிறவர்களுக்கு வருகிறது. அடிக்கடி இளவயதில் கலர் அருந்தும் தம்பதிகளுக்கு பிறவியிலேயே குறைபாடு உள்ள குழந்தைகள் பிறந்துள்ளன.
இத்தகைய ஊக்க பானங்களை மதுவுடன் சேர்த்து அருந்துவது உடலுக்கு மிகவும் கேடு செய்யும். ஏனெனில் இவை தற்காலிகமாக மூளையை தூண்டுகின்றன. அதேசமயம் மது மூளையை மந்தப்ப்படுத்துகிறது. இந்த முரண்பட்ட தன்மையால் மனிதனின் நரம்பு மண்டல கட்டுபாடு சீர்குலைகிறது. மயக்கம் வாந்தி, இதயத் துடிப்பில் சீரின்மை உண்டாகிறது.

Tartrazine
       ஆரஞ்சு மற்றும் மஞ்சள் நிறத்திலும் கலர் பானங்கள் தயாரிக்கப் படுகின்றன. இந்த டார்ட்ராஜைன் Tartrazine என்ற கலரை நார்வே, பின்லாந்து ஆகிய நாடுகள் தடை செய்துள்ளன. இந்த வண்ணச் சாயம் தோலிற்கு அலர்ஜியைத் தந்து, உடலில் வீக்கம், கடுமையான ஜலதோஷம், கண்கள் சிவப்பாக மாறுதல், பார்வைக் குறைபாடு, நரம்புக்கோளாறு ஆகிய விளைவுகளை ஏற்படுத்துகின்றன. குளிர் பானங்களின் நிறத்துக்கு சேர்க்கப்படும் சிவப்புச் சாயம் புற்றுநோய், ஒவ்வாமை, சாப்பிட்ட உணவை அல்லது தயாரித்த உணவை நஞ்சாக மாற்றிவிடுகிறது.

carboxymethylcellulose
       ஐஸ்க்ரீமில் உள்ள carboxymethylcellulose எலிகளிடம் செய்த சோதனையில் 80% புற்று நோய் உரு்வாக்குவது கண்டு பிடிக்கப் பட்டது.

Aluminium
அலுமினிய கேன்களில் அடைக்கப்பட்டு வரும் குளிர்பானங்களில் அதன் அமிலத் தன்மையால் அலுமினியத்தோடு வினைபுரிந்து அலுமினியம் சிறு அளவாவது குளிர்பானத்தில் கலக்கும் வாய்ப்புள்ளது.மேலும் இந்த கேன்கள் பெட்டி பெட்டியாக கடைகளிலும் குடோன்களிலும் வைக்கப்பட்டிருக்கும் வேளையில் எலிகள் போன்ற பிராணிகளால்  கேன்களில் வாய் வைத்து குடிக்கும் பகுதியில் கிருமிதொற்று ஏற்படும் அபாயம் உள்ளது


பாக்கெட்டுகளில் அடைத்து வரும் பழச்சாறுகள் பலதும் உண்மையில் பழச்சாறுகள் அல்ல. சர்க்கரை, தண்ணீர், அராபிக் கம் எனப்படும் கோந்து மற்றும் சில ரசாயன வண்ணங்களும் எஸ்சென்சும் தான். பல சாஃப்ட் ட்ரிங்க் பொடிகளும் ஆபத்தான வெறும் ரசாயனக்கலவைகளே.எனவே, அடுத்த முறை கலர் அருந்த நினைக்கும் போது அந்த எண்ணத்தைக் கைவிட்டு, மோர், லெமன்ஜூஸ், காரட் ஜூஸ், இயற்கையான பழச்சாறுகள், இளநீர் போன்றவற்றை அருந்துங்கள். அதுவே நல்லது.

தாகம் ஏற்பட்டல் தயவு செய்து தண்ணீர் மட்டுமே அருந்துங்கள்.. ஜூஸ் அதற்கு தீர்வாகாது.சுத்தமான தண்ணீர் என்ற பிரமையை உருவாக்கி வரும் மினரல் வாட்டர்களிலும் எந்த விதமான சத்துப் பொருளும் இல்லை பதிலுக்கு ரசாயனங்களே சேர்க்கபடுகிறது.

பூமியிலிருந்து கிடைக்கும் இயற்கையான குடிநீரையும் பரிசோதித்து  நல்ல குடி நீராக மாற்றி உபயோகப் படுத்துவதே நல்லது.

என் பதிவை படித்ததற்கு நன்றி . 

Tuesday, July 19, 2016

LruCache Bitmaps


A cache that holds strong references to a limited number of values. Each time a value is accessed, it is moved to the head of a queue. When a value is added to a full cache, the value at the end of that queue is evicted and may become eligible for garbage collection.

Loading a single bitmap into your user interface (UI) is straightforward, however things get more complicated if you need to load a larger set of images at once. In many cases (such as with components like ListView, GridView or ViewPager), the total number of images on-screen combined with images that might soon scroll onto the screen are essentially unlimited.

Memory usage is kept down with components like this by recycling the child views as they move off-screen. The garbage collector also frees up your loaded bitmaps, assuming you don't keep any long lived references. This is all good and well, but in order to keep a fluid and fast-loading UI you want to avoid continually processing these images each time they come back on-screen. A memory and disk cache can often help here, allowing components to quickly reload processed images.

A memory cache offers fast access to bitmaps at the cost of taking up valuable application memory. The LruCache class (also available in the Support Library for use back to API Level 4) is particularly well suited to the task of caching bitmaps, keeping recently referenced objects in a strong referenced LinkedHashMap and evicting the least recently used member before the cache exceeds its designated size.

It is a cache that holds strong references to a limited number of values. Each time a value is accessed, it is moved to the head of a queue. When a value is added to a full cache, the value at the end of that queue is evicted and may become eligible for garbage collection.

A cache that is too small causes additional overhead with no benefit, a cache that is too large can once again cause java.lang.OutOfMemory exceptions and leave the rest of your app little memory to work with.

Here’s an example of setting up a LruCache for bitmaps:

private LruCache mLruCache;
public CustomListAdapter(Context context, ArrayList listData) {
        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        final int cacheSize = maxMemory / 4;
        mLruCache = new LruCache(cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                // The cache size will be measured in kilobytes
                return bitmap.getByteCount() / 1024;
            }
        };
        this.listData = listData;
        layoutInflater = LayoutInflater.from(context);
    }
public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
        if (getBitmapFromMemCache(key) == null) {
            mLruCache.put(key, bitmap);
        }
    }
public Bitmap getBitmapFromMemCache(String key) {
return mLruCache.get(key);
}

When loading a bitmap into an ImageView, the LruCache is checked first. If an entry is found, it is used immediately and update the ImageView, otherwise a background thread is spawned to process the image:

Bitmap thumbnailImage = getBitmapFromMemCache(newsItem.getUrl());
    if (thumbnailImage == null) {
    new ImageLoadingTask(holder.imageView).execute(newsItem.getUrl());
    } else {
holder.imageView.setImageBitmap(thumbnailImage);
        Log.d("FileSize", "Cached stored");
    }
Suppose we have a list of images in application. When user scrolls down, application has to load next images. If we will load the images directly from source it will take more time. And what if user scrolls up, then we have to fetch those recently used bitmaps again causing a wastage of resources. This is not a suitable approach if we have a lot of bitmaps in application. In such case LruCache would be helpful. It will fetch the images, put them into cache and will only remove the least recently used bitmap which means the bitmap not used for the longest time.

Here is the full source code download here

Wednesday, July 13, 2016

Send messages from ubutnu Terminal to Whatsapp

What is WhatsApp

WhatsApp Messenger is a cross-platform mobile messaging app which allows you to exchange messages without having to pay for SMS.

WhatsApp Messenger is available for iPhone, BlackBerry, Android, Windows Phone and Nokia and yes, those phones can all message each other! Because WhatsApp Messenger uses the same internet data plan that you use for email and web browsing, there is no cost to message and stay in touch with your friends.

Installing and Configuring Yowsup in ubuntu

Yowsup is a python library that enables you build application which use WhatsApp service. Yowsup has been used to create an unofficial WhatsApp client Nokia N9 through the Wazapp project which was in use by 200K + users as well as another fully featured unofficial client for Blackberry 10. 

It act as a WhatsApp service under platforms like Linux, MAC and windows.

Yowsup Architecture

A running Yowsup is a stack of several layers. The previous figure is a breakdown of the core Yowsup stack. A layer is a bidirectional channel that transforms the data passing through it before passing it to underlying or the above layer. 

To know more about yowsup click

Yowsup Installation

We need to install yowsup library, it enables you to send an messages using WhatsApp.
Before we need to setup configuration for yowsup.
First step, we need to install all the dependencies using the below command as the root user
> apt-get install python python-dateutil python-argparse python-dev python-setuptools
After installation of python, then download yowsup WhatsApi on github
> git clone https://github.com/tgalal/yowsup
After download, go to inside the yowsup folder
> cd yowsup
Provide permission to setup.py
> chmod +x setup.py
Run the following command
> python setup.py install
After finish the installation complete, you can setup whatsapp configuation by
> chmod +x yowsup-cli

Yowsup-Cli

yowsup-cli is a command line interface to Yowsup library. It provides you with the options of registration, and provides a few demos such as a command line client

First you need to register using your phone number and password for setup the yowsup library.
> ./yowsup-cli
This above input provides the following results
Available commmands: 
==================== 
demos, registration, version
Then you need to register your phone number using yowsup with the registration command
> ./yowsup-cli registration --requestcode sms --phone xxxxxxxx --cc 49 --mcc 24 --mnc 07
You must be given your phone number with country code, for example 9196xxxxxx39 (In india country code is 91)

It provides the following output if the above command is correct. and you will receive whatsapp one time password.
INFO:yowsup.common.http.warequest:{"status":"sent","length":6,"method":"sms","retry_after":1805}
status: sent
retry_after: 1805
length: 6
method: sms
Registration Option:
-m MCC, --mcc MCC Mobile Country Code. Check your mcc here: https://en.wikipedia.org/wiki/Mobile_country_code
-n MNC, --mnc MNC Mobile Network Code. Check your mnc from https://en.wikipedia.org/wiki/Mobile_country_code
-p PHONE, --phone PHONE Your full phone number including the country code you
defined in 'cc', without preceeding '+' or '00'
-C CC, --cc CC Country code. See http://www.ipipi.com/help/telephone-country-codes.htm. 
Then you need to finish the registration by using the following command and provide OTP here.
./yowsup-cli registration --register 263-541 --phone 91xxxxxxx --cc 49

If the above command is correct, then you will get the following results in command
INFO:yowsup.common.http.warequest:{"status":"ok","login":"xxxxxxxxxxxxxxx","pw":"0pJj5cLaGSk6pDTa6rJR/5bDiR0=","type":"new","expiration":1471273284,"kind":"free","price":"0,89 \u20ac","cost":"0.89","currency":"EUR","price_expiration":1442376976}
status: ok
kind: free
pw: 0pJj5cLaGSk6pDTa6rJR/5bDiR0=
price: 0,89 €
price_expiration: 1442376976
currency: EUR
cost: 0.89
expiration: 1471273284
login: xxxxxxxxxxxxxx
type: new
Here you need to note the password (pw). Just copy it and paste in vim editor.

Create the config file as following.
> vim yowsup-cli.conf
Then add content as follows
cc=49 #Your country code
phone=xxxxxxxxxxxx #Your phone number with country code 91(india)
id= #This is where you insert your IMEI number (not needed)
password=0pJj5cLaGSk6pDTa6rJR/5bDiR0= #your password which you got from registration command 

Then save this file by using press Esc button and type !wq then enter to exit.
Then test your configuration by sending message by using the following command.
./yowsup-cli demos -c yowsup-cli.conf -s ************ “testing msg”
******** is the receiver number.
Thats all.

If you facing an any issue, kindly let me know.

Thanks for reading our blog.

Wednesday, June 13, 2012

How to parse JSON values without tag in iPhone

Here i post how to parse JSON values without using tags...

this is sample json values without tag except main tag.


{
  "Parsing_Json": [
    "[7, Best, hello]",
    "[2, Day, welcome]",
    "[3, News, here]",
    "[6, Test, postings]",
    "[4, Mother, jsonvalues]"
  ]
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[responseData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"ERROR with theConenction");
[connection release];
[responseData release];
}


-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
array = [(NSDictionary*)[responseString JSONValue] objectForKey:@"Parsing_Json"]; 
NSString *str =[NSString stringWithFormat:@"%@",array];

for (int i=0; i<[array count]; i++)
{
NSString *member=[array objectAtIndex:i];
NSArray *array1 =[member componentsSeparatedByString:@","]; 
NSString *n1=[array1 objectAtIndex:0];
NSString *n2=[array1 objectAtIndex:1];
NSString *n3=[array1 objectAtIndex:2];

}



}

In above n1, n2 and n3 string values are parsed from JSON values. This is very easy method to getting JSON values without using tags except head tag.

Thanks...




Saturday, May 5, 2012

SOAP Web Services in iPhone/iPad

Here i posted the code. simply follow the steps.....

Create one button in xib and implemented with name -(IBAction) read_data,
bcz when we press the button then it fired soap webservice.

firstView.h file

@interface firstView : UIViewController {


NSMutableArray *list;
UILabel *soapValue;
}
- (IBAction) read_data;
@end

firstView.m file

@implementation firstView


- (IBAction) read_data
{
 NSString *name=@"50";     // Here name is, we providing value. so u change to ur provide value.

NSString *soapMessage = [NSString stringWithFormat:
@"\n"
"\n"
"\n"
"n"
"%@n"
"n"
"\n"
"\n",name
];

NSLog(@"soap Message= %@",soapMessage);
NSURL *url = [NSURL URLWithString:@"http://w3schools.com/webservices/tempconvert.asmx"];    //Here is the your server URL

NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];   

NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];
[theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[theRequest addValue: @"http://tempuri.org/CelsiusToFahrenheit" forHTTPHeaderField:@"SOAPAction"];
[theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
[theRequest setHTTPMethod:@"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];

NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection )
{
webData = [[NSMutableData data] retain];
}
else
{
NSLog(@"theConnection is NULL");
}
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"ERROR with theConenction");
[connection release];
[webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"DONE. Received Bytes: %d", [webData length]);
NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
NSLog(@"theXML %@",theXML);     //theXML is the ur server XML
[theXML release];
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:webData];
[parser setDelegate:self];
[parser setDelegate:self];
[parser setShouldProcessNamespaces:NO];
[parser setShouldReportNamespacePrefixes:NO];
[parser setShouldResolveExternalEntities:NO];
[parser parse];
[parser release];
}


-(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
{
if([elementName isEqualToString:@"CelsiusToFahrenheitResult"])
{
list = [[NSMutableArray alloc] init];
}
}

-(void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
{
if([elementName isEqualToString:@"CelsiusToFahrenheitResult"])
{
list = [[NSMutableArray alloc] init];
}
}

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string 
{
if(string)
{
NSLog(@"String Value= %@",string);    //this string value is the response value splitted from xml
}
}

Thanks 
----------------------

Ravi Kumar K



Sunday, July 17, 2011

how to create popup menu in android


Here i show the how to create popup menu with list in android...

ActionItem.java
------------------------


public class ActionItem {
private Drawable icon;
private Bitmap thumb;
private String title;
private boolean selected;
private OnClickListener listener;
public ActionItem() {}
public ActionItem(Drawable icon) {
this.icon = icon;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return this.title;
}
public void setIcon(Drawable icon) {
this.icon = icon;
}
public Drawable getIcon() {
return this.icon;
}
public void setOnClickListener(OnClickListener listener) {
this.listener = listener;
}
public OnClickListener getListener() {
return this.listener;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public boolean isSelected() {
return this.selected;
}

public void setThumb(Bitmap thumb) {
this.thumb = thumb;
}
public Bitmap getThumb() {
return this.thumb;
}
}

CustomPopupWindow.java
------------------------------------


public class CustomPopupWindow {
protected final View anchor;
protected final PopupWindow window;
private View root;
private Drawable background = null;
protected final WindowManager windowManager;
/**
* Create a QuickAction
*
* @param anchor
* the view that the QuickAction will be displaying 'from'
*/
public CustomPopupWindow(View anchor) {
this.anchor = anchor;
this.window = new PopupWindow(anchor.getContext());

// when a touch even happens outside of the window
// make the window go away
window.setTouchInterceptor(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
CustomPopupWindow.this.window.dismiss();
return true;
}
return false;
}
});

windowManager = (WindowManager) anchor.getContext().getSystemService(Context.WINDOW_SERVICE);
onCreate();
}

/**
* Anything you want to have happen when created. Probably should create a view and setup the event listeners on
* child views.
*/
protected void onCreate() {}

/**
* In case there is stuff to do right before displaying.
*/
protected void onShow() {}

protected void preShow() {
if (root == null) {
throw new IllegalStateException("setContentView was not called with a view to display.");
}
onShow();

if (background == null) {
window.setBackgroundDrawable(new BitmapDrawable());
} else {
window.setBackgroundDrawable(background);
}

// if using PopupWindow#setBackgroundDrawable this is the only values of the width and hight that make it work
// otherwise you need to set the background of the root viewgroup
// and set the popupwindow background to an empty BitmapDrawable
window.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
window.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
window.setTouchable(true);
window.setFocusable(true);
window.setOutsideTouchable(true);

window.setContentView(root);
}

public void setBackgroundDrawable(Drawable background) {
this.background = background;
}

/**
* Sets the content view. Probably should be called from {@link onCreate}
*
* @param root
* the view the popup will display
*/
public void setContentView(View root) {
this.root = root;
window.setContentView(root);
}

/**
* Will inflate and set the view from a resource id
*
* @param layoutResID
*/
public void setContentView(int layoutResID) {
LayoutInflater inflator =
(LayoutInflater) anchor.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
setContentView(inflator.inflate(layoutResID, null));
}

/**
* If you want to do anything when {@link dismiss} is called
*
* @param listener
*/
public void setOnDismissListener(PopupWindow.OnDismissListener listener) {
window.setOnDismissListener(listener);
}

/**
* Displays like a popdown menu from the anchor view
*/
public void showDropDown() {
showDropDown(0, 0);
}

/**
* Displays like a popdown menu from the anchor view.
*
* @param xOffset
* offset in X direction
* @param yOffset
* offset in Y direction
*/
public void showDropDown(int xOffset, int yOffset) {
preShow();

window.setAnimationStyle(R.style.Animations_PopDownMenu_Left);

window.showAsDropDown(anchor, xOffset, yOffset);
}

/**
* Displays like a QuickAction from the anchor view.
*/
public void showLikeQuickAction() {
showLikeQuickAction(0, 0);
}

/**
* Displays like a QuickAction from the anchor view.
*
* @param xOffset
* offset in the X direction
* @param yOffset
* offset in the Y direction
*/
public void showLikeQuickAction(int xOffset, int yOffset) {
preShow();

window.setAnimationStyle(R.style.Animations_PopUpMenu_Center);

int[] location = new int[2];
anchor.getLocationOnScreen(location);

Rect anchorRect =
new Rect(location[0], location[1], location[0] + anchor.getWidth(), location[1]
+ anchor.getHeight());

root.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
root.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
int rootWidth = root.getMeasuredWidth();
int rootHeight = root.getMeasuredHeight();

int screenWidth = windowManager.getDefaultDisplay().getWidth();
//int screenHeight = windowManager.getDefaultDisplay().getHeight();

int xPos = ((screenWidth - rootWidth) / 2) + xOffset;
int yPos = anchorRect.top - rootHeight + yOffset;

// display on bottom
if (rootHeight > anchor.getTop()) {
yPos = anchorRect.bottom + yOffset;
window.setAnimationStyle(R.style.Animations_PopDownMenu_Center);
}

window.showAtLocation(anchor, Gravity.NO_GRAVITY, xPos, yPos);
}
public void dismiss() {
window.dismiss();
}
}

NewQA.java
--------------

public class NewQA extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView mList = (ListView) findViewById(R.id.l_list);
NewQAAdapter adapter = new NewQAAdapter(this);
final String[] data = {"Test 01", "Test 02", "Test 03", "Test 04", "Test 05", "Test 06", "Test 07", "Test 08",
"Test 09", "Test 10"};
adapter.setData(data);
mList.setAdapter(adapter);
final ActionItem addAction = new ActionItem();
addAction.setTitle("Add");
addAction.setIcon(getResources().getDrawable(R.drawable.ic_add));

final ActionItem accAction = new ActionItem();
accAction.setTitle("Accept");
accAction.setIcon(getResources().getDrawable(R.drawable.ic_accept));
final ActionItem upAction = new ActionItem();
upAction.setTitle("Upload");
upAction.setIcon(getResources().getDrawable(R.drawable.ic_up));
mList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View view, int position, long id) {
final QuickAction mQuickAction = new QuickAction(view);
final ImageView mMoreImage = (ImageView) view.findViewById(R.id.i_more);
final String text = data[position];
mMoreImage.setImageResource(R.drawable.ic_list_more_selected);
addAction.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(NewQA.this, "Add " + text, Toast.LENGTH_SHORT).show();
mQuickAction.dismiss();
}
});

accAction.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(NewQA.this, "Accept " + text, Toast.LENGTH_SHORT).show();
mQuickAction.dismiss();
}
});
upAction.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(NewQA.this, "Upload " + text, Toast.LENGTH_SHORT).show();
mQuickAction.dismiss();
}
});
mQuickAction.addActionItem(addAction);
mQuickAction.addActionItem(accAction);
mQuickAction.addActionItem(upAction);
mQuickAction.setAnimStyle(QuickAction.ANIM_AUTO);
mQuickAction.setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss() {
mMoreImage.setImageResource(R.drawable.ic_list_more);
}
});
mQuickAction.show();
}
});
}
}

NewQAAdapter.java
-------------------------


public class NewQAAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private String[] data;
public NewQAAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}

public void setData(String[] data) {
this.data = data;
}
@Override
public int getCount() {
return data.length;
}

@Override
public Object getItem(int item) {
return data[item];
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list, null);
holder = new ViewHolder();
holder.mTitleText = (TextView) convertView.findViewById(R.id.t_name);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}

holder.mTitleText.setText(data[position]);
return convertView;
}

static class ViewHolder {
TextView mTitleText;
}
}

QuickAction.java
--------------------------

public class QuickAction extends CustomPopupWindow {
private final View root;
private final ImageView mArrowUp;
private final ImageView mArrowDown;
private final Animation mTrackAnim;
private final LayoutInflater inflater;
private final Context context;
public static final int ANIM_GROW_FROM_LEFT = 1;
public static final int ANIM_GROW_FROM_RIGHT = 2;
public static final int ANIM_GROW_FROM_CENTER = 3;
public static final int ANIM_AUTO = 4;
private int animStyle;
private boolean animateTrack;
private ViewGroup mTrack;
private ArrayList actionList;
/**
* Constructor
*
* @param anchor {@link View} on where the popup should be displayed
*/
public QuickAction(View anchor) {
super(anchor);
actionList = new ArrayList();
context = anchor.getContext();
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
root = (ViewGroup) inflater.inflate(R.layout.quickaction, null);
mArrowDown = (ImageView) root.findViewById(R.id.arrow_down);
mArrowUp = (ImageView) root.findViewById(R.id.arrow_up);
setContentView(root);
mTrackAnim = AnimationUtils.loadAnimation(anchor.getContext(), R.anim.rail);
mTrackAnim.setInterpolator(new Interpolator() {
public float getInterpolation(float t) {
// Pushes past the target area, then snaps back into place.
// Equation for graphing: 1.2-((x*1.6)-1.1)^2
final float inner = (t * 1.55f) - 1.1f;
return 1.2f - inner * inner;
}
});
mTrack = (ViewGroup) root.findViewById(R.id.tracks);
animStyle = ANIM_AUTO;
animateTrack = true;
}

/**
* Animate track
*
* @param animateTrack flag to animate track
*/
public void animateTrack(boolean animateTrack) {
this.animateTrack = animateTrack;
}
/**
* Set animation style
*
* @param animStyle animation style, default is set to ANIM_AUTO
*/
public void setAnimStyle(int animStyle) {
this.animStyle = animStyle;
}

/**
* Add action item
*
* @param action {@link ActionItem}
*/
public void addActionItem(ActionItem action) {
actionList.add(action);
}
/**
* Show popup window
*/
public void show () {
preShow();

int[] location = new int[2];
anchor.getLocationOnScreen(location);

Rect anchorRect = new Rect(location[0], location[1], location[0] + anchor.getWidth(), location[1]
+ anchor.getHeight());

root.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
root.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
int rootWidth = root.getMeasuredWidth();
int rootHeight = root.getMeasuredHeight();

int screenWidth = windowManager.getDefaultDisplay().getWidth();
//int screenHeight = windowManager.getDefaultDisplay().getHeight();

int xPos = (screenWidth - rootWidth) / 2;
int yPos = anchorRect.top - rootHeight;

boolean onTop = true;
// display on bottom
if (rootHeight > anchor.getTop()) {
yPos = anchorRect.bottom;
onTop = false;
}

showArrow(((onTop) ? R.id.arrow_down : R.id.arrow_up), anchorRect.centerX());
setAnimationStyle(screenWidth, anchorRect.centerX(), onTop);
createActionList();
window.showAtLocation(this.anchor, Gravity.NO_GRAVITY, xPos, yPos);
if (animateTrack) mTrack.startAnimation(mTrackAnim);
}
/**
* Set animation style
*
* @param screenWidth Screen width
* @param requestedX distance from left screen
* @param onTop flag to indicate where the popup should be displayed. Set TRUE if displayed on top of anchor and vice versa
*/
private void setAnimationStyle(int screenWidth, int requestedX, boolean onTop) {
int arrowPos = requestedX - mArrowUp.getMeasuredWidth()/2;

switch (animStyle) {
case ANIM_GROW_FROM_LEFT:
window.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Left : R.style.Animations_PopDownMenu_Left);
break;
case ANIM_GROW_FROM_RIGHT:
window.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Right : R.style.Animations_PopDownMenu_Right);
break;
case ANIM_GROW_FROM_CENTER:
window.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Center : R.style.Animations_PopDownMenu_Center);
break;
case ANIM_AUTO:
if (arrowPos <= screenWidth/4) {
window.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Left : R.style.Animations_PopDownMenu_Left);
} else if (arrowPos > screenWidth/4 && arrowPos < 3 * (screenWidth/4)) {
window.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Center : R.style.Animations_PopDownMenu_Center);
} else {
window.setAnimationStyle((onTop) ? R.style.Animations_PopDownMenu_Right : R.style.Animations_PopDownMenu_Right);
}
break;
}
}
/**
* Create action list
*
*/
private void createActionList() {
View view;
String title;
Drawable icon;
OnClickListener listener;
int index = 1;
for (int i = 0; i < actionList.size(); i++) {
title = actionList.get(i).getTitle();
icon = actionList.get(i).getIcon();
listener = actionList.get(i).getListener();
view = getActionItem(title, icon, listener);
view.setFocusable(true);
view.setClickable(true);
mTrack.addView(view, index);
index++;
}
}
/**
* Get action item {@link View}
*
* @param title action item title
* @param icon {@link Drawable} action item icon
* @param listener {@link View.OnClickListener} action item listener
* @return action item {@link View}
*/
private View getActionItem(String title, Drawable icon, OnClickListener listener) {
LinearLayout container = (LinearLayout) inflater.inflate(R.layout.action_item, null);
ImageView img = (ImageView) container.findViewById(R.id.icon);
TextView text = (TextView) container.findViewById(R.id.title);
if (icon != null) {
img.setImageDrawable(icon);
} else {
img.setVisibility(View.GONE);
}
if (title != null) {
text.setText(title);
} else {
text.setVisibility(View.GONE);
}
if (listener != null) {
container.setOnClickListener(listener);
}

return container;
}
/**
* Show arrow
*
* @param whichArrow arrow type resource id
* @param requestedX distance from left screen
*/
private void showArrow(int whichArrow, int requestedX) {
final View showArrow = (whichArrow == R.id.arrow_up) ? mArrowUp : mArrowDown;
final View hideArrow = (whichArrow == R.id.arrow_up) ? mArrowDown : mArrowUp;

final int arrowWidth = mArrowUp.getMeasuredWidth();

showArrow.setVisibility(View.VISIBLE);
ViewGroup.MarginLayoutParams param = (ViewGroup.MarginLayoutParams)showArrow.getLayoutParams();
param.leftMargin = requestedX - arrowWidth / 2;
hideArrow.setVisibility(View.INVISIBLE);
}
}