Monthly Archives: December 2012

Samsung Year in Review: Galaxy Triumphs, Apple Losses

Samsung produces a number of products – from kitchen appliances to PCs – but it was the company’s mobile division that made the most headlines in 2012.
The Korea-based company dominated the mobile phone space, introducing several new Galaxy devices throughout the year. But it couldn’t shake one its biggest rivals, Apple, which proved to be a worthy opponent in the courtroom and in stores.
Still, despite all the hysteria surrounding the launch of the iPhone 5 and iPad mini, it was Samsung and its Android-heavy lineup of devices like the Galaxy S III and Galaxy Note II that were the really mobile winners in 2012. Those two smartphones were only introduced in the second half of the year and they have already sold at least 30 million and 5 million worldwide, respectively.

Read more from here..

http://www.pcmag.com/article2/0,2817,2413529,00.asp

How to copy a file to another saved in SDCARD in Android?

Hello all…

This tutorial explains how to copy a file contents to another in Android. The file to copy is saved in SDCARD, however you can change the path to save it in your application sandbox.
if you want to save it in your sandbox, change the path to

/data/data/your_packagename/your_file.extension

Now we will see the layout for the program.


<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=".CopyFileActivity" >

    <TextView
        android:id="@+id/tv1"
        android:textStyle="bold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <TextView
        android:id="@+id/tv2"
        android:textStyle="bold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Copy First file to second" />
    
      <TextView
        android:id="@+id/tv3"
        android:textStyle="bold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />

</LinearLayout>

Now this is the java program that does the copying.

package com.coderzheaven.copyfiletoanother;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class CopyFileActivity extends Activity {

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

		Button btn = (Button) findViewById(R.id.btn1);
		TextView tv1 = (TextView) findViewById(R.id.tv1);
		final TextView tv2 = (TextView) findViewById(R.id.tv2);
		final TextView tv3 = (TextView) findViewById(R.id.tv3);

		final String path1 = Environment.getExternalStorageDirectory()
				+ "/first_file.txt";
		final String path2 = Environment.getExternalStorageDirectory()
				+ "/second_file.txt";

		File file1 = new File(path1);
		tv1.setText("First File  : " + file1.getPath() + "(" + file1.length()
				+ " Bytes)\nFirst file contents : \n" + readFromSD(path1));

		File file2 = new File(path2);
		tv2.setText("Second File  : " + file2.getPath() + "(" + file2.length()
				+ " Bytes)");

		btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (copyFile(path1, path2))
					Toast.makeText(getApplicationContext(), "File Copied.",
							Toast.LENGTH_LONG).show();
				else
					Toast.makeText(getApplicationContext(), "File Not Copied.",
							Toast.LENGTH_LONG).show();

				tv3.setText("Second File Contents :" + readFromSD(path2));

			}
		});

	}

	public static boolean copyFile(String from, String to) {
		try {
			int bytesum = 0;
			int byteread = 0;
			File oldfile = new File(from);
			if (oldfile.exists()) {
				InputStream inStream = new FileInputStream(from);
				FileOutputStream fs = new FileOutputStream(to);
				byte[] buffer = new byte[1444];
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread;
					fs.write(buffer, 0, byteread);
				}
				inStream.close();
				fs.close();
			}
			return true;
		} catch (Exception e) {
			System.out.println(e.getMessage());
			return false;
		}
	}

	public String readFromSD(String path) {
		File file = new File(path);
		StringBuilder text = new StringBuilder();
		try {
			BufferedReader br = new BufferedReader(new FileReader(file));
			String line;
			while ((line = br.readLine()) != null) {
				text.append(line);
				text.append('\n');
			}
		} catch (IOException e) {
		}
		return text.toString();
	}

}

Note : if you are writing to Sdcard, then always give this permission in the AndroidManifest file.

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

Another important thing is here I am not creating the file to copy, simply assuming that the first file is present in the sdcard in the correct path.

Copy File

Copy File

Download complete Android source code from here.

Download the tutorial PDF from here.

Apple fined by China court for copyright violation

A court in China has ordered Apple to pay compensation to eight Chinese writers and two companies for violating their copyrights.

