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();
	}
}

How to create Gradient Buttons Dynamically without XML in Android?

Hello all..

I have shown you how to create gradient buttons in Android using XML in this post.

Now I will show you how to create these gradient buttons dynamically.

We will start with a class that extends StateListDrawable similar to state-list we use in XML

UIGradientSelector.java

package com.example.dynamicgradient;

import android.graphics.drawable.StateListDrawable;

/**
 * {@link StateListDrawable} that controls selection of
 * {@link UIGradientDrawable} based on the three basic button states.
 */
public class UIGradientSelector extends StateListDrawable {

	/**
	 * {@link UIGradientSelector} that selects the {@link UIGradientDrawable}
	 * defined by the colors for the three basic button states.
	 * 
	 * @param normalColors
	 *            Array of primitive ints that define the gradient colors for a
	 *            button in its normal state.
	 * @param focusedColors
	 *            Array of primitive ints that define the gradient colors for a
	 *            button in its focused state.
	 * @param pressedColors
	 *            Array of primitive ints that define the gradient colors for a
	 *            button in its pressed state. If the array is null, then
	 *            focusedColors will be used for the pressed state.
	 */
	public UIGradientSelector(int[] normalColors, int[] focusedColors,
			int[] pressedColors) {
		int stateFocused = android.R.attr.state_focused;
		int statePressed = android.R.attr.state_pressed;
		UIGradientDrawable normalGradient = new UIGradientDrawable(normalColors);
		UIGradientDrawable focusedGradient = new UIGradientDrawable(
				focusedColors);
		UIGradientDrawable pressedGradient;

		if (pressedColors == null) {
			pressedGradient = focusedGradient;
		} else {
			pressedGradient = new UIGradientDrawable(pressedColors);
		}

		addState(new int[] { stateFocused }, focusedGradient);
		addState(new int[] { statePressed }, pressedGradient);
		addState(new int[] { -statePressed, -stateFocused }, normalGradient);
	}
}

Now the class that extends PaintDrawable Class.

UIGradientDrawable.java

package com.example.dynamicgradient;

import android.graphics.drawable.PaintDrawable;
import android.graphics.drawable.shapes.RectShape;

/**
 * {@link PaintDrawable} that paints the surface via a {@link UIGradientShader}.
 */
public class UIGradientDrawable extends PaintDrawable {

    /**
     * {@link UIGradientDrawable} with an initial shape of a rounded rectangle
     * that transitions evenly between the specified colors.
     * 
     * @param colors
     *            Array of primitive ints that contain the argb values of the
     *            color to use for transitioning.
     */
    public UIGradientDrawable(int[] colors) {
        UIGradientShader gradientShader = new UIGradientShader(colors);
        setShape(new RectShape());
        setCornerRadius(8);
        setShaderFactory(gradientShader);
        setDither(true);
    }
}

Now the last java class that extends ShaderFactory.
UIGradientShader.java

package com.example.dynamicgradient;

import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Shader;
import android.graphics.drawable.ShapeDrawable.ShaderFactory;

/**
 * {@link ShaderFactory} that uses a {@link LinearGradient} to transition
 * between specified colors. Any number of colors may be specified.
 */
public class UIGradientShader extends ShaderFactory {
	private int[] colors;
	private float[] positions;

	/**
	 * {@link UIGradientShader} that spaces color transitions evenly across the
	 * painting surface.
	 * 
	 * @param colors
	 *            Array of primitive ints that contain the argb values of the
	 *            color to use for transitioning. If the array contains only one
	 *            color, then an argb of (0, 0, 0, 0) will be used for the end
	 *            color of the transition. If the array is set to null or
	 *            contains zero colors, then the transition will be from an argb
	 *            of (255, 255, 255, 255) to and argb of (0, 0, 0, 0).
	 * 
	 * @see Color
	 */
	public UIGradientShader(int[] colors) {
		init(colors, null);
	}

