How to create a List with Alphabet Overlay in Android

Hello everyone…

Today’s post is about simply loading the ListView with some alphabetically sorted data BUT with the first alphabet overlay over them when you scroll.
It’s same as the overlay you see when a user scrolls through the contacts application.

List Overlay

List Overlay

List Overlay

SO Let’s start with the code.

At first I will create a class that holds the array for the ListView. This is a little big class.
So Create a java class named Cheeses.java and copy this code into it.


package com.coderzheaven.alphabetprojectionlistview;


public class Cheeses {

    public static final String[] sCheeseStrings = {
            "Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi",
            "Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag", "Airedale",
            "Aisy Cendre", "Allgauer Emmentaler", "Alverca", "Ambert", "American Cheese",
            "Ami du Chambertin", "Anejo Enchilado", "Anneau du Vic-Bilh", "Anthoriro", "Appenzell",
            "Aragon", "Ardi Gasna", "Ardrahan", "Armenian String", "Aromes au Gene de Marc",
            "Asadero", "Asiago", "Aubisque Pyrenees", "Autun", "Avaxtskyr", "Baby Swiss",
            "Babybel", "Baguette Laonnaise", "Bakers", "Baladi", "Balaton", "Bandal", "Banon",
            "Barry's Bay Cheddar", "Basing", "Basket Cheese", "Bath Cheese", "Bavarian Bergkase",
            "Baylough", "Beaufort", "Beauvoorde", "Beenleigh Blue", "Beer Cheese", "Bel Paese",
            "Bergader", "Bergere Bleue", "Berkswell", "Beyaz Peynir", "Bierkase", "Bishop Kennedy",
            "Blarney", "Bleu d'Auvergne", "Bleu de Gex", "Bleu de Laqueuille",
            "Bleu de Septmoncel", "Bleu Des Causses", "Blue", "Blue Castello", "Blue Rathgore",
            "Blue Vein (Australian)", "Blue Vein Cheeses", "Bocconcini", "Bocconcini (Australian)",
            "Boeren Leidenkaas", "Bonchester", "Bosworth", "Bougon", "Boule Du Roves",
            "Boulette d'Avesnes", "Boursault", "Boursin", "Bouyssou", "Bra", "Braudostur",
            "Breakfast Cheese", "Brebis du Lavort", "Brebis du Lochois", "Brebis du Puyfaucon",
            "Bresse Bleu", "Brick", "Brie", "Brie de Meaux", "Brie de Melun", "Brillat-Savarin",
            "Brin", "Brin d' Amour", "Brin d'Amour", "Brinza (Burduf Brinza)",
            "Briquette de Brebis", "Briquette du Forez", "Broccio", "Broccio Demi-Affine",
            "Brousse du Rove", "Bruder Basil", "Brusselae Kaas (Fromage de Bruxelles)", "Bryndza",
            "Buchette d'Anjou", "Buffalo", "Burgos", "Butte", "Butterkase", "Button (Innes)",
            "Buxton Blue", "Cabecou", "Caboc", "Cabrales", "Cachaille", "Caciocavallo", "Caciotta",
            "Caerphilly", "Cairnsmore", "Calenzana", "Cambazola", "Camembert de Normandie",
            "Canadian Cheddar", "Canestrato", "Cantal", "Caprice des Dieux", "Capricorn Goat",
            "Capriole Banon", "Carre de l'Est", "Casciotta di Urbino", "Cashel Blue", "Castellano",
            "Castelleno", "Castelmagno", "Castelo Branco", "Castigliano", "Cathelain",
            "Celtic Promise", "Cendre d'Olivet", "Cerney", "Chabichou", "Chabichou du Poitou",
            "Chabis de Gatine", "Chaource", "Charolais", "Chaumes", "Cheddar",
            "Cheddar Clothbound", "Cheshire", "Chevres", "Chevrotin des Aravis", "Chontaleno",
            "Civray", "Coeur de Camembert au Calvados", "Coeur de Chevre", "Colby", "Cold Pack",
            "Comte", "Coolea", "Cooleney", "Coquetdale", "Corleggy", "Cornish Pepper",
            "Cotherstone", "Cotija", "Cottage Cheese", "Cottage Cheese (Australian)",
            "Cougar Gold", "Coulommiers", "Coverdale", "Crayeux de Roncq", "Cream Cheese",
            "Cream Havarti", "Crema Agria", "Crema Mexicana", "Creme Fraiche", "Crescenza",
            "Croghan", "Crottin de Chavignol", "Crottin du Chavignol", "Crowdie", "Crowley",
            "Cuajada", "Curd", "Cure Nantais", "Curworthy", "Cwmtawe Pecorino",
            "Cypress Grove Chevre", "Danablu (Danish Blue)", "Danbo", "Danish Fontina",
            "Daralagjazsky", "Dauphin", "Delice des Fiouves", "Denhany Dorset Drum", "Derby",
            "Dessertnyj Belyj", "Devon Blue", "Devon Garland", "Dolcelatte", "Doolin",
            "Doppelrhamstufel", "Dorset Blue Vinney", "Double Gloucester", "Double Worcester",
            "Dreux a la Feuille", "Dry Jack", "Duddleswell", "Dunbarra", "Dunlop", "Dunsyre Blue",
            "Duroblando", "Durrus", "Dutch Mimolette (Commissiekaas)", "Edam", "Edelpilz",
            "Emental Grand Cru", "Emlett", "Emmental", "Epoisses de Bourgogne", "Esbareich",
            "Esrom", "Etorki", "Evansdale Farmhouse Brie", "Evora De L'Alentejo", "Exmoor Blue",
            "Explorateur", "Feta", "Feta (Australian)", "Figue", "Filetta", "Fin-de-Siecle",
            "Finlandia Swiss", "Finn", "Fiore Sardo", "Fleur du Maquis", "Flor de Guia",
            "Flower Marie", "Folded", "Folded cheese with mint", "Fondant de Brebis",
            "Fontainebleau", "Fontal", "Fontina Val d'Aosta", "Formaggio di capra", "Fougerus",
            "Four Herb Gouda", "Fourme d' Ambert", "Fourme de Haute Loire", "Fourme de Montbrison",
            "Fresh Jack", "Fresh Mozzarella", "Fresh Ricotta", "Fresh Truffles", "Fribourgeois",
            "Friesekaas", "Friesian", "Friesla", "Frinault", "Fromage a Raclette", "Fromage Corse",
            "Fromage de Montagne de Savoie", "Fromage Frais", "Fruit Cream Cheese",
            "Frying Cheese", "Fynbo", "Gabriel", "Galette du Paludier", "Galette Lyonnaise",
            "Galloway Goat's Milk Gems", "Gammelost", "Gaperon a l'Ail", "Garrotxa", "Gastanberra",
            "Geitost", "Gippsland Blue", "Gjetost", "Gloucester", "Golden Cross", "Gorgonzola",
            "Gornyaltajski", "Gospel Green", "Gouda", "Goutu", "Gowrie", "Grabetto", "Graddost",
            "Grafton Village Cheddar", "Grana", "Grana Padano", "Grand Vatel",
            "Grataron d' Areches", "Gratte-Paille", "Graviera", "Greuilh", "Greve",
            "Gris de Lille", "Gruyere", "Gubbeen", "Guerbigny", "Halloumi",
            "Halloumy (Australian)", "Haloumi-Style Cheese", "Harbourne Blue", "Havarti",
            "Heidi Gruyere", "Hereford Hop", "Herrgardsost", "Herriot Farmhouse", "Herve",
            "Hipi Iti", "Hubbardston Blue Cow", "Hushallsost", "Iberico", "Idaho Goatster",
            "Idiazabal", "Il Boschetto al Tartufo", "Ile d'Yeu", "Isle of Mull", "Jarlsberg",
            "Jermi Tortes", "Jibneh Arabieh", "Jindi Brie", "Jubilee Blue", "Juustoleipa",
            "Kadchgall", "Kaseri", "Kashta", "Kefalotyri", "Kenafa", "Kernhem", "Kervella Affine",
            "Kikorangi", "King Island Cape Wickham Brie", "King River Gold", "Klosterkaese",
            "Knockalara", "Kugelkase", "L'Aveyronnais", "L'Ecir de l'Aubrac", "La Taupiniere",
            "La Vache Qui Rit", "Laguiole", "Lairobell", "Lajta", "Lanark Blue", "Lancashire",
            "Langres", "Lappi", "Laruns", "Lavistown", "Le Brin", "Le Fium Orbo", "Le Lacandou",
            "Le Roule", "Leafield", "Lebbene", "Leerdammer", "Leicester", "Leyden", "Limburger",
            "Lincolnshire Poacher", "Lingot Saint Bousquet d'Orb", "Liptauer", "Little Rydings",
            "Livarot", "Llanboidy", "Llanglofan Farmhouse", "Loch Arthur Farmhouse",
            "Loddiswell Avondale", "Longhorn", "Lou Palou", "Lou Pevre", "Lyonnais", "Maasdam",
            "Macconais", "Mahoe Aged Gouda", "Mahon", "Malvern", "Mamirolle", "Manchego",
            "Manouri", "Manur", "Marble Cheddar", "Marbled Cheeses", "Maredsous", "Margotin",
            "Maribo", "Maroilles", "Mascares", "Mascarpone", "Mascarpone (Australian)",
            "Mascarpone Torta", "Matocq", "Maytag Blue", "Meira", "Menallack Farmhouse",
            "Menonita", "Meredith Blue", "Mesost", "Metton (Cancoillotte)", "Meyer Vintage Gouda",
            "Mihalic Peynir", "Milleens", "Mimolette", "Mine-Gabhar", "Mini Baby Bells", "Mixte",
            "Molbo", "Monastery Cheeses", "Mondseer", "Mont D'or Lyonnais", "Montasio",
            "Monterey Jack", "Monterey Jack Dry", "Morbier", "Morbier Cru de Montagne",
            "Mothais a la Feuille", "Mozzarella", "Mozzarella (Australian)",
            "Mozzarella di Bufala", "Mozzarella Fresh, in water", "Mozzarella Rolls", "Munster",
            "Murol", "Mycella", "Myzithra", "Naboulsi", "Nantais", "Neufchatel",
            "Neufchatel (Australian)", "Niolo", "Nokkelost", "Northumberland", "Oaxaca",
            "Olde York", "Olivet au Foin", "Olivet Bleu", "Olivet Cendre",
            "Orkney Extra Mature Cheddar", "Orla", "Oschtjepka", "Ossau Fermier", "Ossau-Iraty",
            "Oszczypek", "Oxford Blue", "P'tit Berrichon", "Palet de Babligny", "Paneer", "Panela",
            "Pannerone", "Pant ys Gawn", "Parmesan (Parmigiano)", "Parmigiano Reggiano",
            "Pas de l'Escalette", "Passendale", "Pasteurized Processed", "Pate de Fromage",
            "Patefine Fort", "Pave d'Affinois", "Pave d'Auge", "Pave de Chirac", "Pave du Berry",
            "Pecorino", "Pecorino in Walnut Leaves", "Pecorino Romano", "Peekskill Pyramid",
            "Pelardon des Cevennes", "Pelardon des Corbieres", "Penamellera", "Penbryn",
            "Pencarreg", "Perail de Brebis", "Petit Morin", "Petit Pardou", "Petit-Suisse",
            "Picodon de Chevre", "Picos de Europa", "Piora", "Pithtviers au Foin",
            "Plateau de Herve", "Plymouth Cheese", "Podhalanski", "Poivre d'Ane", "Polkolbin",
            "Pont l'Eveque", "Port Nicholson", "Port-Salut", "Postel", "Pouligny-Saint-Pierre",
            "Pourly", "Prastost", "Pressato", "Prince-Jean", "Processed Cheddar", "Provolone",
            "Provolone (Australian)", "Pyengana Cheddar", "Pyramide", "Quark",
            "Quark (Australian)", "Quartirolo Lombardo", "Quatre-Vents", "Quercy Petit",
            "Queso Blanco", "Queso Blanco con Frutas --Pina y Mango", "Queso de Murcia",
            "Queso del Montsec", "Queso del Tietar", "Queso Fresco", "Queso Fresco (Adobera)",
            "Queso Iberico", "Queso Jalapeno", "Queso Majorero", "Queso Media Luna",
            "Queso Para Frier", "Queso Quesadilla", "Rabacal", "Raclette", "Ragusano", "Raschera",
            "Reblochon", "Red Leicester", "Regal de la Dombes", "Reggianito", "Remedou",
            "Requeson", "Richelieu", "Ricotta", "Ricotta (Australian)", "Ricotta Salata", "Ridder",
            "Rigotte", "Rocamadour", "Rollot", "Romano", "Romans Part Dieu", "Roncal", "Roquefort",
            "Roule", "Rouleau De Beaulieu", "Royalp Tilsit", "Rubens", "Rustinu", "Saaland Pfarr",
            "Saanenkaese", "Saga", "Sage Derby", "Sainte Maure", "Saint-Marcellin",
            "Saint-Nectaire", "Saint-Paulin", "Salers", "Samso", "San Simon", "Sancerre",
            "Sap Sago", "Sardo", "Sardo Egyptian", "Sbrinz", "Scamorza", "Schabzieger", "Schloss",
            "Selles sur Cher", "Selva", "Serat", "Seriously Strong Cheddar", "Serra da Estrela",
            "Sharpam", "Shelburne Cheddar", "Shropshire Blue", "Siraz", "Sirene", "Smoked Gouda",
            "Somerset Brie", "Sonoma Jack", "Sottocenare al Tartufo", "Soumaintrain",
            "Sourire Lozerien", "Spenwood", "Sraffordshire Organic", "St. Agur Blue Cheese",
            "Stilton", "Stinking Bishop", "String", "Sussex Slipcote", "Sveciaost", "Swaledale",
            "Sweet Style Swiss", "Swiss", "Syrian (Armenian String)", "Tala", "Taleggio", "Tamie",
            "Tasmania Highland Chevre Log", "Taupiniere", "Teifi", "Telemea", "Testouri",
            "Tete de Moine", "Tetilla", "Texas Goat Cheese", "Tibet", "Tillamook Cheddar",
            "Tilsit", "Timboon Brie", "Toma", "Tomme Brulee", "Tomme d'Abondance",
            "Tomme de Chevre", "Tomme de Romans", "Tomme de Savoie", "Tomme des Chouans", "Tommes",
            "Torta del Casar", "Toscanello", "Touree de L'Aubier", "Tourmalet",
            "Trappe (Veritable)", "Trois Cornes De Vendee", "Tronchon", "Trou du Cru", "Truffe",
            "Tupi", "Turunmaa", "Tymsboro", "Tyn Grug", "Tyning", "Ubriaco", "Ulloa",
            "Vacherin-Fribourgeois", "Valencay", "Vasterbottenost", "Venaco", "Vendomois",
            "Vieux Corse", "Vignotte", "Vulscombe", "Waimata Farmhouse Blue",
            "Washed Rind Cheese (Australian)", "Waterloo", "Weichkaese", "Wellington",
            "Wensleydale", "White Stilton", "Whitestone Farmhouse", "Wigmore", "Woodside Cabecou",
            "Xanadu", "Xynotyro", "Yarg Cornish", "Yarra Valley Pyramid", "Yorkshire Blue",
            "Zamorano", "Zanetti Grana Padano", "Zanetti Parmigiano Reggiano"
    };

}