They had claimed that unlicensed electronic versions of their books had been sold on Apple’s online store.

The court ordered Apple to pay them 1.03m yuan ($165,000; £100,000) in compensation, according to the official news agency Xinhua.
… Read more from here.

http://www.bbc.co.uk/news/business-20856199

How to store an Image from Android to a SQlite and retrieve it?

Hello all…

In today’s post I will show you how to store an image in an SQLite database and retrieve it.

Check out the output after running the program.

Image in SQLite DB

Image in SQLite DB

Image in SQLite DB

Image in SQLite DB

Image in SQLite DB

Image in SQLite DB

Image in SQLite DB

This is the layout for the MainActivity.

<ScrollView 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" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <Button
            android:id="@+id/get_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/textView1"
            android:layout_alignRight="@+id/textView1"
            android:text="Get Image" />

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/button1"
            android:layout_alignLeft="@+id/button1"
            android:src="@drawable/ic_action_search"
            android:visibility="gone" />

        <Button
            android:id="@+id/save_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/textView1"
            android:layout_alignRight="@+id/textView1"
            android:text="Save Image in DB" />

        <Button
            android:id="@+id/read_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/textView1"
            android:layout_alignRight="@+id/textView1"
            android:text="Read Image from DB" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            tools:context=".MainActivity" />

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/button1"
            android:layout_alignLeft="@+id/button1"
            android:layout_marginBottom="40dp"
            android:src="@drawable/ic_action_search" />
    </LinearLayout>

</ScrollView>

Now the code for the Activity.

MainActivity.java

package com.coderzheaven.saveimageindb;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
	protected static TextView textView;
	protected static ImageView image1, image2;
	protected Button get_image, save_image, read_image;
	private String selectedImagePath;
	private static final int SELECT_PICTURE = 1;
	String DB_NAME = Environment.getExternalStorageDirectory() + "/test.db";
	String TABLE_NAME = "mytable";

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

		image1 = (ImageView) findViewById(R.id.imageView1);
		image2 = (ImageView) findViewById(R.id.imageView2);
		textView = (TextView) findViewById(R.id.textView1);

		get_image = (Button) findViewById(R.id.get_image);
		get_image.setOnClickListener(this);

		save_image = (Button) findViewById(R.id.save_image);
		save_image.setOnClickListener(this);

		read_image = (Button) findViewById(R.id.read_image);
		read_image.setOnClickListener(this);

	}

	public void onClick(View v) {

		int id = v.getId();
		switch (id) {

		case R.id.get_image:
			Intent intent = new Intent();
			intent.setType("image/*");
			intent.setAction(Intent.ACTION_GET_CONTENT);
			startActivityForResult(
					Intent.createChooser(intent, "Select Picture"),
					SELECT_PICTURE);
			break;

		case R.id.save_image:
			createTable();
			saveInDB();
			break;

		case R.id.read_image:
			readFromDB();
			break;
		default:
			break;

		}
	}

	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);
				image1.setVisibility(View.VISIBLE);
				image1.setImageURI(selectedImageUri);
			}
		}
	}

	@SuppressWarnings("deprecation")
	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);
	}

	void createTable() {
		SQLiteDatabase myDb = openOrCreateDatabase(DB_NAME,
				Context.MODE_PRIVATE, null);
		String MySQL = "create table if not exists "
				+ TABLE_NAME
				+ " (_id INTEGER primary key autoincrement, name TEXT not null, image BLOB);";
		myDb.execSQL(MySQL);
		myDb.close();
	}

	void saveInDB() {
		SQLiteDatabase myDb = openOrCreateDatabase(DB_NAME,
				Context.MODE_PRIVATE, null);
		byte[] byteImage1 = null;
		String s = myDb.getPath();

		myDb.execSQL("delete from " + TABLE_NAME); 			// clearing the table
		ContentValues newValues = new ContentValues();
		String name = "CoderzHeaven";
		newValues.put("name", name);
		try {
			FileInputStream instream = new FileInputStream(selectedImagePath);
			BufferedInputStream bif = new BufferedInputStream(instream);
			byteImage1 = new byte[bif.available()];
			bif.read(byteImage1);
			newValues.put("image", byteImage1);
			long ret = myDb.insert(TABLE_NAME, null, newValues);
			if (ret < 0)
				textView.append("Error");
		} catch (IOException e) {
			textView.append("Error Exception : " + e.getMessage());
		}
		myDb.close();
		textView.append("\n Saving Details \n Name : " + name);
		textView.append("\n Image Size : " + byteImage1.length + " KB");
		textView.append("\n Saved in DB : " + s + "\n");
		Toast.makeText(this.getBaseContext(),
				"Image Saved in DB successfully.", Toast.LENGTH_SHORT).show();
	}

	void readFromDB() {
		byte[] byteImage2 = null;
		SQLiteDatabase myDb;
		myDb = openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null);
		Cursor cur = myDb.query(TABLE_NAME, null, null, null, null, null, null);
		cur.moveToFirst();
		while (cur.isAfterLast() == false) {
			textView.append("\n Reading Details \n Name : " + cur.getString(1));
			cur.moveToNext();
		}

		// /////Read data from blob field////////////////////
		cur.moveToFirst();
		byteImage2 = cur.getBlob(cur.getColumnIndex("image"));
		setImage(byteImage2);
		cur.close();
		myDb.close();
		Toast.makeText(this.getBaseContext(),
				"Image read from DB successfully.", Toast.LENGTH_SHORT).show();
		Toast.makeText(this.getBaseContext(),
				"If your image is big, please scrolldown to see the result.",
				Toast.LENGTH_SHORT).show();
	}

	void setImage(byte[] byteImage2) {
		image2.setImageBitmap(BitmapFactory.decodeByteArray(byteImage2, 0,
				byteImage2.length));
		textView.append("\n Image Size : " + byteImage2.length + " KB");
	}

}