	/**
	 * {@link UIGradientShader} that spaces color transitions across the
	 * painting surface as specified.
	 * 
	 * @param colors
	 *            Array of primitive ints that contain the argb values of the
	 *            color to use for transitioning. If the array contains only one
	 *            color, then an argb of (0, 0, 0, 0) will be used for the end
	 *            color of the transition. If the array is set to null or
	 *            contains zero colors, then the transition will be from an argb
	 *            of (255, 255, 255, 255) to and argb of (0, 0, 0, 0).
	 * @param positions
	 *            Array of primitive floats that contain the position of the
	 *            transition points. If the array is null, then the color
	 *            transitions will be spaced evenly.
	 */
	public UIGradientShader(int[] colors, float[] positions) {
		init(colors, positions);
	}

	private void init(int[] colors, float[] positions) {
		if (colors == null || colors.length == 0) {
			this.colors = new int[2];
			this.colors[0] = Color.argb(255, 255, 255, 255);
			this.colors[1] = Color.argb(0, 0, 0, 0);
		} else if (colors.length == 1) {
			this.colors = new int[2];
			this.colors[0] = colors[0];
			this.colors[1] = Color.argb(0, 0, 0, 0);
		} else {
			this.colors = colors;
		}

		this.positions = positions;
	}

	public Shader resize(int width, int height) {
		LinearGradient lg = new LinearGradient(0, 0, 0, height, colors,
				positions, Shader.TileMode.REPEAT);
		return lg;
	}

}

Atlast the MainActivity Class that applies these java classes.

package com.example.dynamicgradient;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.Button;
import android.widget.LinearLayout;

public class MainActivity extends Activity {

	protected LinearLayout mainLayout;
	public static Button btn1 = null;
	public static Button btn2 = null;

	// Members
	private int[] normalColors = new int[4];
	private int[] focusedColors = new int[2];
	private int[] disabledColors = new int[1];
	private int defaultSkinR = 255;
	private int defaultSkinG = 100;
	private int defaultSkinB = 150;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		  mainLayout = (LinearLayout) getLayoutInflater().inflate(R.layout.activity_main,
	                null);

	        normalColors[0] = Color.argb(255, defaultSkinR, defaultSkinG,
	                defaultSkinB);
	        normalColors[1] = Color.argb(255, 217, 217, 217);
	        normalColors[2] = Color.argb(191, defaultSkinR, defaultSkinG,
	                defaultSkinB);
	        normalColors[3] = Color.argb(140, defaultSkinR, defaultSkinG,
	                defaultSkinB);

	        focusedColors[0] = Color.argb(100, 242, 242, 242);
	        focusedColors[1] = Color.BLUE;

	        UIGradientSelector gradientSelector1 = new UIGradientSelector(
	                normalColors, focusedColors, null);
	        UIGradientSelector gradientSelector2 = new UIGradientSelector(
	                normalColors, focusedColors, null);

	        disabledColors[0] = Color.argb(153, 216, 216, 216);
	        UIGradientDrawable disabledGradient = new UIGradientDrawable(
	                disabledColors);

	        btn1 = (Button) mainLayout.findViewById(R.id.btn1);
	        btn1.setBackgroundDrawable(gradientSelector1);

	        btn2 = (Button) mainLayout.findViewById(R.id.btn3);
	        btn2.setBackgroundDrawable(disabledGradient);

	        setContentView(mainLayout);
	}

}

Now the Layout XML that contains two buttons.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" 
    android:background="@android:color/black">

    <Button
        android:id="@+id/btn1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:textColor="@android:color/white"
        android:text="Dynamic Gradient Button" />

    <Button
        android:id="@+id/btn3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:textColor="@android:color/white"
        android:text="Dynamic Gradient Disbled Button" />

</LinearLayout>

How to Download a PDF File and open it in Android using an installed PDF Reader?

Actually this is fairly simple.

Open PDF

Open PDF

Open PDF

This simple code does this.

Uri path = Uri.fromFile(downloadFile(download_file_url));
				try {
					Intent intent = new Intent(Intent.ACTION_VIEW);
					intent.setDataAndType(path, "application/pdf");
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
					finish();
				} catch (ActivityNotFoundException e) {
					setError("PDF Reader application is not installed in your device");
				}

Here is the complete program that shows how to download a PDF File and open it in Android using an installed PDF Reader.

package com.example.openpdf;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.Gravity;
import android.widget.TextView;

public class MainActivity extends Activity {