Ok Now we will create an XML for the overlay in the ListView that holds only a TextView.

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:textSize="50sp"
    android:textColor="#99FFFFFF"
    android:background="#BB000000"
    android:minWidth="70dip"
    android:maxWidth="70dip"
    android:padding="10dip"
    android:gravity="center"
/>

Ok Now we will create the ListView and populate the Data.
Create a java class that extends ListActivity and implements the Scroll Listener.

This is how it is going to be.

ListOverlay.java

package com.coderzheaven.alphabetprojectionlistview;

import android.app.ListActivity;
import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class ListOverlay extends ListActivity implements ListView.OnScrollListener {

    private final class RemoveWindow implements Runnable {
        public void run() {
            removeWindow();
        }
    }

    private RemoveWindow mRemoveWindow = new RemoveWindow();
    Handler mHandler = new Handler();
    private WindowManager mWindowManager;
    private TextView mDialogText;
    private boolean mShowing;
    private boolean mReady;
    private char mPrevLetter = Character.MIN_VALUE;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mWindowManager = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
        
        // Use an existing ListAdapter that will map an array
        // of strings to TextViews
        setListAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, mStrings));
        
        getListView().setOnScrollListener(this);
        
        LayoutInflater inflate = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        
        mDialogText = (TextView) inflate.inflate(R.layout.list_position, null);
        mDialogText.setVisibility(View.INVISIBLE);
        
        mHandler.post(new Runnable() {

            public void run() {
                mReady = true;
                WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
                        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
                        WindowManager.LayoutParams.TYPE_APPLICATION,
                        WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
                                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                        PixelFormat.TRANSLUCENT);
                mWindowManager.addView(mDialogText, lp);
            }});
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        mReady = true;
    }

    
    @Override
    protected void onPause() {
        super.onPause();
        removeWindow();
        mReady = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mWindowManager.removeView(mDialogText);
        mReady = false;
    }

    
   
    
    public void onScroll(AbsListView view, int firstVisibleItem,
            int visibleItemCount, int totalItemCount) {
        if (mReady) {
            char firstLetter = mStrings[firstVisibleItem].charAt(0);
            
            if (!mShowing && firstLetter != mPrevLetter) {

                mShowing = true;
                mDialogText.setVisibility(View.VISIBLE);
            }
            mDialogText.setText(((Character)firstLetter).toString());
            mHandler.removeCallbacks(mRemoveWindow);
            mHandler.postDelayed(mRemoveWindow, 3000);
            mPrevLetter = firstLetter;
        }
    }
    

    public void onScrollStateChanged(AbsListView view, int scrollState) {
    }
    
    
    private void removeWindow() {
        if (mShowing) {
            mShowing = false;
            mDialogText.setVisibility(View.INVISIBLE);
        }
    }

    private String[] mStrings = Cheeses.sCheeseStrings;
}

Hooray it’s done and it’s that simple.Go on and run the project and see the result.

You can download the java source code from here.

How to start with Android – Basics and Fundementals.

Hello all

This post for everyone who like to start with android and know the basics.

Android

It includes

Introduction to Android
Android Architecture
Dalvik Virtual Machine
Android Application Fundamental Components

The above links will be going by another android blog which also teaches you the basics of Android.

Check out these links and start coding in android.
You are on the right path because Android is the future.

Happy coding..

How to use ImageSwitcher in Android?

You can read more about ImageSwitcher here

http://developer.android.com/reference/android/widget/ImageSwitcher.html

ImageSwitcher1

ImageSwitcher1

Click on the link below to download the code.

This is the layout that contains the ImageSwitcher

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageSwitcher
        android:id="@+id/switcher"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" />

    <Gallery
        android:id="@+id/gallery"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:background="#55000000"
        android:gravity="center_vertical"
        android:spacing="16dp" />

</RelativeLayout>

What we will do is we will load some images into the Gallery and then load each image into the ImageSwitcher on clicking on each item in the Gallery.
Here is the java class that does it.

package com.example.imageswitcherdemo;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.Gallery.LayoutParams;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher;

@SuppressWarnings("deprecation")
public class MainActivity extends Activity implements
		AdapterView.OnItemSelectedListener, ViewSwitcher.ViewFactory {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(R.layout.activity_main);

		mSwitcher = (ImageSwitcher) findViewById(R.id.switcher);
		mSwitcher.setFactory(this);
		mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
				android.R.anim.fade_in));
		mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
				android.R.anim.fade_out));

		Gallery g = (Gallery) findViewById(R.id.gallery);
		g.setAdapter(new ImageAdapter(this));
		g.setOnItemSelectedListener(this);
	}

	public void onItemSelected(AdapterView<?> parent, View v, int position,
			long id) {
		mSwitcher.setImageResource(mImageIds[position]);
	}

	public void onNothingSelected(AdapterView<?> parent) {
	}

	public View makeView() {
		ImageView i = new ImageView(this);
		i.setBackgroundColor(0xFF000000);
		i.setScaleType(ImageView.ScaleType.FIT_CENTER);
		i.setLayoutParams(new ImageSwitcher.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		return i;
	}

	private ImageSwitcher mSwitcher;

	public class ImageAdapter extends BaseAdapter {
		public ImageAdapter(Context c) {
			mContext = c;
		}

		public int getCount() {
			return mThumbIds.length;
		}

		public Object getItem(int position) {
			return position;
		}

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

		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView i = new ImageView(mContext);

			i.setImageResource(mThumbIds[position]);
			i.setAdjustViewBounds(true);
			i.setLayoutParams(new Gallery.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
			i.setBackgroundResource(R.drawable.picture_frame);
			return i;
		}

		private Context mContext;

	}

	private Integer[] mThumbIds = { R.drawable.sample_thumb_0,
			R.drawable.sample_thumb_1, R.drawable.sample_thumb_2,
			R.drawable.sample_thumb_3, R.drawable.sample_thumb_4,
			R.drawable.sample_thumb_5, R.drawable.sample_thumb_6,
			R.drawable.sample_thumb_7 };

	private Integer[] mImageIds = { R.drawable.sample_0, R.drawable.sample_1,
			R.drawable.sample_2, R.drawable.sample_3, R.drawable.sample_4,
			R.drawable.sample_5, R.drawable.sample_6, R.drawable.sample_7 };

}

Make sure you have all these resources in the drawable folder

private Integer[] mThumbIds = { R.drawable.sample_thumb_0,
			R.drawable.sample_thumb_1, R.drawable.sample_thumb_2,
			R.drawable.sample_thumb_3, R.drawable.sample_thumb_4,
			R.drawable.sample_thumb_5, R.drawable.sample_thumb_6,
			R.drawable.sample_thumb_7 };

	private Integer[] mImageIds = { R.drawable.sample_0, R.drawable.sample_1,
			R.drawable.sample_2, R.drawable.sample_3, R.drawable.sample_4,
			R.drawable.sample_5, R.drawable.sample_6, R.drawable.sample_7 };

You can download the complete java source code from here

How to shutdown a computer using a C program?

Hello all

I have been posting Android posts for months, now there is a slight change, Here is a simple C program to shutdown your computer.

Let’s start.

If you are using Windows XP then use this code.

#include <stdio.h>
#include <stdlib.h>
 
main()
{
   char ch;
 
   printf("Do you want to shutdown your computer now (y/n)\n");
   scanf("%c",&ch);
 
   if (ch == 'y' || ch == 'Y')
      system("C:\\WINDOWS\\System32\\shutdown -s");
 
   return 0;
}

For Windows 7

#include <stdio.h>
#include <stdlib.h>
 
main()
{
   char ch;
 
   printf("Do you want to shutdown your computer now (y/n)\n");
   scanf("%c",&ch);
 
   if (ch == 'y' || ch == 'Y')
      system("C:\\WINDOWS\\System32\\shutdown /s");
 
   return 0;
}

In ubuntu

#include <stdio.h>
 
int main() {
  system("shutdown -P now");
  return 0;
}