Please leave your valuable comments.

Cheaper, slimmer Google Nexus 7 rumored for Q1 2013

Google

Google may be readying a revamped model of the middle sibling in its Nexus line of Android devices for as early as the first quarter of 2013, if the supply-chain snoops at Taiwanese tech news site DigiTimes are correct.

Sources in the tech manufacturing sector are whispering that the Chocolate Factory and its manufacturing partner Asustek are “making headway” on a new, slimmer version of the popular Nexus 7 fondleslab.

Google – working on a secret phone called the “X-Phone”

Google

Google is working on what the company is internally calling the “X Phone” that it hopes will provide a credible challenge to Apple and Samsung, reveals the Wall Street Journal. Google is using Motorola, which it acquired seven months ago for $12.5 billion, to design a phone that will supposedly have new features unlike any seen in the crop of products currently in the market. But becoming a cutting-edge phone manufacturer is proving a tad more difficult for Google than it had foreseen and the Internet giant has run into several supply-chain management problems, according to the paper.

source : http://www.slate.com/blogs/the_slatest/2012/12/22/google_works_on_secret_phone_to_rival_iphone_apple.html

Samsung’s New Galaxy Grand with Dual-SIM, 5-Inch Display

Samsung Galxy Grand

Samsung has added the Grand, a new midrange smartphone, to its Android-running Galaxy lineup. At a glance, it strongly resembles the Galaxy S III, though Grand features a larger, though lower-resolution display—a 5-inch WVGA TFT LCD compared with the 4.8-inch HD Super AMOLED on the Galaxy S III—and will be available in a dual Subscriber Identity Module (SIM) version.

Read More from here

http://www.eweek.com/mobile/samsungs-new-galaxy-grand-offers-dual-sim-5-inch-display

A better Google News experience on tablets

Google News on Tablets

There’s something special about reading news on your tablet. Indeed, swiping through articles brings to mind the familiar feeling of flipping through a favorite magazine or newspaper. Starting today, Google News feels even more natural and fluid on tablet devices. For example:

You can find new articles, news sources, and even topics of interest with intuitive gestures. Swipe horizontally between sections – from Business to Entertainment, for example – or tap “Explore in depth” to see multiple articles and other info related to a particular story.

Read more from here

Samsung Galaxy S3 will get Android 4.1 Jelly Bean this Friday