	TextView tv_loading;
	String dest_file_path = "test.pdf";
	int downloadedSize = 0, totalsize;
	String download_file_url = "http://ilabs.uw.edu/sites/default/files/sample_0.pdf";
	float per = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		tv_loading = new TextView(this);
		setContentView(tv_loading);
		tv_loading.setGravity(Gravity.CENTER);
		tv_loading.setTypeface(null, Typeface.BOLD);
		downloadAndOpenPDF();
	}

	void downloadAndOpenPDF() {
		new Thread(new Runnable() {
			public void run() {
				Uri path = Uri.fromFile(downloadFile(download_file_url));
				try {
					Intent intent = new Intent(Intent.ACTION_VIEW);
					intent.setDataAndType(path, "application/pdf");
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
					finish();
				} catch (ActivityNotFoundException e) {
					tv_loading
							.setError("PDF Reader application is not installed in your device");
				}
			}
		}).start();
  
	}

	File downloadFile(String dwnload_file_path) {
		File file = null;
		try {

			URL url = new URL(dwnload_file_path);
			HttpURLConnection urlConnection = (HttpURLConnection) url
					.openConnection();

			urlConnection.setRequestMethod("GET");
			urlConnection.setDoOutput(true);

			// connect
			urlConnection.connect();

			// set the path where we want to save the file
			File SDCardRoot = Environment.getExternalStorageDirectory();
			// create a new file, to save the downloaded file
			file = new File(SDCardRoot, dest_file_path);

			FileOutputStream fileOutput = new FileOutputStream(file);

			// Stream used for reading the data from the internet
			InputStream inputStream = urlConnection.getInputStream();

			// this is the total size of the file which we are
			// downloading
			totalsize = urlConnection.getContentLength();
			setText("Starting PDF download...");

			// create a buffer...
			byte[] buffer = new byte[1024 * 1024];  
			int bufferLength = 0;

			while ((bufferLength = inputStream.read(buffer)) > 0) {
				fileOutput.write(buffer, 0, bufferLength);
				downloadedSize += bufferLength;
				per = ((float) downloadedSize / totalsize) * 100;
				setText("Total PDF File size  : "
						+ (totalsize / 1024)
						+ " KB\n\nDownloading PDF " + (int) per
						+ "% complete");
			}
			// close the output stream when complete //
			fileOutput.close();
			setText("Download Complete. Open PDF Application installed in the device.");

		} catch (final MalformedURLException e) {
			setTextError("Some error occured. Press back and try again.",
					Color.RED);
		} catch (final IOException e) {
			setTextError("Some error occured. Press back and try again.",
					Color.RED);
		} catch (final Exception e) {
			setTextError(
					"Failed to download image. Please check your internet connection.",
					Color.RED);
		}
		return file;
	}

	void setTextError(final String message, final int color) {
		runOnUiThread(new Runnable() {
			public void run() {
				tv_loading.setTextColor(color);
				tv_loading.setText(message);
			}
		});

	}

	void setText(final String txt) {
		runOnUiThread(new Runnable() {
			public void run() {
				tv_loading.setText(txt);
			}
		});

	}

}

Samsung Galaxy s4 Rumours – Bigger, Better, Eye-Based Scrolling

Samsung Galaxy S4

We know Samsung is set to reveal its Galaxy S4 smartphone on March 14th, and that the company has been desperately trying to spin up the same sort of pre-release hype about the device that Apple usually benefits from–including a rather strange promotion campaign involving a young “secret messenger” called Jeremy. Now a source that has been accurate with Samsung rumors in the past has leaked some specs of the device.

Read the complete story here…

http://www.fastcompany.com/3006602/tech-forecast/galaxy-s-iv-rumors-bigger-better-eye-based-scrolling

Different ways to KEEP SCREEN ON in Android.

These are the different ways in which you can keep your screen on in your app

1. Declare the screen stays on in your XML layout
2. Inform the window manager in onCreate you want the screen to stay on
3. WakeLock – used for critical downloads or things that you definitely don’t want the Android system shutting down for

First Method

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

public class ScreenOnFlagActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_flag);
 
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }
}

Next Method

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