Login as a root user for this to work otherwise you will get the message shutdown: Need to be root, now specifies that you want to shutdown immediately. ‘-P’ option specifies you want to power off your machine.

You can specify minutes as:
shutdown -P “number of minutes”.

ListView Bottom to Top Animation in Android.

Like my previous posts animation chapter is again continued. This time the animation in on a ListView from Bottom to Top.
You have already seen animations from Top to Bottom in my previous posts.
See some of my posts here.

All animation posts from CoderzHeaven is here

Bottom Top animation

Click on the download link at the bottom to download the source code.

So We will start

Like my other examples for this animation also we need two XML files one which extends the “layoutAnimation” class
Here is how it looks
layout_bottom_to_top_slide.xml

<?xml version="1.0" encoding="utf-8"?>
<layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
        android:delay="30%"
        android:animationOrder="reverse"
        android:animation="@anim/slide_right" />

Now the animation for Sliding to right.
slide_right.xml
After applying this animation the View will slide from right side of the screen.

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/accelerate_interpolator" >

    <translate
        android:duration="@android:integer/config_shortAnimTime"
        android:fromXDelta="-100%p"
        android:toXDelta="0" />

</set>

Our animation XML files are complete.
Now we will apply this in the layout.
activity_main.xml

<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layoutAnimation="@anim/layout_bottom_to_top_slide" />

Now just set this layout as the content of your activity. You can see the animation.
Just like this

package com.example.reverseanimationlistviews;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public class MainActivity extends ListActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		setListAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, mStrings));
	}

	private String[] mStrings = { "CoderzHeaven", "Android", "Google", "iPhone",
			"Windows Phone", "Samsung", "Sony" };
}

Note : Changing the delay in the XML, you can change the speed of the animation.

Download the complete Android source code from here.

Creating a Drawable animation in Android.

This is a simple example of how to animate a drawable in Android.
This example is from the official android demo applications.

Animate Drawable

Animate Drawable

Here we have 5 java classes.
AnimateDrawable.java
AnimateDrawables.java
GraphicsActivity.java
PictureLayout.java
ProxyDrawable.java

AnimateDrawable.java

package com.coderzheaven.animatedrawable;

import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Transformation;

public class AnimateDrawable extends ProxyDrawable {

    private Animation mAnimation;
    private Transformation mTransformation = new Transformation();

    public AnimateDrawable(Drawable target) {
        super(target);
    }

    public AnimateDrawable(Drawable target, Animation animation) {
        super(target);
        mAnimation = animation;
    }

    public Animation getAnimation() {
        return mAnimation;
    }

    public void setAnimation(Animation anim) {
        mAnimation = anim;
    }

    public boolean hasStarted() {
        return mAnimation != null && mAnimation.hasStarted();
    }

    public boolean hasEnded() {
        return mAnimation == null || mAnimation.hasEnded();
    }

    @Override
    public void draw(Canvas canvas) {
        Drawable dr = getProxy();
        if (dr != null) {
            int sc = canvas.save();
            Animation anim = mAnimation;
            if (anim != null) {
                anim.getTransformation(
                                    AnimationUtils.currentAnimationTimeMillis(),
                                    mTransformation);
                canvas.concat(mTransformation.getMatrix());
            }
            dr.draw(canvas);
            canvas.restoreToCount(sc);
        }
    }
}

AnimateDrawables.java


package com.coderzheaven.animatedrawable;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;

public class AnimateDrawables extends GraphicsActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new SampleView(this));
    }

    private static class SampleView extends View {
        private AnimateDrawable mDrawable;

        public SampleView(Context context) {
            super(context);
            setFocusable(true);
            setFocusableInTouchMode(true);

            Drawable dr = context.getResources().getDrawable(R.drawable.ic_launcher);
            dr.setBounds(0, 0, dr.getIntrinsicWidth(), dr.getIntrinsicHeight());

            Animation an = new TranslateAnimation(0, 100, 0, 200);
            an.setDuration(2000);
            an.setRepeatCount(-1);
            an.initialize(10, 10, 10, 10);

            mDrawable = new AnimateDrawable(dr, an);
            an.startNow();
        }

        @Override
        protected void onDraw(Canvas canvas) {
            canvas.drawColor(Color.WHITE);

            mDrawable.draw(canvas);
            invalidate();
        }
    }
}

GraphicsActivity.java

package com.coderzheaven.animatedrawable;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;

class GraphicsActivity extends Activity {
    // set to true to test Picture
    private static final boolean TEST_PICTURE = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void setContentView(View view) {
        if (TEST_PICTURE) {
            ViewGroup vg = new PictureLayout(this);
            vg.addView(view);
            view = vg;
        }

        super.setContentView(view);
    }
}

PictureLayout.java


package com.coderzheaven.animatedrawable;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Picture;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;

public class PictureLayout extends ViewGroup {
    private final Picture mPicture = new Picture();

    public PictureLayout(Context context) {
        super(context);
    }

    public PictureLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public void addView(View child) {
        if (getChildCount() > 1) {
            throw new IllegalStateException("PictureLayout can host only one direct child");
        }

        super.addView(child);
    }

    @Override
    public void addView(View child, int index) {
        if (getChildCount() > 1) {
            throw new IllegalStateException("PictureLayout can host only one direct child");
        }

        super.addView(child, index);
    }

    @Override
    public void addView(View child, LayoutParams params) {
        if (getChildCount() > 1) {
            throw new IllegalStateException("PictureLayout can host only one direct child");
        }

        super.addView(child, params);
    }

    @Override
    public void addView(View child, int index, LayoutParams params) {
        if (getChildCount() > 1) {
            throw new IllegalStateException("PictureLayout can host only one direct child");
        }

        super.addView(child, index, params);
    }

    @Override
    protected LayoutParams generateDefaultLayoutParams() {
        return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        final int count = getChildCount();

        int maxHeight = 0;
        int maxWidth = 0;

        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                measureChild(child, widthMeasureSpec, heightMeasureSpec);
            }
        }

        maxWidth += getPaddingLeft() + getPaddingRight();
        maxHeight += getPaddingTop() + getPaddingBottom();

        Drawable drawable = getBackground();
        if (drawable != null) {
            maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
            maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
        }

        setMeasuredDimension(resolveSize(maxWidth, widthMeasureSpec),
                resolveSize(maxHeight, heightMeasureSpec));
    }

    private void drawPict(Canvas canvas, int x, int y, int w, int h,
                          float sx, float sy) {
        canvas.save();
        canvas.translate(x, y);
        canvas.clipRect(0, 0, w, h);
        canvas.scale(0.5f, 0.5f);
        canvas.scale(sx, sy, w, h);
        canvas.drawPicture(mPicture);
        canvas.restore();
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(mPicture.beginRecording(getWidth(), getHeight()));
        mPicture.endRecording();

        int x = getWidth()/2;
        int y = getHeight()/2;

        drawPict(canvas, 0, 0, x, y,  1,  1);
		drawPict(canvas, x, 0, x, y, -1,  1);
		drawPict(canvas, 0, y, x, y,  1, -1);
		drawPict(canvas, x, y, x, y, -1, -1);
    }

    @Override
    public ViewParent invalidateChildInParent(int[] location, Rect dirty) {
        location[0] = getLeft();
        location[1] = getTop();
        dirty.set(0, 0, getWidth(), getHeight());
        return getParent();
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        final int count = super.getChildCount();

        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                final int childLeft = getPaddingLeft();
                final int childTop = getPaddingTop();
                child.layout(childLeft, childTop,
                        childLeft + child.getMeasuredWidth(),
                        childTop + child.getMeasuredHeight());

            }
        }
    }
}

ProxyDrawable.java

package com.coderzheaven.animatedrawable;

import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;

public class ProxyDrawable extends Drawable {

    private Drawable mProxy;
    private boolean mMutated;

    public ProxyDrawable(Drawable target) {
        mProxy = target;
    }

    public Drawable getProxy() {
        return mProxy;
    }

    public void setProxy(Drawable proxy) {
        if (proxy != this) {
            mProxy = proxy;
        }
    }

    @Override
    public void draw(Canvas canvas) {
        if (mProxy != null) {
            mProxy.draw(canvas);
        }
    }

    @Override
    public int getIntrinsicWidth() {
        return mProxy != null ? mProxy.getIntrinsicWidth() : -1;
    }

    @Override
    public int getIntrinsicHeight() {
        return mProxy != null ? mProxy.getIntrinsicHeight() : -1;
    }

    @Override
    public int getOpacity() {
        return mProxy != null ? mProxy.getOpacity() : PixelFormat.TRANSPARENT;
    }

    @Override
    public void setFilterBitmap(boolean filter) {
        if (mProxy != null) {
            mProxy.setFilterBitmap(filter);
        }
    }

    @Override
    public void setDither(boolean dither) {
        if (mProxy != null) {
            mProxy.setDither(dither);
        }
    }

    @Override
    public void setColorFilter(ColorFilter colorFilter) {
        if (mProxy != null) {
            mProxy.setColorFilter(colorFilter);
        }
    }

    @Override
    public void setAlpha(int alpha) {
        if (mProxy != null) {
            mProxy.setAlpha(alpha);
        }
    }

    @Override
    public Drawable mutate() {
        if (mProxy != null && !mMutated && super.mutate() == this) {
            mProxy.mutate();
            mMutated = true;
        }
        return this;
    }
}

Download the complete source code from here

Join the Forum discussion on this post

GridView RandomFade animation in Android

In some of my older posts I have already showed a lot of animations on ListView and GridViews. Search coderzheaven for ListView and GridView animations if you want to see the articles and posts.

This is also yet another post on animation. Here what I will do is create an animation in a GridView such that all cells will appear “RANDOM” with a fade animation.

GridView Random Animation
GridView Random Animation

So we will start

Click on the download link to download the code.

We will start with the animation XML first.

First create a folder named “anim” inside the “res” folder of your project.
Inside it create fade.xml and copy this code into it.

fade.xml

<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
       android:interpolator="@android:anim/accelerate_interpolator"
       android:fromAlpha="0.0" android:toAlpha="1.0"
       android:duration="@android:integer/config_longAnimTime" />

Then create anotther xml file named “layout_random_fade.xml” and copy this code into it.

<?xml version="1.0" encoding="utf-8"?>
<layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
        android:delay="0.5"
        android:animationOrder="random"
        android:animation="@anim/fade" />

This is the factor that creates the random animation.
android:animationOrder=”random”

And this one creates the fade animation.
android:animation=”@anim/fade”

Now we will write the activity that uses the gridview to create the animation.

package com.coderzheaven.gridviewrandomfadeanimation;

import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class MainActivity extends Activity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		loadApps();

		setContentView(R.layout.activity_main);
		GridView grid = (GridView) findViewById(R.id.grid);
		grid.setAdapter(new AppsAdapter());

	}

	private List<ResolveInfo> mApps;

	private void loadApps() {
		Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
		mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

		mApps = getPackageManager().queryIntentActivities(mainIntent, 0);
	}

	public class AppsAdapter extends BaseAdapter {
		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView i = new ImageView(MainActivity.this);

			ResolveInfo info = mApps.get(position % mApps.size());

			i.setImageDrawable(info.activityInfo.loadIcon(getPackageManager()));
			i.setScaleType(ImageView.ScaleType.FIT_CENTER);
			final int w = (int) (36 * getResources().getDisplayMetrics().density + 0.5f);
			i.setLayoutParams(new GridView.LayoutParams(w, w));
			return i;
		}

		public final int getCount() {
			return Math.min(32, mApps.size());
		}

		public final Object getItem(int position) {
			return mApps.get(position % mApps.size());
		}

		public final long getItemId(int position) {
			return position;
		}
	}
}