Samsung Galxy S3 gets Android JellyBean Update
US Cellular has announced that it would be rolling Jelly Bean out to its Samsung Galaxy S3 starting this Friday, December 21st. This would make it the fifth and final upgrade needing to go out to the Samsung Galaxy S3 here in the United States as all major carriers, including Verizon, will have been offering it.

Read more from here….

http://phandroid.com/2012/12/17/us-cellular-galaxy-s3-jelly-bean/

Join the Forum discussion on this post

CoverFlow in Android – Complete implementation with source code.

Have you seen the coverflow in iPhone.
This is the Android implementation of CoverFlow.

Please leave your comments if this article is helpful for you.

Let’s see how.

This is the CoverFlow class that extends the Gallery.

package com.coderzheaven.coverflow;

import android.content.Context;
import android.graphics.Camera;
import android.graphics.Color;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Transformation;
import android.widget.Gallery;
import android.widget.ImageView;

@SuppressWarnings("deprecation")
public class CoverFlow extends Gallery {

	/**
	 * Graphics Camera used for transforming the matrix of ImageViews
	 */
	private Camera mCamera = new Camera();

	/**
	 * The maximum angle the Child ImageView will be rotated by
	 */
	private int mMaxRotationAngle = 60;

	/**
	 * The maximum zoom on the centre Child
	 */
	private int mMaxZoom = -120;

	/**
	 * The Centre of the Coverflow
	 */
	private int mCoveflowCenter;

	public CoverFlow(Context context) {
		super(context);
		this.setStaticTransformationsEnabled(true);
		this.setBackgroundColor(Color.BLACK);
	}

	public CoverFlow(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.setStaticTransformationsEnabled(true);
		this.setBackgroundColor(Color.BLACK);
	}

	public CoverFlow(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		this.setStaticTransformationsEnabled(true);
		this.setBackgroundColor(Color.BLACK);
	}

	/**
	 * Get the max rotational angle of the image
	 * 
	 * @return the mMaxRotationAngle
	 */
	public int getMaxRotationAngle() {
		return mMaxRotationAngle;
	}

	/**
	 * Set the max rotational angle of each image
	 * 
	 * @param maxRotationAngle
	 *            the mMaxRotationAngle to set
	 */
	public void setMaxRotationAngle(int maxRotationAngle) {
		mMaxRotationAngle = maxRotationAngle;
	}

	/**
	 * Get the Max zoom of the centre image
	 * 
	 * @return the mMaxZoom
	 */
	public int getMaxZoom() {
		return mMaxZoom;
	}

	/**
	 * Set the max zoom of the centre image
	 * 
	 * @param maxZoom
	 *            the mMaxZoom to set
	 */
	public void setMaxZoom(int maxZoom) {
		mMaxZoom = maxZoom;
	}

	/**
	 * Get the Centre of the Coverflow
	 * 
	 * @return The centre of this Coverflow.
	 */
	private int getCenterOfCoverflow() {
		return (getWidth() - getPaddingLeft() - getPaddingRight()) / 2
				+ getPaddingLeft();
	}

	/**
	 * Get the Centre of the View
	 * 
	 * @return The centre of the given view.
	 */
	private static int getCenterOfView(View view) {
		return view.getLeft() + view.getWidth() / 2;
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see #setStaticTransformationsEnabled(boolean)
	 */
	protected boolean getChildStaticTransformation(View child, Transformation t) {

		final int childCenter = getCenterOfView(child);
		final int childWidth = child.getWidth();
		int rotationAngle = 0;

		t.clear();
		t.setTransformationType(Transformation.TYPE_MATRIX);

		if (childCenter == mCoveflowCenter) {
			transformImageBitmap((ImageView) child, t, 0);
		} else {
			rotationAngle = (int) (((float) (mCoveflowCenter - childCenter) / childWidth) * mMaxRotationAngle);
			if (Math.abs(rotationAngle) > mMaxRotationAngle) {
				rotationAngle = (rotationAngle < 0) ? -mMaxRotationAngle
						: mMaxRotationAngle;
			}
			transformImageBitmap((ImageView) child, t, rotationAngle);
		}

		return true;
	}

	/**
	 * This is called during layout when the size of this view has changed. If
	 * you were just added to the view hierarchy, you're called with the old
	 * values of 0.
	 * 
	 * @param w
	 *            Current width of this view.
	 * @param h
	 *            Current height of this view.
	 * @param oldw
	 *            Old width of this view.
	 * @param oldh
	 *            Old height of this view.
	 */
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		mCoveflowCenter = getCenterOfCoverflow();
		super.onSizeChanged(w, h, oldw, oldh);
	}