public class ScreenOnWakeLockActivity extends Activity {
    private static final String TAG = "com.blundell.tut.ui.phone.ScreenOnWakeLockActivity.WAKE_LOCK_TAG";
    private WakeLock wakeLock;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wake_lock);
 
        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, TAG);
    }
 
    @Override
    protected void onResume() {
        super.onResume();
        wakeLock.acquire();
    }
 
    @Override
    protected void onPause() {
        super.onPause();
        wakeLock.release();
    }
}

The third method

Add this to your root layout

‘android:keepScreenOn=”true”‘

But for all these to work.
You have to add this permission in the AndroidManifest.xml

<uses-permission android:name="android.permission.WAKE_LOCK" />

Note : Don’t use this screen on feature unless you really need it, because it kills your battery.

Budget iPhone 5 Coming Soon

iPhone 5

The budget version of Apple’s latest iPhone will cost roughly $330 (£220), priced in order to appeal to young, middle class consumers in countries like China and India.
The claims about the price and the imminent release were made on the Japanese website Macotakara, following on from earlier reports about Apple plans for a cheaper phone.
In January it was reported that the planned new phone will resemble the iPhone 5 from the front but Apple will replace that handset’s aluminium body with a cheaper plastic casing.

Read More from here
http://www.telegraph.co.uk/technology/apple/9902864/Budget-iPhone-5-to-launch-soon.html

Galaxy S3 rival LG Optimus G @ Rs 30,990

LG launching Galaxy S3 rival Optimus G @ Rs 30,990

LG is all set to launch its erstwhile flagship smartphone Optimus G in India at an event in Mumbai on February 27. This device is pitted against the current market leader Samsung Galaxy S III and is the basis for the highly popular Google Nexus 4. India will be among the first countries outside the US, Canada, Japan and South Korea, as the device is yet to hit Europe as well as other major markets. The phone is available on online retail sites in the country at Rs 30,990 even before its launch.

Read More from
here

What are webservices? How we can use in Android?

A webservice can be

A web service is any piece of software that makes itself available over the internet and uses a standardized XML messaging system. XML is used to encode all communications to a web service. For example, a client invokes a web service by sending an XML message, then waits for a corresponding XML response. Because all communication is in XML, web services are not tied to any one operating system or programming language–Java can talk with Perl; Windows applications can talk with Unix applications.

Web Services are self-contained, modular, distributed, dynamic applications that can be described, published, located, or invoked over the network to create products, processes, and supply chains. These applications can be local, distributed, or Web-based. Web services are built on top of open standards such as TCP/IP, HTTP, Java, HTML, and XML.

Web services are XML-based information exchange systems that use the Internet for direct application-to-application interaction. These systems can include programs, objects, messages, or documents.

A web service is a collection of open protocols and standards used for exchanging data between applications or systems. Software applications written in various programming languages and running on various platforms can use web services to exchange data over computer networks like the Internet in a manner similar to inter-process communication on a single computer. This interoperability (e.g., between Java and Python, or Windows and Linux applications) is due to the use of open standards.

To summarize, a complete web service is, therefore, any service that:

1. Is available over the Internet or private (intranet) networks

2. Uses a standardized XML messaging system

3. Is not tied to any one operating system or programming language

4. Is self-describing via a common XML grammar

Is discoverable via a simple find mechanism

An Example

Consider a simple account-management and order -processing system. The accounting personnel use a client application built with Visual Basic or JSP to create new accounts and enter new customer orders.

The processing logic for this system is written in Java and resides on a Solaris machine, which also interacts with a database to store the information.
The steps illustrated above are as follows:

The client program bundles the account registration information into a SOAP message.
This SOAP message is sent to the Web Service as the body of an HTTP POST request.
The Web Service unpacks the SOAP request and converts it into a command that the application can understand. The application processes the information as required and responds with a new unique account number for that customer.
Next, the Web Service packages up the response into another SOAP message, which it sends back to the client program in response to its HTTP request.
The client program unpacks the SOAP message to obtain the results of the account registration process. For further details regarding the implementation of Web Services technology, read about the Cape Clear product set and review the product components.

In Android we can use it like an HTTP call. Several examples can be found on coderzheaven.com
Some of them are “connecting with php and android” where the php script can be called as a webservice which can be used by any system independent of the operating systems.

Some example links

http://www.coderzheaven.com/2012/09/25/table-values-mysql-database-show-android-tables/

How to create Simple Login form using php in android? – Connect php with android.