Ok Now it’s done. Run the project and see the result.

You can download the complete java android sample code from here.

Cascade animation in a ListView in Android.

Here is a simple example for cascade animation of a listview in android.

ListView cascade

ListView cascade

We use these classes for achieving this.

1. AnimationSet
Represents a group of Animations that should be played together. The transformation of each individual animation are composed together into a single transform. If AnimationSet sets any properties that its children also set (for example, duration or fillBefore), the values of AnimationSet override the child values.

The way that AnimationSet inherits behavior from Animation is important to understand. Some of the Animation attributes applied to AnimationSet affect the AnimationSet itself, some are pushed down to the children, and some are ignored, as follows:

duration, repeatMode, fillBefore, fillAfter: These properties, when set on an AnimationSet object, will be pushed down to all child animations.
repeatCount, fillEnabled: These properties are ignored for AnimationSet.
startOffset, shareInterpolator: These properties apply to the AnimationSet itself.

2. TranslateAnimation

Read about TranslateAnimation classes here.

LayoutAnimationController
A layout animation controller is used to animated a layout’s, or a view group’s, children. Each child uses the same animation but for every one of them, the animation starts at a different time. A layout animation controller is used by ViewGroup to compute the delay by which each child’s animation start must be offset. The delay is computed by using characteristics of each child, like its index in the view group. This standard implementation computes the delay by multiplying a fixed amount of miliseconds by the index of the child in its parent view group. Subclasses are supposed to override getDelayForView(android.view.View) to implement a different way of computing the delay. For instance, a GridLayoutAnimationController will compute the delay based on the column and row indices of the child in its parent view group. Information used to compute the animation delay of each child are stored in an instance of LayoutAnimationController.AnimationParameters, itself stored in the ViewGroup.LayoutParams of the view.

Just copy this simple code to your activity and see the cascading animation in the ListView.

package com.coderzheaven.listcascadeanimation;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LayoutAnimationController;
import android.view.animation.TranslateAnimation;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends ListActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setListAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, mStrings));

        AnimationSet set = new AnimationSet(true);

        Animation animation = new AlphaAnimation(0.0f, 1.0f); 
        animation.setDuration(500);
        set.addAnimation(animation);

        animation = new TranslateAnimation(
            Animation.RELATIVE_TO_SELF, 0.0f,Animation.RELATIVE_TO_SELF, 0.0f,
            Animation.RELATIVE_TO_SELF, -1.0f,Animation.RELATIVE_TO_SELF, 0.0f
        );
        animation.setDuration(100);
        set.addAnimation(animation);

        LayoutAnimationController controller = new LayoutAnimationController(set, 0.5f);
        ListView listView = getListView();        
        listView.setLayoutAnimation(controller);
    }

    private String[] mStrings = {
        "Bordeaux",
        "Lyon",
        "Marseille",
        "Nancy",
        "Paris",
        "Toulouse",
        "Strasbourg"
    };
}

Multiple Selection GridView in Android

This is a simple post that helps you to do multiple selection in a ListView.

Check out previous posts for 3D animation in a Listview.

At first we will see the XML layout file.
This layout contains a gridview since we are dealing with it only.

Multiple Selection GridView

Multiple Selection GridView

grid_1.xml

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/myGrid"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:columnWidth="60dp"
    android:gravity="center"
    android:horizontalSpacing="10dp"
    android:numColumns="auto_fit"
    android:padding="10dp"
    android:stretchMode="columnWidth"
    android:verticalSpacing="10dp" />

Now the MainActivity that does all the work for the multiple selection in a ListView.

package com.coderzheaven.multipleselectiongrid;

import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Checkable;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;

public class MainActivity extends Activity {

	GridView mGrid;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		loadApps();

		setContentView(R.layout.grid_1);
		mGrid = (GridView) findViewById(R.id.myGrid);
		mGrid.setAdapter(new AppsAdapter());
		mGrid.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL);
		mGrid.setMultiChoiceModeListener(new MultiChoiceModeListener());
	}

	private List<ResolveInfo> mApps;

	private void loadApps() {
		Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
		mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

		mApps = getPackageManager().queryIntentActivities(mainIntent, 0);
	}

	public class AppsAdapter extends BaseAdapter {
		public AppsAdapter() {
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			CheckableLayout l;
			ImageView i;

			if (convertView == null) {
				i = new ImageView(MainActivity.this);
				i.setScaleType(ImageView.ScaleType.FIT_CENTER);
				i.setLayoutParams(new ViewGroup.LayoutParams(50, 50));
				l = new CheckableLayout(MainActivity.this);
				l.setLayoutParams(new GridView.LayoutParams(
						GridView.LayoutParams.WRAP_CONTENT,
						GridView.LayoutParams.WRAP_CONTENT));
				l.addView(i);
			} else {
				l = (CheckableLayout) convertView;
				i = (ImageView) l.getChildAt(0);
			}

			ResolveInfo info = mApps.get(position);
			i.setImageDrawable(info.activityInfo.loadIcon(getPackageManager()));

			return l;
		}

		public final int getCount() {
			return mApps.size();
		}

		public final Object getItem(int position) {
			return mApps.get(position);
		}

		public final long getItemId(int position) {
			return position;
		}
	}

	public class CheckableLayout extends FrameLayout implements Checkable {
		private boolean mChecked;

		public CheckableLayout(Context context) {
			super(context);
		}

		@SuppressWarnings("deprecation")
		public void setChecked(boolean checked) {
			mChecked = checked;
			setBackgroundDrawable(checked ? getResources().getDrawable(
					R.drawable.blue) : null);
		}

		public boolean isChecked() {
			return mChecked;
		}

		public void toggle() {
			setChecked(!mChecked);
		}

	}

	public class MultiChoiceModeListener implements
			GridView.MultiChoiceModeListener {
		public boolean onCreateActionMode(ActionMode mode, Menu menu) {
			mode.setTitle("Select Items");
			mode.setSubtitle("One item selected");
			return true;
		}

		public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
			return true;
		}

		public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
			return true;
		}

		public void onDestroyActionMode(ActionMode mode) {
		}

		public void onItemCheckedStateChanged(ActionMode mode, int position,
				long id, boolean checked) {
			int selectCount = mGrid.getCheckedItemCount();
			switch (selectCount) {
			case 1:
				mode.setSubtitle("One item selected");
				break;
			default:
				mode.setSubtitle("" + selectCount + " items selected");
				break;
			}
		}

	}
}

You don’t have have to change anything in the manifest for this to work.
Now go on and run it.

You can download the complete sample code for the above post from here.

Join the Forum discussion on this post

Join the Forum discussion on this post

Different types of Animation – Push Up in, Push Up Out, Push Left in, Push Left Out, HyperSpace In, HyperSpace Out in a ViewFlipper in Android.

Hello all….
This is going to be a big post..

Check out my previous post for a rotate3D animation between a ListView and an Image.

How to create a rotate 3D Animation between a ListView and an ImageView in Android?

Today I will show you different types of Animations using ViewFlipper in a textView.

Here we have 4 TextViews which we will animate one after another using different animations.

I will introduce 4 sample animations which you can modify in any way according to your need.

Animations will be shown in a listview which onclick will animate the ViewFlipper.

At first you have to create a folder named “anim” inside the “res” folder and copy these XML files inside it.

hyperspace_in.xml

<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="300"
    android:fromAlpha="0.0"
    android:startOffset="1200"
    android:toAlpha="1.0" />

hyperspace_out.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false" >

    <scale
        android:duration="700"
        android:fillAfter="false"
        android:fillEnabled="true"
        android:fromXScale="1.0"
        android:fromYScale="1.0"
        android:interpolator="@android:anim/accelerate_decelerate_interpolator"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toXScale="1.4"
        android:toYScale="0.6" />

    <set android:interpolator="@android:anim/accelerate_interpolator" >
        <scale
            android:duration="400"
            android:fillAfter="true"
            android:fillBefore="false"
            android:fillEnabled="true"
            android:fromXScale="1.4"
            android:fromYScale="0.6"
            android:pivotX="50%"
            android:pivotY="50%"
            android:startOffset="700"
            android:toXScale="0.0"
            android:toYScale="0.0" />

        <rotate
            android:duration="400"
            android:fillAfter="true"
            android:fillBefore="false"
            android:fillEnabled="true"
            android:fromDegrees="0"
            android:pivotX="50%"
            android:pivotY="50%"
            android:startOffset="700"
            android:toDegrees="-45"
            android:toYScale="0.0" />
    </set>

</set>

push_left_in.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >

    <translate
        android:duration="300"
        android:fromXDelta="100%p"
        android:toXDelta="0" />

    <alpha
        android:duration="300"
        android:fromAlpha="0.0"
        android:toAlpha="1.0" />

</set>

push_left_out.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >

    <translate
        android:duration="300"
        android:fromXDelta="0"
        android:toXDelta="-100%p" />

    <alpha
        android:duration="300"
        android:fromAlpha="1.0"
        android:toAlpha="0.0" />

</set>

push_up_in.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >

    <translate
        android:duration="300"
        android:fromYDelta="100%p"
        android:toYDelta="0" />

    <alpha
        android:duration="300"
        android:fromAlpha="0.0"
        android:toAlpha="1.0" />

</set>

push_up_out.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >

    <translate
        android:duration="300"
        android:fromYDelta="0"
        android:toYDelta="-100%p" />

    <alpha
        android:duration="300"
        android:fromAlpha="1.0"
        android:toAlpha="0.0" />

</set>

All animation XML files are over. Now copy this XML to your main layout file.

animation_2.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="10dip" >

    <ViewFlipper
        android:id="@+id/flipper"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dip"
        android:flipInterval="2000" >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:text="Hello"
            android:textSize="26sp" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:text="From"
            android:textSize="26sp" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:text="CoderzHeaven"
            android:textSize="26sp" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:text="Heaven of all working Codes"
            android:textSize="26sp" />
    </ViewFlipper>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dip"
        android:text="Select the Animation to Apply" />

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

OK Done. Now our Layout files and animation files are over.

Now the MainActivity that uses these animation XML files and layouts.
MainActivity.java

package com.example.pushupanimation;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.ViewFlipper;

public class MainActivity extends Activity implements
		AdapterView.OnItemSelectedListener {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.animation_2);

		mFlipper = ((ViewFlipper) this.findViewById(R.id.flipper));
		mFlipper.startFlipping();

		Spinner s = (Spinner) findViewById(R.id.spinner);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, mStrings);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		s.setAdapter(adapter);
		s.setOnItemSelectedListener(this);
	}

	public void onItemSelected(AdapterView<?> parent, View v, int position,
			long id) {
		switch (position) {

		case 0:
			mFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
					R.anim.push_up_in));
			mFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,
					R.anim.push_up_out));
			break;
		case 1:
			mFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
					R.anim.push_left_in));
			mFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,
					R.anim.push_left_out));
			break;
		case 2:
			mFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
					android.R.anim.fade_in));
			mFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,
					android.R.anim.fade_out));
			break;
		default:
			mFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
					R.anim.hyperspace_in));
			mFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,
					R.anim.hyperspace_out));
			break;
		}
	}

	public void onNothingSelected(AdapterView<?> parent) {
	}

	private String[] mStrings = { "Push up", "Push left", "Cross fade",
			"Hyperspace" };

	private ViewFlipper mFlipper;

}

Read complete android sample code for this post from here

How to create a rotate 3D Animation between a ListView and an ImageView in Android?

At first we will create a class called “Rotate3dAnimation” which is responsible for the 3D Animation.

The Rotate3dAnimation.java looks like this.

package com.example.transition3d;