	/**
	 * Transform the Image Bitmap by the Angle passed
	 * 
	 * @param imageView
	 *            ImageView the ImageView whose bitmap we want to rotate
	 * @param t
	 *            transformation
	 * @param rotationAngle
	 *            the Angle by which to rotate the Bitmap
	 */
	private void transformImageBitmap(ImageView child, Transformation t,
			int rotationAngle) {
		mCamera.save();
		final Matrix imageMatrix = t.getMatrix();
		;
		final int imageHeight = child.getLayoutParams().height;
		;
		final int imageWidth = child.getLayoutParams().width;
		final int rotation = Math.abs(rotationAngle);

		mCamera.translate(0.0f, 0.0f, 100.0f);

		// As the angle of the view gets less, zoom in
		if (rotation < mMaxRotationAngle) {
			float zoomAmount = (float) (mMaxZoom + (rotation * 1.5));
			mCamera.translate(0.0f, 0.0f, zoomAmount);
		}

		mCamera.rotateY(rotationAngle);
		mCamera.getMatrix(imageMatrix);
		imageMatrix.preTranslate(-(imageWidth / 2), -(imageHeight / 2));
		imageMatrix.postTranslate((imageWidth / 2), (imageHeight / 2));
		mCamera.restore();
	}
}

Now the main activity that implements the coverflow.

package com.coderzheaven.coverflow;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

public class CoverFlowDemo extends Activity {

	@SuppressWarnings("deprecation")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		CoverFlow coverFlow;
		coverFlow = new CoverFlow(this);

		coverFlow.setAdapter(new ImageAdapter(this));

		ImageAdapter coverImageAdapter = new ImageAdapter(this);

		coverFlow.setAdapter(coverImageAdapter);

		coverFlow.setSpacing(-25);
		coverFlow.setSelection(4, true);
		coverFlow.setAnimationDuration(1000);

		setContentView(coverFlow);
	}

	public class ImageAdapter extends BaseAdapter {
		int mGalleryItemBackground;
		private Context mContext;

		private Integer[] mImageIds = { R.drawable.android,
				R.drawable.img1, R.drawable.img2,
				R.drawable.img3, R.drawable.img4,
				R.drawable.img1, R.drawable.img2,
				R.drawable.img3, R.drawable.img4
		};

		private ImageView[] mImages;

		public ImageAdapter(Context c) {
			mContext = c;
			mImages = new ImageView[mImageIds.length];
		}

		@SuppressWarnings("deprecation")
		public boolean createReflectedImages() {
			// The gap we want between the reflection and the original image
			final int reflectionGap = 4;

			int index = 0;
			for (int imageId : mImageIds) {
				Bitmap originalImage = BitmapFactory.decodeResource(
						getResources(), imageId);
				int width = originalImage.getWidth();
				int height = originalImage.getHeight();

				// This will not scale but will flip on the Y axis
				Matrix matrix = new Matrix();
				matrix.preScale(1, -1);

				// Create a Bitmap with the flip matrix applied to it.
				// We only want the bottom half of the image
				Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0,
						height / 2, width, height / 2, matrix, false);

				// Create a new bitmap with same width but taller to fit
				// reflection
				Bitmap bitmapWithReflection = Bitmap.createBitmap(width,
						(height + height / 2), Config.ARGB_8888);

				// Create a new Canvas with the bitmap that's big enough for
				// the image plus gap plus reflection
				Canvas canvas = new Canvas(bitmapWithReflection);
				// Draw in the original image
				canvas.drawBitmap(originalImage, 0, 0, null);
				// Draw in the gap
				Paint deafaultPaint = new Paint();
				canvas.drawRect(0, height, width, height + reflectionGap,
						deafaultPaint);
				// Draw in the reflection
				canvas.drawBitmap(reflectionImage, 0, height + reflectionGap,
						null);

				// Create a shader that is a linear gradient that covers the
				// reflection
				Paint paint = new Paint();
				LinearGradient shader = new LinearGradient(0,
						originalImage.getHeight(), 0,
						bitmapWithReflection.getHeight() + reflectionGap,
						0x70ffffff, 0x00ffffff, TileMode.CLAMP);
				// Set the paint to use this shader (linear gradient)
				paint.setShader(shader);
				// Set the Transfer mode to be porter duff and destination in
				paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
				// Draw a rectangle using the paint with our linear gradient
				canvas.drawRect(0, height, width,
						bitmapWithReflection.getHeight() + reflectionGap, paint);

				ImageView imageView = new ImageView(mContext);
				imageView.setImageBitmap(bitmapWithReflection);
				android.widget.Gallery.LayoutParams imgLayout = new CoverFlow.LayoutParams(
						320, 480);
				imageView.setLayoutParams(imgLayout);
				imageView.setPadding(30, 100, 20, 20);
				mImages[index++] = imageView;

			}
			return true;
		}

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

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

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

		@SuppressWarnings("deprecation")
		public View getView(int position, View convertView, ViewGroup parent) {

			// Use this code if you want to load from resources
			ImageView i = new ImageView(mContext);
			i.setImageResource(mImageIds[position]);
			i.setLayoutParams(new CoverFlow.LayoutParams(380, 450));
			i.setScaleType(ImageView.ScaleType.CENTER_INSIDE);

			// Make sure we set anti-aliasing otherwise we get jaggies
			BitmapDrawable drawable = (BitmapDrawable) i.getDrawable();
			drawable.setAntiAlias(true);
			return i;

			// return mImages[position];
		}

		/**
		 * Returns the size (0.0f to 1.0f) of the views depending on the
		 * 'offset' to the center.
		 */
		public float getScale(boolean focused, int offset) {
			/* Formula: 1 / (2 ^ offset) */
			return Math.max(0, 1.0f / (float) Math.pow(2, Math.abs(offset)));
		}

	}
}

