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.

Image in SQLite DB

First I will just create a Database Helper Class for adding and reading from the Database.
Our Database contains only one table “Images” with two columns “id” and “image”.

Note : If you want to see the SQLite DB Structure and values in Eclipse you can check this post.

We are going to save our selected image in the column “image”.

DBHelper.java

package com.coderzheaven.storeimage;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper {

    public static final String IMAGE_ID = "id";
    public static final String IMAGE = "image";
    private final Context mContext;

    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;

    private static final String DATABASE_NAME = "Images.db";
    private static final int DATABASE_VERSION = 1;

    private static final String IMAGES_TABLE = "ImagesTable";

    private static final String CREATE_IMAGES_TABLE =
            "CREATE TABLE " + IMAGES_TABLE + " (" +
                    IMAGE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                    + IMAGE + " BLOB NOT NULL );";


    private static class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        public void onCreate(SQLiteDatabase db) {
            db.execSQL(CREATE_IMAGES_TABLE);
        }

        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS " + CREATE_IMAGES_TABLE);
            onCreate(db);
        }
    }

    public void Reset() {
        mDbHelper.onUpgrade(this.mDb, 1, 1);
    }

    public DBHelper(Context ctx) {
        mContext = ctx;
        mDbHelper = new DatabaseHelper(mContext);
    }

    public DBHelper open() throws SQLException {
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        mDbHelper.close();
    }

    // Insert the image to the Sqlite DB
    public void insertImage(byte[] imageBytes) {
        ContentValues cv = new ContentValues();
        cv.put(IMAGE, imageBytes);
        mDb.insert(IMAGES_TABLE, null, cv);
    }

    // Get the image from SQLite DB
    // We will just get the last image we just saved for convenience...
    public byte[] retreiveImageFromDB() {
        Cursor cur = mDb.query(true, IMAGES_TABLE, new String[]{IMAGE,},
                               null, null, null, null,
                               IMAGE_ID + " DESC", "1");
        if (cur.moveToFirst()) {
            byte[] blob = cur.getBlob(cur.getColumnIndex(IMAGE));
            cur.close();
            return blob;
        }
        cur.close();
        return null;
    }
}

Now a helper Utility class for image processing..

Utils.java


package com.coderzheaven.storeimage;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class Utils {

    public static byte[] getImageBytes(Bitmap bitmap) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        return stream.toByteArray();
    }

    public static Bitmap getImage(byte[] image) {
        return BitmapFactory.decodeByteArray(image, 0, image.length);
    }

    public static byte[] getBytes(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];

        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            byteBuffer.write(buffer, 0, len);
        }
        return byteBuffer.toByteArray();
    }

}

Layout

Our layout mainly contains a Floating button, for selecting an image and
an ImageView for showing the image Selected and Image from the Database.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/coordinatorLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.coderzheaven.storeimage.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.AppCompatImageView
        android:id="@+id/imgView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="@dimen/activity_horizontal_margin" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/btnSelectImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_menu_gallery" />

</android.support.design.widget.CoordinatorLayout>

MainActivity.java

On Selecting the image, we will insert it into the database, show a message to the user and after 3 seconds, we will read it back from the database.


package com.coderzheaven.storeimage;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;

import java.io.IOException;
import java.io.InputStream;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final int SELECT_PICTURE = 100;
    private static final String TAG = "MainActivity";

    CoordinatorLayout coordinatorLayout;
    FloatingActionButton btnSelectImage;
    AppCompatImageView imgView;

    DBHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        // Find the views...
        coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
        btnSelectImage = (FloatingActionButton) findViewById(R.id.btnSelectImage);
        imgView = (AppCompatImageView) findViewById(R.id.imgView);

        btnSelectImage.setOnClickListener(this);

        // Create the Database helper object
        dbHelper = new DBHelper(this);

    }

    // Show simple message using SnackBar
    void showMessage(String message) {
        Snackbar snackbar = Snackbar.make(coordinatorLayout, message, Snackbar.LENGTH_LONG);
        snackbar.show();
    }

    // Choose an image from Gallery
    void openImageChooser() {
        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();

                if (null != selectedImageUri) {

                    // Saving to Database...
                    if (saveImageInDB(selectedImageUri)) {
                        showMessage("Image Saved in Database...");
                        imgView.setImageURI(selectedImageUri);
                    }

                    // Reading from Database after 3 seconds just to show the message
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (loadImageFromDB()) {
                                showMessage("Image Loaded from Database...");
                            }
                        }
                    }, 3000);
                }

            }
        }
    }

    @Override
    public void onClick(View v) {
        openImageChooser();
    }

    // Save the
    Boolean saveImageInDB(Uri selectedImageUri) {

        try {
            dbHelper.open();
            InputStream iStream = getContentResolver().openInputStream(selectedImageUri);
            byte[] inputData = Utils.getBytes(iStream);
            dbHelper.insertImage(inputData);
            dbHelper.close();
            return true;
        } catch (IOException ioe) {
            Log.e(TAG, "<saveImageInDB> Error : " + ioe.getLocalizedMessage());
            dbHelper.close();
            return false;
        }

    }

    Boolean loadImageFromDB() {
        try {
            dbHelper.open();
            byte[] bytes = dbHelper.retreiveImageFromDB();
            dbHelper.close();
            // Show Image from DB in ImageView
            imgView.setImageBitmap(Utils.getImage(bytes));
            return true;
        } catch (Exception e) {
            Log.e(TAG, "<loadImageFromDB> Error : " + e.getLocalizedMessage());
            dbHelper.close();
            return false;
        }
    }
}

Build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.coderzheaven.storeimage"
        minSdkVersion 21
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.1'
    compile 'com.android.support:design:23.2.1'
}

Done.

You can download the complete Android Studio Source Code from here.

Send your comments to coderzheaven@gmail.com.

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

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>