import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.graphics.Camera;
import android.graphics.Matrix;

/**
 * An animation that rotates the view on the Y axis between two specified angles.
 * This animation also adds a translation on the Z axis (depth) to improve the effect.
 */
public class Rotate3dAnimation extends Animation {
    private final float mFromDegrees;
    private final float mToDegrees;
    private final float mCenterX;
    private final float mCenterY;
    private final float mDepthZ;
    private final boolean mReverse;
    private Camera mCamera;

    /**
     * Creates a new 3D rotation on the Y axis. The rotation is defined by its
     * start angle and its end angle. Both angles are in degrees. The rotation
     * is performed around a center point on the 2D space, definied by a pair
     * of X and Y coordinates, called centerX and centerY. When the animation
     * starts, a translation on the Z axis (depth) is performed. The length
     * of the translation can be specified, as well as whether the translation
     * should be reversed in time.
     *
     * @param fromDegrees the start angle of the 3D rotation
     * @param toDegrees the end angle of the 3D rotation
     * @param centerX the X center of the 3D rotation
     * @param centerY the Y center of the 3D rotation
     * @param reverse true if the translation should be reversed, false otherwise
     */
    public Rotate3dAnimation(float fromDegrees, float toDegrees,
            float centerX, float centerY, float depthZ, boolean reverse) {
        mFromDegrees = fromDegrees;
        mToDegrees = toDegrees;
        mCenterX = centerX;
        mCenterY = centerY;
        mDepthZ = depthZ;
        mReverse = reverse;
    }

    @Override
    public void initialize(int width, int height, int parentWidth, int parentHeight) {
        super.initialize(width, height, parentWidth, parentHeight);
        mCamera = new Camera();
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        final float fromDegrees = mFromDegrees;
        float degrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime);

        final float centerX = mCenterX;
        final float centerY = mCenterY;
        final Camera camera = mCamera;

        final Matrix matrix = t.getMatrix();

        camera.save();
        if (mReverse) {
            camera.translate(0.0f, 0.0f, mDepthZ * interpolatedTime);
        } else {
            camera.translate(0.0f, 0.0f, mDepthZ * (1.0f - interpolatedTime));
        }
        camera.rotateY(degrees);
        camera.getMatrix(matrix);
        camera.restore();

        matrix.preTranslate(-centerX, -centerY);
        matrix.postTranslate(centerX, centerY);
    }
}

The Matrix class holds a 3×3 matrix for transforming coordinates. Matrix does not have a constructor, so it must be explicitly initialized using either reset() – to construct an identity matrix, or one of the set..() functions (e.g. setTranslate, setRotate, etc.).

Read more about Matrix Classes here.

Now the MainActivity that contains a ListView and an Image.
What we are going to do here is When we click the ListView the ListView will rotate with a 3D Animation and show the Image on the other side.

MainActivity.java

package com.example.transition3d;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;

public class MainActivity extends Activity implements
		AdapterView.OnItemClickListener, View.OnClickListener {
	private ListView mPhotosList;
	private ViewGroup mContainer;
	private ImageView mImageView;

	// Names of the photos we show in the list
	private static final String[] PHOTOS_NAMES = new String[] { "Lyon",
			"Livermore", "Tahoe Pier", "Lake Tahoe", "Grand Canyon", "Bodie" };

	// Resource identifiers for the photos we want to display
	private static final int[] PHOTOS_RESOURCES = new int[] {
			R.drawable.photo1, R.drawable.photo2, R.drawable.photo3,
			R.drawable.photo4, R.drawable.photo5, R.drawable.photo6 };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.animations_main_screen);

		mPhotosList = (ListView) findViewById(android.R.id.list);
		mImageView = (ImageView) findViewById(R.id.picture);
		mContainer = (ViewGroup) findViewById(R.id.container);

		// Prepare the ListView
		final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, PHOTOS_NAMES);

		mPhotosList.setAdapter(adapter);
		mPhotosList.setOnItemClickListener(this);

		// Prepare the ImageView
		mImageView.setClickable(true);
		mImageView.setFocusable(true);
		mImageView.setOnClickListener(this);

		// Since we are caching large views, we want to keep their cache
		// between each animation
		mContainer
				.setPersistentDrawingCache(ViewGroup.PERSISTENT_ANIMATION_CACHE);
	}

	/**
	 * Setup a new 3D rotation on the container view.
	 * 
	 * @param position
	 *            the item that was clicked to show a picture, or -1 to show the
	 *            list
	 * @param start
	 *            the start angle at which the rotation must begin
	 * @param end
	 *            the end angle of the rotation
	 */
	private void applyRotation(int position, float start, float end) {
		// Find the center of the container
		final float centerX = mContainer.getWidth() / 2.0f;
		final float centerY = mContainer.getHeight() / 2.0f;

		// Create a new 3D rotation with the supplied parameter
		// The animation listener is used to trigger the next animation
		final Rotate3dAnimation rotation = new Rotate3dAnimation(start, end,
				centerX, centerY, 310.0f, true);
		rotation.setDuration(500);
		rotation.setFillAfter(true);
		rotation.setInterpolator(new AccelerateInterpolator());
		rotation.setAnimationListener(new DisplayNextView(position));

		mContainer.startAnimation(rotation);
	}

	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
		// Pre-load the image then start the animation
		mImageView.setImageResource(PHOTOS_RESOURCES[position]);
		applyRotation(position, 0, 90);
	}

	public void onClick(View v) {
		applyRotation(-1, 180, 90);
	}

	/**
	 * This class listens for the end of the first half of the animation. It
	 * then posts a new action that effectively swaps the views when the
	 * container is rotated 90 degrees and thus invisible.
	 */
	private final class DisplayNextView implements Animation.AnimationListener {
		private final int mPosition;

		private DisplayNextView(int position) {
			mPosition = position;
		}

		public void onAnimationStart(Animation animation) {
		}

		public void onAnimationEnd(Animation animation) {
			mContainer.post(new SwapViews(mPosition));
		}

		public void onAnimationRepeat(Animation animation) {
		}
	}

	/**
	 * This class is responsible for swapping the views and start the second
	 * half of the animation.
	 */
	private final class SwapViews implements Runnable {
		private final int mPosition;

		public SwapViews(int position) {
			mPosition = position;
		}

		public void run() {
			final float centerX = mContainer.getWidth() / 2.0f;
			final float centerY = mContainer.getHeight() / 2.0f;
			Rotate3dAnimation rotation;

			if (mPosition > -1) {
				mPhotosList.setVisibility(View.GONE);
				mImageView.setVisibility(View.VISIBLE);
				mImageView.requestFocus();

				rotation = new Rotate3dAnimation(90, 180, centerX, centerY,
						310.0f, false);
			} else {
				mImageView.setVisibility(View.GONE);
				mPhotosList.setVisibility(View.VISIBLE);
				mPhotosList.requestFocus();

				rotation = new Rotate3dAnimation(90, 0, centerX, centerY,
						310.0f, false);
			}

			rotation.setDuration(500);
			rotation.setFillAfter(true);
			rotation.setInterpolator(new DecelerateInterpolator());

			mContainer.startAnimation(rotation);
		}
	}

}

Now the layout for the MainActivity.java

animations_main_screen.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@android:id/list"
        android:persistentDrawingCache="animation|scrolling"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layoutAnimation="@anim/layout_bottom_to_top_slide" />

    <ImageView
        android:id="@+id/picture"
        android:scaleType="fitCenter"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="gone" />

</FrameLayout>

Now we have some XML files for the animation of the ListView when it loads.
Here we are applying a bottom to top slide animation in the ListView when it loads.
So for that you have to first create a folder named “anim” in the “res” folder and create an XML named “layout_bottom_to_top_slide.xml” inside it.

layout_bottom_to_top_slide.xml

<?xml version="1.0" encoding="utf-8"?>
<layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
        android:delay="50%"
        android:animationOrder="reverse"
        android:animation="@anim/slide_right" />

Now you will get an error at this line.

android:animation="@anim/slide_right" 

So for that we create another animation. Create another XML inside the same “anim” folder, but now it is named “slide_right.xml”

slide_right.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/accelerate_interpolator">
    <translate android:fromXDelta="-100%p" android:toXDelta="0"
            android:duration="@android:integer/config_shortAnimTime" />
</set>

This is the translate animation that slides each row in the ListView.

Make sure you have six sample images with the named “photo1.jpg or png” , photo2.jpg etc…

Download the complete Android sample source code from here.

Join the Forum discussion on this post

HTC One X

HTC ONE X
GENERAL 2G Network GSM 850 / 900 / 1800 / 1900
3G Network HSDPA 850 / 900 / 1900 / 2100
HTD-SCDMA/ TD-HSPA 1900 / 2100 – HTC One XT
SIM Micro-SIM
Announced 2012, February
Status Available. Released 2012, May
BODY Dimensions 134.4 x 69.9 x 8.9 mm (5.29 x 2.75 x 0.35 in)
Weight 130 g (4.59 oz)
DISPLAY Type Super IPS LCD2 capacitive touchscreen, 16M colors
Size 720 x 1280 pixels, 4.7 inches (~312 ppi pixel density)
Multitouch Yes
Protection Corning Gorilla Glass
– HTC Sense UI
SOUND Alert types Vibration, MP3, WAV ringtones
Loudspeaker Yes
3.5mm jack Yes
MEMORY Card slot No
Internal 16/32 GB (26 GB user available), 1 GB RAM
DATA GPRS Yes
EDGE Yes
Speed HSDPA, 21 Mbps; HSUPA, 5.76 Mbps
WLAN Wi-Fi 802.11 a/b/g/n, Wi-Fi Direct, DLNA, Wi-Fi hotspot
Bluetooth Yes, v4.0 with A2DP
NFC Yes
USB Yes, microUSB v2.0 (MHL)
CAMERA Primary 8 MP, 3264×2448 pixels, autofocus, LED flash, check quality
Features Simultaneous HD video and image recording, geo-tagging, face and smile detection
Video Yes, 1080p@24fps, stereo sound rec., video stabilization, check quality
Secondary Yes, 1.3 MP, 720p
FEATURES OS Android OS, v4.0 (Ice Cream Sandwich), upgradable to v4.1.1 (Jelly Bean)
Chipset Nvidia Tegra 3
CPU Quad-core 1.5 GHz
GPU ULP GeForce
Sensors Accelerometer, gyro, proximity, compass
Messaging SMS (threaded view), MMS, Email, Push Email

HTC ONE X

Browser HTML, Adobe Flash
Radio Stereo FM radio with RDS
GPS Yes, with A-GPS support
Java Yes, via Java MIDP emulator
Colors Gray, White
– Beats Audio
– Active noise cancellation with dedicated mic
– Dropbox (25 GB storage)
– TV-out (via MHL A/V link)
– SNS integration
– MP4/H.263/H.264/WMV player
– MP3/eAAC+/WMA/WAV player
– Google Search, Maps, Gmail,
YouTube, Calendar, Google Talk
– Document viewer/editor
– Voice memo/dial/commands
– Predictive text input
BATTERY Non-removable Li-Po 1800 mAh battery
Stand-by No official data
Talk time No official data
MISC SAR US 0.68 W/kg (head) 0.70 W/kg (body)
SAR EU 0.68 W/kg (head)

Samsung Galaxy S4

Samsung Galaxy S4