OK Done. Now go on and Run your project.

CoverFlow

Download the Complete android source code from here.

Best Buy offering Samsung Galaxy S III for $49 on December 16th

Samsung Galaxy S3

Best Buy has been known to have some pretty good deals, but this one should have any Android fan pretty excited. Tomorrow only, Best Buy will be offering the famed Galaxy S III for only $49.99 with a new or renewed contract. This offer is good for all four major carriers: Verizon, AT&T, Sprint and T-Mobile.

Read More from here

http://www.talkandroid.com/144810-deal-best-buy-offering-samsung-galaxy-s-iii-for-49-on-december-16th/

How to crop an Image in Android?

This is a sample program that launches the camera and crop the captured image.

Check this link to another crop image example.

http://www.coderzheaven.com/2011/03/15/crop-an-image-in-android/

Crop an Image in Android

Crop an Image in Android

Crop an Image in Android

This is the layout xml.
activity_main.xml

<?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="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="3dp"
        android:text="@string/intro"
        android:textStyle="bold" />

    <Button
        android:id="@+id/capture_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/capture" />

    <ImageView
        android:id="@+id/picture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:contentDescription="@string/picture" />

</LinearLayout>

Now this is the Main Java File that implements the crop functionality.

Here we are using the “com.android.camera.action.CROP” Intent to crop the Image passing the captured Image URI to it.

package com.coderzheaven.cropimage;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
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;
import android.widget.Toast;

public class ShootAndCropActivity extends Activity implements OnClickListener {

	final int CAMERA_CAPTURE = 1;
	final int CROP_PIC = 2;
	private Uri picUri;

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