GENERAL 2G Network GSM 850 / 900 / 1800 / 1900
3G Network HSDPA 850 / 900 / 1900 / 2100
4G Network LTE
SIM Micro-SIM
Announced 2013, March
Status Coming soon. Exp. release 2013, April 26th
BODY Dimensions 136.6 x 69.8 x 7.9 mm (5.38 x 2.75 x 0.31 in)
Weight 130 g (4.59 oz)
DISPLAY Type Super AMOLED capacitive touchscreen, 16M colors
Size 1080 x 1920 pixels, 5.0 inches (~441 ppi pixel density)
Multitouch Yes
Protection Corning Gorilla Glass 3
– TouchWiz UI
SOUND Alert types Vibration; MP3, WAV ringtones
Loudspeaker Yes
3.5mm jack Yes
MEMORY Card slot microSD, up to 64 GB
Internal 16/32/64 GB storage, 2 GB RAM
DATA GPRS Yes
EDGE Yes
Speed HSDPA, 42.2 Mbps; HSUPA, 5.76 Mbps
WLAN Wi-Fi 802.11 a/b/g/n/ac, dual-band, DLNA, Wi-Fi Direct, Wi-Fi hotspot
Bluetooth Yes, v4.0 with A2DP, EDR, LE
NFC Yes
Infrared port Yes
USB Yes, microUSB v2.0 (MHL 2), USB On-the-go, USB Host
CAMERA Primary 13 MP, 4128 x 3096 pixels, autofocus, LED flash, check quality
Features Dual Shot, Simultaneous HD video and image recording, geo-tagging, touch focus, face and smile detection, image stabilization, HDR
Video Yes, 1080p@30fps, dual-video rec., check quality
Secondary Yes, 2 MP,1080p@30fps, dual video call
FEATURES OS Android OS, v4.2.2 (Jelly Bean)
Chipset Exynos 5 Octa 5410
CPU Quad-core 1.6 GHz Cortex-A15 & quad-core 1.2 GHz Cortex-A7
GPU PowerVR SGX 544MP3
Sensors Accelerometer, gyro, proximity, compass, barometer, temperature, humidity, gesture

http://www.geeky-gadgets.com/wp-content/uploads/2013/02/samsung-galaxy-s4-mini1.jpg

Messaging SMS(threaded view), MMS, Email, Push Mail, IM, RSS
Browser HTML5, Adobe Flash
Radio No
GPS Yes, with A-GPS support and GLONASS
Java Yes, via Java MIDP emulator
Colors White Frost, Black Mist
– Wireless charging (market dependent)
– S-Voice natural language commands and dictation
– Smart stay, Smart pause, Smart scroll
– Air gestures
– Dropbox (50 GB storage)
– Active noise cancellation with dedicated mic
– TV-out (via MHL 2 A/V link)
– SNS integration
– MP4/DivX/XviD/WMV/H.264/H.263 player
– MP3/WAV/eAAC+/AC3/FLAC player
– Organizer
– Image/video editor
– Document viewer (Word, Excel, PowerPoint, PDF)
– Google Search, Maps, Gmail,
YouTube, Calendar, Google Talk, Picasa
– Voice memo/dial/commands
– Predictive text input (Swype)
BATTERY Li-Ion 2600 mAh battery

Buy Micromax A 91 Ninja online for Rs 8,499.

Micromax A91 NInja

The device was spotted on online site Saholic, while India TV News reported that the device was also available at ManiacStore for Rs 8,990 and Sulekha.com for Rs 9,000.

The A91 Ninja
The dual sim phone runs on Android 4.0 (Ice Cream Sandwich) and comes with 4GB internal storage, expandable via microSD. It runs on a MediaTek MT6577 1GHz dual-core processor, and has a PowerVR SGX531 GPU.

Read more from this link.
http://www.firstpost.com/tech/micromax-a91-ninja-with-ics-is-now-on-sale-online-for-rs-8499-689222.html

How to create a simple PopUp Menu in Android?

Hello all…

This is a simple tutorial for creating a simple popup menu like the one you see in the action bar options button.
Actually this is fairly simple with actionBar. But if you don’t want the actionbar and only want the popup menu, then here is the solution.

PopUp in Android

You can read more about PopupMenu here
http://developer.android.com/reference/android/widget/PopupMenu.html

Note : The “PopupMenu” Class is only supported in versions from 3.0 (HoneyComb). So you must Set your project SDK to 3.0 or greater while testing this post.

Android 3.0(API Level 11) provide android.widget.PopupMenu class, to displays a Menu in a modal popup window anchored to a View. The popup will appear below the anchor view if there is room, or above it if there is not. If the IME is visible the popup will not overlap it until it is touched. Touching outside of the popup will dismiss it.

So here we start…

At first what you have to do is

1. Create a folder named “menu” in the “res” folder.

then create an XML named “popup.xml” in it and copy these contents to it.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/search"
        android:icon="@android:drawable/ic_menu_search"
        android:title="Search"/>
    <item
        android:id="@+id/add"
        android:icon="@android:drawable/ic_menu_add"
        android:title="Add"/>
    <item
        android:id="@+id/edit"
        android:icon="@android:drawable/ic_menu_edit"
        android:title="Edit">
        <menu>
            <item
                android:id="@+id/share"
                android:icon="@android:drawable/ic_menu_share"
                android:title="Share"/>
        </menu>
    </item>

</menu>

Now in your activity copy this code.
My Activity is named “PopupMenu1″…
So my code look like this…

package com.example.popuptest;

import android.app.Activity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.PopupMenu;
import android.widget.Toast;

public class PopupMenu1 extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.popup_menu_1);
	}

	public void onPopupButtonClick(View button) {
		PopupMenu popup = new PopupMenu(this, button);
		popup.getMenuInflater().inflate(R.menu.popup, popup.getMenu());

		popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
			public boolean onMenuItemClick(MenuItem item) {
				Toast.makeText(PopupMenu1.this,
						"Clicked popup menu item " + item.getTitle(),
						Toast.LENGTH_SHORT).show();
				return true;
			}
		});

		popup.show();
	}
}

Reading webpage contents as a string in Windows Phone 7.

Hello all….

I am new to Windows Phone 7. So I am starting by posting a simple tutorial Here.

In this post I will try to read a webpage contents as a string and show it in a MessageBox.

https://lh3.googleusercontent.com/-m_5Xb6PLJiE/UV23ivMTXiI/AAAAAAAAAPs/Nkxw2rwtqy0/w258-h428-p-o/1.png

Here is the complete code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO;

namespace PhoneApp1
{
    public partial class MainPage : PhoneApplicationPage
    {        
        public MainPage()
        {
            InitializeComponent();
            RequestAsync( new Uri("http://google.com"), (html, exc) =>
             {
                 if (exc == null)
                 {
                     Dispatcher.BeginInvoke(() => MessageBox.Show(html));
                 }
                 else
                 {
                     // handle exception appropriately
                 }
             });
        }

        public static void RequestAsync(Uri url, Action<string, Exception> callback)
        {
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }

            try
            {
                var req = WebRequest.CreateHttp(url);

                AsyncCallback getTheResponse = ar =>
                {
                    try
                    {
                        string responseString;

                        var request = (HttpWebRequest)ar.AsyncState;

                        using (var resp = (HttpWebResponse)request.EndGetResponse(ar))
                        {
                            using (var streamResponse = resp.GetResponseStream())
                            {
                                using (var streamRead = new StreamReader(streamResponse))
                                {
                                    responseString = streamRead.ReadToEnd();
                                    Console.WriteLine(responseString);
                                }
                            }
                        }

                        callback(responseString, null);
                    }
                    catch (Exception ex)
                    {
                        callback(null, ex);
                    }
                };

                req.BeginGetResponse(getTheResponse, req);
            }
            catch (Exception ex)
            {
                callback(null, ex);
            }
        }
    }
}

How to send Data between two individual applications in Android?

We can send data between two individual applications in Android if the receiving application is configured to received that type of data.
For example if an application is to receive Image data then it’s manifest should contain the ImageFilter as Shown below

 <intent-filter>
                <action android:name="android.intent.action.SEND" />

                <category android:name="android.intent.category.DEFAULT" />

                <data android:mimeType="image/*" />
            </intent-filter>

For example ac activity in the receiving application is named “Receiver” then its entry in the AndroidManifest.xml should be like this.

 <activity
            android:name="com.example.receivingapplication.Receiver"
            android:label="@string/app_name" >             
            <intent-filter>
                <action android:name="android.intent.action.SEND" />

                <category android:name="android.intent.category.DEFAULT" />

                <data android:mimeType="image/*" />
            </intent-filter>
        </activity>

This line means that the Receiver application can receive any image type data.

Now in this post I have two application each have an activity. One is the Sending application and other is the receiving application.

At first I will explain what am I doing in “Sender application”

SENDING APPLICATION STARTS

My Only activity in the SenderApplication will have a layout like this

<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:text="Send Text" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:text="Send Image" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/textView1"
        android:layout_alignLeft="@+id/button1"
        android:layout_marginBottom="68dp"
        android:src="@drawable/ic_launcher" />

</LinearLayout>

My Activity will be looking like this

package com.example.sendingapplication;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class SendingActivity extends Activity {

	private static final int SELECT_PICTURE = 1;
	private String selectedImagePath;
	private ImageView img;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		img = (ImageView) findViewById(R.id.imageView1);
		Button send = (Button) findViewById(R.id.button1);
		send.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent sendIntent = new Intent();
				sendIntent.setAction(Intent.ACTION_SEND);
				sendIntent.putExtra(Intent.EXTRA_TEXT,
						"This is my text to send.");
				sendIntent.putExtra("MyKey",
						"This is second my text to send using my key.");
				sendIntent.setType("text/plain");
				startActivity(Intent.createChooser(sendIntent, "Send"));
			}
		});

		Button sendImage = (Button) findViewById(R.id.button2);
		sendImage.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent();
				intent.setType("image/*");
				intent.setAction(Intent.ACTION_GET_CONTENT);
				startActivityForResult(
						Intent.createChooser(intent, "Select Picture"),
						SELECT_PICTURE);
			}
		});

	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (requestCode == SELECT_PICTURE) {
				Uri selectedImageUri = data.getData();
				selectedImagePath = getPath(selectedImageUri);
				System.out.println("Image Path : " + selectedImagePath);
				img.setImageURI(selectedImageUri);
				sendImage(selectedImageUri);
			}
		}
	}

	void sendImage(Uri selectedImageUri) {
		Intent shareIntent = new Intent();
		shareIntent.setAction(Intent.ACTION_SEND);
		shareIntent.putExtra(Intent.EXTRA_STREAM, selectedImageUri);
		shareIntent.setType("image/*");
		startActivity(Intent.createChooser(shareIntent, "Send Image"));
	}

	public String getPath(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, projection, null, null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

}

Note that for sharing data we have to do nothing for the Sending Application.

Now Our Sending application is Over

RECEIVING APPLICATION STARTS.

This is my only activity in the Receiving application.

package com.example.receivingapplication;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ReceivingActivity extends Activity {

	private Bitmap bitmap;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		LinearLayout lin = new LinearLayout(this);

		Intent intent = getIntent();
		String action = intent.getAction();
		String type = intent.getType();
		TextView tv = new TextView(this);
		lin.addView(tv);
		lin.setOrientation(LinearLayout.VERTICAL);
		if (Intent.ACTION_SEND.equals(action) && type != null) {
			if ("text/plain".equals(type)) {

				tv.setText(intent.getExtras().getString(Intent.EXTRA_TEXT));
				tv.append("\n" + (intent.getExtras().getString("MyKey")));

			} else if (type.startsWith("image/")) {
				if (bitmap != null) {
					bitmap.recycle();
				}
				ImageView img = new ImageView(this);
				Bundle bundle = intent.getExtras();
				Uri uri = (Uri) bundle.get(Intent.EXTRA_STREAM);
				img.setImageURI(uri);
				lin.addView(img);
		}

		} else {
			// Handle other intents, such as being started from the home screen
		}
		setContentView(lin);
	}
}

This is the AndroidManifest for the Receiving application.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.receivingapplication"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.receivingapplication.ReceivingActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.SEND" />

                <category android:name="android.intent.category.DEFAULT" />

                <data android:mimeType="text/plain" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.SEND" />

                <category android:name="android.intent.category.DEFAULT" />

                <data android:mimeType="image/*" />
            </intent-filter>
        </activity>
    </application>

</manifest>

WATCH CAREFULLY THE INTENT FILTERS IN THE MANIFEST FOR THE RECEIVING ACTIVITY.
YOU CAN HAVE PLAIN TEXT, IMAGE OR MULTIPLE IMAGES SEND TO IT. I HAVE NOT WRITTEN CODE FOR SENDING MULTIPLE IMAGES NOW, IT WILL BE COMING IN THE NEXT UPDATE.

How to pass an object back from a finishing activity to the previous activity in android?

Hello all

This simple post tells you how to pass an object to next activity and pass it back when that activity is closed.

Check these posts before reading this post to get an overview of other methods.
1. How to pass an Object from One Activity to another in Android?

2. How to pass an arraylist value from one activity to another in android?

Note : The most important thing to note in this post is that for an object to be passed to an activity or back, the Object class should implement Serializable Interface.

Here MyObject is My class whose object is I am going to pass.
And the MyObject class should look like this.

MyObject.java

package com.example.passobjectback;

import java.io.Serializable;

public class MyObject implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	String name, website;

	public MyObject() {

	}

	public String getWebsite() {
		return website;
	}

	public void setWebsite(String website) {
		this.website = website;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}

This is my first activity that is sending MyObject to the Second Activity.

MainActivity.java

package com.example.passobjectback;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		final MyObject myobj = new MyObject();
		myobj.setName("Coderz"); 
		myobj.setWebsite("CoderzHeaven.com");

		Intent intent = new Intent(MainActivity.this, Second.class);
		intent.putExtra("myobject", myobj);
		startActivityForResult(intent, 1);
	} 

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 1) {
			if (resultCode == Activity.RESULT_OK) {
				Bundle b = data.getExtras();
				if (b != null) {
					MyObject myobj = (MyObject) b.getSerializable("Obj");
					System.out.println("Name : " + myobj.getName()
							+ ", Website : " + myobj.getWebsite());
				}  
			} else if (resultCode == 0) {
				System.out.println("RESULT CANCELLED");    
			}
		}
	}  
}

Note that here I am starting my second activity directly but using “startActivityForResult” because I am expecting something back from the Second Activity when it closes.

So we should have this method in the MainActivity to get the results.

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	super.onActivityResult(requestCode, resultCode, data);

}

This is my Second Activity that is accepting my object and sending back the same object which is received in the intent in the “onActivityResult” function in the MainActivity.

Second.java.

package com.example.passobjectback;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;


public class Second extends Activity {

	MyObject myobj;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		this.setTitle("Second Activity");

		Bundle b = getIntent().getExtras();

		if (b != null) {
			myobj = (MyObject) getIntent().getExtras()
					.getSerializable("myobject");

		}
	}

	@Override
	public void onBackPressed() {
		Intent intent = new Intent();
 		intent.putExtra("Obj", myobj);
		setResult(Activity.RESULT_OK, intent);
		finish();
		super.onBackPressed();
	}

}


I am getting the object back in the “onActivityResult” in the MainActivity when we press BackButton in the second Activity.
This is how we send back the object in the backpressed function

@Override
	public void onBackPressed() {
		Intent intent = new Intent();
 		intent.putExtra("Obj", myobj);
		setResult(Activity.RESULT_OK, intent);
		finish();
		super.onBackPressed();
	}

The main thing to note is that if you are closing the activity using back button then you should write the setResult() before “super.onBackPressed();” statement.

How to change the Style of a button dynamically in android?

Here I am going to change the style of a default button to buttonStyleSmall. So after that the button will appear small.

this simple code does this.

Button myButton = new Button(context, null, android.R.attr.buttonStyleSmall);

The try this adding to a layout

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                                     RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(android.widget.RelativeLayout.ALIGN_PARENT_RIGHT);
rLayout.addView(rightButton, lp);

How to create a simple App Launcher in Android?

You have seen Launchers listing your apps. Ever wondered how they get the list of all apps.

https://lh4.googleusercontent.com/-30y4nKNVGI0/UUxx3Nb7kcI/AAAAAAAAANY/I3f-77piaX4/w762-h428-p-o-k/app_launcher.png

This program help you to list all apps installed in your phone and in a gridview and invoke them.

Here we use this class..
PackageManager
Class for retrieving various kinds of information related to the application packages that are currently installed on the device. You can find this class through getPackageManager().

ResolveInfo
Information that is returned from resolving an intent against an IntentFilter. This partially corresponds to information collected from the AndroidManifest.xml’s tags.

First we will create the adapter for the GridView.

MyAdapter.java

package com.coderzheaven.applauncher;

import java.util.List;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class MyAdapter extends BaseAdapter {

	private Context myContext;
	private List<ResolveInfo> MyAppList;
	PackageManager myPackageManager;

	MyAdapter(Context c, List<ResolveInfo> appIntentList) {
		myContext = c;
		MyAppList = appIntentList;
		myPackageManager = c.getPackageManager();
	}

	@Override
	public int getCount() {
		return MyAppList.size();
	}

	@Override
	public Object getItem(int position) {
		return MyAppList.get(position);
	}

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

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

		ImageView imageView;
		if (convertView == null) {
			imageView = new ImageView(myContext);
			imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
			imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
			imageView.setPadding(8, 8, 8, 8);
		} else {
			imageView = (ImageView) convertView;
		}

		ResolveInfo resolveInfo = MyAppList.get(position);
		imageView.setImageDrawable(resolveInfo.loadIcon(myPackageManager));

		return imageView;

	}

}

Now the Activity that uses this adapter in the GridView.

package com.coderzheaven.applauncher;

import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;

public class AppListActivity extends Activity {

	PackageManager myPackageManager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		myPackageManager = getPackageManager();

		Intent intent = new Intent(Intent.ACTION_MAIN, null);
		intent.addCategory(Intent.CATEGORY_LAUNCHER);
		List<ResolveInfo> appIntentList = getPackageManager()
				.queryIntentActivities(intent, 0);

		GridView gridview = new GridView(this);
		gridview.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
		gridview.setNumColumns(GridView.AUTO_FIT);
		gridview.setHorizontalSpacing(30);
		gridview.setVerticalSpacing(30);
		gridview.setGravity(Gravity.CENTER);
		gridview.setColumnWidth(50);
		gridview.setPadding(10, 10, 10, 10);

		gridview.setAdapter(new MyAdapter(this, appIntentList));

		gridview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				ResolveInfo cleckedResolveInfo = (ResolveInfo) parent
						.getItemAtPosition(position);
				ActivityInfo clickedActivityInfo = cleckedResolveInfo.activityInfo;

				Intent intent = new Intent(Intent.ACTION_MAIN);
				intent.addCategory(Intent.CATEGORY_LAUNCHER);
				intent.setClassName(
						clickedActivityInfo.applicationInfo.packageName,
						clickedActivityInfo.name);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
						| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
				startActivity(intent);
			}

		});

		setContentView(gridview);
	}
}

How to encrypt and decrypt a file using “AES” algorithm in Android? – Google’s Advice

This is a simple example showing how to encrypt and decrypt a file in android.
what we will do in this post is

1. Generate a key for encrypting our data.
2. Create a file and save data using ENCRYPTION with our generated key to the SDCARD.
3. With the help of the key DECRYPT the File and show the contents.

An anti-pattern
A common (but incorrect) pattern that we’ve recently become aware of is to use SecureRandom as a means of generating deterministic key material, which would then be used to encrypt local credential caches. Examples are not hard to find, such as here, here, here, and elsewhere.

In this pattern, rather than storing an encryption key directly as a string inside an APK, the code uses a proxy string to generate the key instead — similar to a passphrase. This essentially obfuscates the key so that it’s not readily visible to attackers. However, a skilled attacker would be able to easily see around this strategy. We don’t recommend it.

This complete program does this.
Please check the Logcat for the output.

package com.coderzheaven.encryptfile;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;

public class MainActivity extends Activity {