		Button captureBtn = (Button) findViewById(R.id.capture_btn);
		captureBtn.setOnClickListener(this);
	}

	public void onClick(View v) {
		if (v.getId() == R.id.capture_btn) {
			try {
				// use standard intent to capture an image
				Intent captureIntent = new Intent(
						MediaStore.ACTION_IMAGE_CAPTURE);
				// we will handle the returned data in onActivityResult
				startActivityForResult(captureIntent, CAMERA_CAPTURE);
			} catch (ActivityNotFoundException anfe) {
				Toast toast = Toast.makeText(this, "This device doesn't support the crop action!",
						Toast.LENGTH_SHORT);
				toast.show();
			}
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (requestCode == CAMERA_CAPTURE) {
				// get the Uri for the captured image
				picUri = data.getData();
				performCrop();
			}
			// user is returning from cropping the image
			else if (requestCode == CROP_PIC) {
				// get the returned data
				Bundle extras = data.getExtras();
				// get the cropped bitmap
				Bitmap thePic = extras.getParcelable("data");
				ImageView picView = (ImageView) findViewById(R.id.picture);
				picView.setImageBitmap(thePic);
			}
		}
	}

	/**
	 * this function does the crop operation.
	 */
	private void performCrop() {
		// take care of exceptions
		try {
			// call the standard crop action intent (the user device may not
			// support it)
			Intent cropIntent = new Intent("com.android.camera.action.CROP");
			// indicate image type and Uri
			cropIntent.setDataAndType(picUri, "image/*");
			// set crop properties
			cropIntent.putExtra("crop", "true");
			// indicate aspect of desired crop
			cropIntent.putExtra("aspectX", 2);
			cropIntent.putExtra("aspectY", 1);
			// indicate output X and Y
			cropIntent.putExtra("outputX", 256);
			cropIntent.putExtra("outputY", 256);
			// retrieve data on return
			cropIntent.putExtra("return-data", true);
			// start the activity - we handle returning in onActivityResult
			startActivityForResult(cropIntent, CROP_PIC);
		}
		// respond to users whose devices do not support the crop action
		catch (ActivityNotFoundException anfe) {
			Toast toast = Toast
					.makeText(this, "This device doesn't support the crop action!", Toast.LENGTH_SHORT);
			toast.show();
		}
	}
}

Download the complete source code for the above example from here.

How to call a function using a String in Android and also pass parameters along with it.

Hi all …

Today’s post is all about calling functions using Simple Strings.

Here we will do two things.

1. Call a function without parameters.
2. Call a function with parameters.

String to functions

String to functions

This is the class which contains the functions that we are going to call using “simple Strings”.


package com.coderzheaven.Stringtofunction;

public class Test {

	public String functionWithParams(String p1, String p2) {
		return p1 + ", " + p2;
	}

	public String noParamsFunction() {
		return "Return from noParamsFunction";
	}

}

Now this is the main activity that calls these functions.

package com.coderzheaven.Stringtofunction;

import java.lang.reflect.Method;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

	String TAG = getClass().getSimpleName();
	TextView tv;
	
	@SuppressWarnings("rawtypes")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		final Object paramsObj[] = { "Hello", "CoderzHeaven" };
		final Class[] class_params = { String.class, String.class };
		final String class_name = getPackageName() + ".Test";

		Button b1 = (Button) findViewById(R.id.button1);
		b1.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				/** This is the function without parameters in Test.java **/
				callFunctionWithoutParameter(class_name, "noParamsFunction");
			}
		});

		Button b2 = (Button) findViewById(R.id.button2);
		b2.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				/** This is the function with two parameters in Test.java **/
				callFunctionWithParams(class_name, "functionWithParams",
						class_params, paramsObj);
			}
		});
		
		tv = (TextView)findViewById(R.id.tv);

	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	void callFunctionWithoutParameter(String class_name, String function_name) {
		try {
			Class c = Class.forName(class_name);
			Method m = c.getMethod(function_name);
			Object iClass = c.newInstance();
			String p = (String) m.invoke(iClass);
			Log.i(TAG, p);
			tv.setText("Result (Without Prameters) : " + p);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	void callFunctionWithParams(String aClass, String aMethod, Class[] params,
			Object[] args) {
		try {
			Class c = Class.forName(aClass);
			Method m = c.getDeclaredMethod(aMethod, params);
			Object i = c.newInstance();
			String p = (String) m.invoke(i, args);
			Log.i(TAG, p);
			tv.setText("Result (With Prameters) : " + p);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

Now this is the layout that the mainactivity uses.

<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" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Call function without parameters" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Call function with parameters" />

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="@dimen/padding_medium"
        android:text="@string/hello_world"
        tools:context=".MainActivity" />

</LinearLayout>