	private String encryptedFileName = "Enc_File.txt";
	private static String algorithm = "AES";
	static SecretKey yourKey = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		saveFile("Hello From CoderzHeaven asaksjalksjals");
		decodeFile();

	}
	
	public static SecretKey generateKey(char[] passphraseOrPin, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException {
	    // Number of PBKDF2 hardening rounds to use. Larger values increase
	    // computation time. You should select a value that causes computation
	    // to take >100ms.
	    final int iterations = 1000; 

	    // Generate a 256-bit key
	    final int outputKeyLength = 256;

	    SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
	    KeySpec keySpec = new PBEKeySpec(passphraseOrPin, salt, iterations, outputKeyLength);
	    SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
	    return secretKey;
	}

	public static SecretKey generateKey() throws NoSuchAlgorithmException {
		// Generate a 256-bit key
		final int outputKeyLength = 256;
		SecureRandom secureRandom = new SecureRandom();
		// Do *not* seed secureRandom! Automatically seeded from system entropy.
		KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
		keyGenerator.init(outputKeyLength, secureRandom);
		yourKey = keyGenerator.generateKey();
		return yourKey;
	}

	public static byte[] encodeFile(SecretKey yourKey, byte[] fileData)
			throws Exception {
		byte[] encrypted = null;
		byte[] data = yourKey.getEncoded();
		SecretKeySpec skeySpec = new SecretKeySpec(data, 0, data.length,
				algorithm);
		Cipher cipher = Cipher.getInstance(algorithm);
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(
				new byte[cipher.getBlockSize()]));
		encrypted = cipher.doFinal(fileData);
		return encrypted;
	}

	public static byte[] decodeFile(SecretKey yourKey, byte[] fileData)
			throws Exception {
		byte[] decrypted = null;
		Cipher cipher = Cipher.getInstance(algorithm);
		cipher.init(Cipher.DECRYPT_MODE, yourKey, new IvParameterSpec(
				new byte[cipher.getBlockSize()]));
		decrypted = cipher.doFinal(fileData);
		return decrypted;
	}

	void saveFile(String stringToSave) {
		try {
			File file = new File(Environment.getExternalStorageDirectory()
					+ File.separator, encryptedFileName);
			BufferedOutputStream bos = new BufferedOutputStream(
					new FileOutputStream(file));
			yourKey = generateKey();
			byte[] filesBytes = encodeFile(yourKey, stringToSave.getBytes());
			bos.write(filesBytes);
			bos.flush();
			bos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	void decodeFile() {

		try {
			byte[] decodedData = decodeFile(yourKey, readFile());
			String str = new String(decodedData);
			System.out.println("DECODED FILE CONTENTS : " + str);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public byte[] readFile() {
		byte[] contents = null;

		File file = new File(Environment.getExternalStorageDirectory()
				+ File.separator, encryptedFileName);
		int size = (int) file.length();
		contents = new byte[size];
		try {
			BufferedInputStream buf = new BufferedInputStream(
					new FileInputStream(file));
			try {
				buf.read(contents);
				buf.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return contents;
	}

}


IF YOU WANT MORE SUCURITY THEN USE THE BELOW CODE…

If your app needs additional encryption, a recommended approach is to require a passphase or PIN to access your application. This passphrase could be fed into PBKDF2 to generate the encryption key. (PBKDF2 is a commonly used algorithm for deriving key material from a passphrase, using a technique known as “key stretching”.) Android provides an implementation of this algorithm inside SecretKeyFactory as PBKDF2WithHmacSHA1:

package com.coderzheaven.encryptfile;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;

public class ActivityEncrypt extends Activity {

	private String encryptedFileName = "Enc_File2.txt";
	private static String algorithm = "AES";
	static SecretKey yourKey = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		saveFile("Hello From CoderzHeaven testing ");
		decodeFile();

	}

	public static SecretKey generateKey(char[] passphraseOrPin, byte[] salt)
			throws NoSuchAlgorithmException, InvalidKeySpecException {
		// Number of PBKDF2 hardening rounds to use. Larger values increase
		// computation time. You should select a value that causes computation
		// to take >100ms.
		final int iterations = 1000;

		// Generate a 256-bit key
		final int outputKeyLength = 256;

		SecretKeyFactory secretKeyFactory = SecretKeyFactory
				.getInstance("PBKDF2WithHmacSHA1");
		KeySpec keySpec = new PBEKeySpec(passphraseOrPin, salt, iterations,
				outputKeyLength);
		yourKey = secretKeyFactory.generateSecret(keySpec);
		return yourKey;
	}

	public static SecretKey generateSalt() throws NoSuchAlgorithmException {
		// Generate a 256-bit key
		final int outputKeyLength = 256;

		SecureRandom secureRandom = new SecureRandom();
		// Do *not* seed secureRandom! Automatically seeded from system entropy.
		KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
		keyGenerator.init(outputKeyLength, secureRandom);
		SecretKey key = keyGenerator.generateKey();
		return key;
	}

	public static byte[] encodeFile(SecretKey yourKey, byte[] fileData)
			throws Exception {
		byte[] data = yourKey.getEncoded();
		SecretKeySpec skeySpec = new SecretKeySpec(data, 0, data.length,
				algorithm);
		Cipher cipher = Cipher.getInstance(algorithm);
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

		byte[] encrypted = cipher.doFinal(fileData);

		return encrypted;
	}

	public static byte[] decodeFile(SecretKey yourKey, byte[] fileData)
			throws Exception {
		byte[] data = yourKey.getEncoded();
		SecretKeySpec skeySpec = new SecretKeySpec(data, 0, data.length,
				algorithm);
		Cipher cipher = Cipher.getInstance(algorithm);
		cipher.init(Cipher.DECRYPT_MODE, skeySpec);

		byte[] decrypted = cipher.doFinal(fileData);

		return decrypted;
	}

	void saveFile(String stringToSave) {
		try {
			File file = new File(Environment.getExternalStorageDirectory()
					+ File.separator, encryptedFileName);
			BufferedOutputStream bos = new BufferedOutputStream(
					new FileOutputStream(file));
			char[] p = { 'p', 'a', 's', 's' };
			SecretKey yourKey = generateKey(p, generateSalt().toString()
					.getBytes());
			byte[] filesBytes = encodeFile(yourKey, stringToSave.getBytes());
			bos.write(filesBytes);
			bos.flush();
			bos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	void decodeFile() {
		try {
			byte[] decodedData = decodeFile(yourKey, readFile());
			String str = new String(decodedData);
			System.out.println("DECODED FILE CONTENTS : " + str);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public byte[] readFile() {
		byte[] contents = null;

		File file = new File(Environment.getExternalStorageDirectory()
				+ File.separator, encryptedFileName);
		int size = (int) file.length();
		contents = new byte[size];
		try {
			BufferedInputStream buf = new BufferedInputStream(
					new FileInputStream(file));
			try {
				buf.read(contents);
				buf.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return contents;
	}

}

Useful information collected from this link.
http://android-developers.blogspot.in/2013/02/using-cryptography-to-store-credentials.html

Highest Rated CEOs 2013

Mark Zuckerberg Facebook

Do you approve of the way your CEO is leading the company? See which CEOs have the highest approval ratings. The Glassdoor list is based entirely on employee feedback shared during the past year.

Check out the Top CEOs of 2013 and caste your vote here..

http://www.glassdoor.com/50-Highest-Rated-CEOs.htm

How to create transparency in your activity or dialog in android – different methods?

There are different ways for making an acitivity transparent.

First method

1. Through XML in AndroidManifest

like this.

<activity
            android:name="com.coderzheaven.interfacedemo.MainActivity"
            android:label="@string/app_name" 
           <strong> android:theme="@android:style/Theme.Translucent"</strong>
            >
          
        </activity>

Here we are using Android’s built in theme.

Method 2

Through styles

create a style like this in your styles.xml

 <style name="Theme.Transparent" parent="android:Theme">
        <item name="android:windowIsTranslucent">true</item>
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:windowContentOverlay">@null</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowIsFloating">true</item>
        <item name="android:backgroundDimEnabled">false</item>
    </style>

and applying like this in the AndroidManifest.xml

 <activity
            android:name="com.coderzheaven.interfacedemo.MainActivity"
            android:label="@string/app_name" 
            <strong>android:theme="@style/Theme.Transparent"</strong>
            >
        </activity>

Check out this post for the complete implementation.
http://www.coderzheaven.com/2011/07/20/how-to-create-a-transparent-activity-in-android/

Now we see how to make a Dialog transparent.

I am using this post for explaining this

http://www.coderzheaven.com/2013/02/13/extend-dialog-class-write-its-button-click-activity-interfaces-android/

package com.coderzheaven.interfacedemo;

import android.app.Activity;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.coderzheaven.interfacedemo.MyDialog.myOnClickListener;

public class MainActivity extends Activity {

	public myOnClickListener myListener;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_main);

		// create new onclicklistener interface //
		myListener = new myOnClickListener() {
			@Override
			public void onButtonClick() {
				Toast.makeText(getApplicationContext(),
						"This is a Transparent Custom Dialog Demo",
						Toast.LENGTH_LONG).show();
			}
		};

		MyDialog mydialog = new MyDialog(this, myListener);
		mydialog.show();
		addTransparency(mydialog);
		
	}

	void addTransparency(MyDialog mydialog) {
		mydialog.getWindow().setBackgroundDrawable(
				new ColorDrawable(android.graphics.Color.TRANSPARENT));
	}

}

This code does the work here for transparency in the Dialog.

void addTransparency(MyDialog mydialog) {
		mydialog.getWindow().setBackgroundDrawable(
				new ColorDrawable(android.graphics.Color.TRANSPARENT));
	}

How to Customize “Force Close” Dialog in Android?

An interesting post..

Everytime you write an app, it may or may not crash and we often see the “Force Close” Dialog.
But what if we can customize the “Force Close” Dialog itself.

Force Close in Android

This is done using “UncaughtExceptionHandler” class.

This post explains this.
here I am knowingly crashing the application like this

int y = 5/0;

Now this is my MainActivity that is going to crash.

package com.coderzheaven.forceclosecustomize;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		Thread.setDefaultUncaughtExceptionHandler(new UnCaughtException(MainActivity.this));
		
		int y = 5/0;
	}

}

And this is the Class that captures the Force Close Dialog and shows our CustomDialog.
UnCaughtException.java

package com.coderzheaven.forceclosecustomize;

import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.Date;
import java.util.Locale;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.os.Looper;
import android.os.StatFs;
import android.util.Log;

public class UnCaughtException implements UncaughtExceptionHandler {

	
	private Context context;
	private static Context context1;

	public UnCaughtException(Context ctx) {
		context = ctx;
		context1 = ctx;
	}

	private StatFs getStatFs() {
		File path = Environment.getDataDirectory();
		return new StatFs(path.getPath());
	}

	private long getAvailableInternalMemorySize(StatFs stat) {
		long blockSize = stat.getBlockSize();
		long availableBlocks = stat.getAvailableBlocks();
		return availableBlocks * blockSize;
	}

	private long getTotalInternalMemorySize(StatFs stat) {
		long blockSize = stat.getBlockSize();
		long totalBlocks = stat.getBlockCount();
		return totalBlocks * blockSize;
	}

	private void addInformation(StringBuilder message) {
		message.append("Locale: ").append(Locale.getDefault()).append('\n');
		try {
			PackageManager pm = context.getPackageManager();
			PackageInfo pi;
			pi = pm.getPackageInfo(context.getPackageName(), 0);
			message.append("Version: ").append(pi.versionName).append('\n');
			message.append("Package: ").append(pi.packageName).append('\n');
		} catch (Exception e) {
			Log.e("CustomExceptionHandler", "Error", e);
			message.append("Could not get Version information for ").append(
					context.getPackageName());
		}
		message.append("Phone Model: ").append(android.os.Build.MODEL)
				.append('\n');
		message.append("Android Version: ")
				.append(android.os.Build.VERSION.RELEASE).append('\n');
		message.append("Board: ").append(android.os.Build.BOARD).append('\n');
		message.append("Brand: ").append(android.os.Build.BRAND).append('\n');
		message.append("Device: ").append(android.os.Build.DEVICE).append('\n');
		message.append("Host: ").append(android.os.Build.HOST).append('\n');
		message.append("ID: ").append(android.os.Build.ID).append('\n');
		message.append("Model: ").append(android.os.Build.MODEL).append('\n');
		message.append("Product: ").append(android.os.Build.PRODUCT)
				.append('\n');
		message.append("Type: ").append(android.os.Build.TYPE).append('\n');
		StatFs stat = getStatFs();
		message.append("Total Internal memory: ")
				.append(getTotalInternalMemorySize(stat)).append('\n');
		message.append("Available Internal memory: ")
				.append(getAvailableInternalMemorySize(stat)).append('\n');
	}

	public void uncaughtException(Thread t, Throwable e) {
		try {
			StringBuilder report = new StringBuilder();
			Date curDate = new Date();
			report.append("Error Report collected on : ")
					.append(curDate.toString()).append('\n').append('\n');
			report.append("Informations :").append('\n');
			addInformation(report);
			report.append('\n').append('\n');
			report.append("Stack:\n");
			final Writer result = new StringWriter();
			final PrintWriter printWriter = new PrintWriter(result);
			e.printStackTrace(printWriter);
			report.append(result.toString());
			printWriter.close();
			report.append('\n');
			report.append("**** End of current Report ***");
			Log.e(UnCaughtException.class.getName(),
					"Error while sendErrorMail" + report);
			sendErrorMail(report);
		} catch (Throwable ignore) {
			Log.e(UnCaughtException.class.getName(),
					"Error while sending error e-mail", ignore);
		}
	}

	/**
	 * This method for call alert dialog when application crashed!
	 */
	public void sendErrorMail(final StringBuilder errorContent) {
		final AlertDialog.Builder builder = new AlertDialog.Builder(context);
		new Thread() {
			@Override
			public void run() {
				Looper.prepare();
				builder.setTitle("Sorry...!");
				builder.create();
				builder.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								System.exit(0);
							}
						});
				builder.setPositiveButton("Report",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								Intent sendIntent = new Intent(
										Intent.ACTION_SEND);
								String subject = "Your App crashed! Fix it!";
								StringBuilder body = new StringBuilder("Yoddle");
								body.append('\n').append('\n');
								body.append(errorContent).append('\n')
										.append('\n');
								// sendIntent.setType("text/plain");
								sendIntent.setType("message/rfc822");
								sendIntent.putExtra(Intent.EXTRA_EMAIL,
										new String[] { "coderzheaven@gmail.com" });
								sendIntent.putExtra(Intent.EXTRA_TEXT,
										body.toString());
								sendIntent.putExtra(Intent.EXTRA_SUBJECT,
										subject);
								sendIntent.setType("message/rfc822");
								context1.startActivity(sendIntent);
								System.exit(0);
							}
						});
				builder.setMessage("Oops,Your application has crashed");
				builder.show();
				Looper.loop();
			}
		}.start();
	}
}