Monthly Archives: January 2012

Central aligning the default message text in AlertDialog in android.

Hello all..

Today I will show you how to align the message text to center in an AlertDialog.
By default it is left aligned, so we have to get a reference to it to align it to center.
This is how we do it.
Check this code.

package com.coderzheaven.pack;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.TextView;

public class AlertTestDemo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("My Title");
        builder.setMessage("CoderzHeavennHeaven of all working codes.");
        builder.setPositiveButton("OK", null);
        AlertDialog dialog = builder.show();
        TextView messageText = (TextView)dialog.findViewById(android.R.id.message);
        messageText.setGravity(Gravity.CENTER);
    }
}

Please leave your valuable comments on this post.

Saving TextFile to SDCARD in android?

Hello android lovers,

In today’s tutorial I will show you how to

1. Create a text file and save a textfile in your SDCARD in your preferred path.

2. Read the contents from the same file and show it in a TextView.

For writing a file we use the FileWriter class and for reading the textfile we use the FileReader class.
Now Let’s check out how we do this .

First create a fresh project and name it “saveFileDemo”.
In the “saveFileDemo.java” file copy this contents.

package com.coderzheaven.pack;

import java.io.FileReader;
import java.io.FileWriter;

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

public class saveFileDemo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        createFile();
        String file_contents = readFile();
    	System.out.println("FILE CONTENTS :  "  + file_contents);

    	TextView tv = (TextView)findViewById(R.id.tv);
    	tv.setText("Read File contents from SDCARD : n" + file_contents);
    }
    public void createFile(){
    	FileWriter fWriter;
        try{
             fWriter = new FileWriter("/sdcard/myfile.txt");
             fWriter.write("My file contents");
             fWriter.flush();
             fWriter.close();
         }catch(Exception e){
                  e.printStackTrace();
         }
    }
    public String readFile(){
        char buf[] = new char[512];
        FileReader rdr;
        String contents = "";
		try {
			rdr = new FileReader("/sdcard/myfile.txt");
			int s = rdr.read(buf);
			for(int k = 0; k < s; k++){
				contents+=buf[k];
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return contents;
    }
}

This is the main.xml file contents.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
	android:id = "@+id/tv"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
</LinearLayout>

Here is the Strings.xml file contents

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, saveFileDemo!</string>
    <string name="app_name">saveFileDemo from Coderzheaven</string>
</resources>

Now the AndroidManifest.xml file contents.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.coderzheaven.pack"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".saveFileDemo"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>


You can actually see the file by going to the FileExplorer and expanding the mnt folder(or simply SDCARD in older versions) and the SDCARD folder.
See the screenshot.

Check this link to see the contents of this file manually.

Please leave your valuable comments on this post.

How to uninstall apk through command line in android?

Hello all…
You may already know how to uninstall an android apk through interface in android emulator or device.
But there is another way to remove the apk. It is through command line.

here is how you do it.
First navigate to android tools directory from your command line.
Here I have installed android in the “G:SoftwaresANDRIOD” directory.

Now type adb shell.
Next type “ls” to list the file since we know android is linux based.

Check the screenshot for complete guide.

Please leave your comments on this post.

Android removes the need of Menu button from devices with ActionBar.

Hello all..
The latest development in android is that google has removed the menu button from android, instead they provide something called the actionbar like in the Honeycomb devices. Google introduced the ActionBar class as the standard solution to make actions from the user options immediately visible and quick to invoke
The ActionBar looks like this

When invoked with options it will look like this…

Thus ActionBar removes the need of physical menu buttons in android devices.

Scaling the android emulator through command line.

Hello everyone,

Today I will show you a simple trick of scaling the android device through command line.
Ofcourse this can be done using the interface, but the otherway is using the command line.
Through interface is like this .

Scaling enulator

Scaling enulator

Through command line

C:>emulator -avd VD_Maps -scale 0.5

Change the scale value and see how your emulator changes.
please leave your comments if this post was useful.

How to download an image in corona SDK?

Downloading an image in corona is really easy.
Check out the example.


	module(..., package.seeall)

	_W = display.contentWidth;
	_H = display.contentHeight;

	function new()
		local grp = display.newGroup();
		local myImage;

		local function networkListener( event )
			if ( event.isError ) then
					print ( "Network error - download failed" )
			else
					myImage = display.newImage( "helloCopy.png", system.TemporaryDirectory, 60, 40 )
					myImage.alpha = 0
					transition.to( myImage, { alpha = 1.0 } )

			end

			print ( "RESPONSE: " .. event.response )
				grp:insert(myImage)
	end

	network.download( "http://developer.anscamobile.com/demo/hello.png", "GET", networkListener, "helloCopy.png", system.TemporaryDirectory )

	return grp;

	end

Check the console to see where the downloaded file is saved.

Download the complete source code from here.

Gradient Text in Corona

To create gradient text in corona, you have to download ‘Corona daily build 612′ which has functions like setFillColor() etc.
You create a new gradient object by calling graphics.newGradient().
You can pass (and reuse) the object in calls to text:setTextColor() and rect:setFillColor().

Here is an example.

local myText =
    display.newText( "Hello, World!", 0, 0, native.systemFont, 40 )
myText.x = display.contentWidth * 0.5
myText.y = display.contentWidth * 0.25
local g = graphics.newGradient( { 180, 180, 0 }, { 255 }, "down" )
myText:setTextColor( g )

Working with SQLite databases through command Line in android.

Hello all,
In todays tutorial I will show you how to work with sqlite databases in android through command line.

Advantages
1. You can browse any number of databases.
2. You can write any queries and execute.

First go through these tutorials to get a glance of how to work with sqlite databases in android.
1. http://coderzheaven.com/2011/04/sqlitemanager-plugin-for-eclipse/
2. http://coderzheaven.com/2011/04/using-sqlite-in-android-a-really-simple-example/
3. http://coderzheaven.com/2011/02/working-with-sqlite-database-in-android/

After going through these tutorials you will get to know these.
1. How to create an SQLite database.?
2. Where to locate the database file in your device or emulator?
3. How to browse the database using the plugin I provided in this example(http://coderzheaven.com/2011/04/sqlitemanager-plugin-for-eclipse/
)?

I am using the sqlite database that I created using this example
http://coderzheaven.com/2012/01/how-to-save-score-in-android-cocos2d/

Now open the command prompt or terminal and type

adb -s emulator-5554 shell

now type the path of your sqlite database like this.

sqlite3 /data/data/com.coderzheaven.pack/databases/mytest.db

check the screenshot for example

Now look at the screenshot for how am I navigating through the tables and selecting and inserting values to the table creating new tables etc.
Click and enlarge the image to see it.


You can exit the shell by typing ‘ ctrl+d’ twice.

This is the path of my database file
/data/data/com.coderzheaven.pack/databases/mytest.db

Which you can see by opening the file explorer from the window menu and expanding your package folder.(check this example for a screenshot of how to see the database http://coderzheaven.com/2012/01/how-to-save-score-in-android-cocos2d/)

Now about the SQLite database file.
Here I have three tables my_table, temp_table and test_table.
I am executing different commands to manipulate these tables.
The results are appearing just after the command

Please leave your valuable comments on this post.
Also +1 this post to share it to others if you liked it.

How to save data or score in Android Cocos2D?

Hello Friends
Today I will show you how to save data in cocos2D android in a database and reload it when the game starts.
This has been always a problem withe game developers for cocos2D android.
I will show you a way to save almost any number of data in a database using SQlite in android.

Check these examples for how to use SQlite databases in android
1. Working with SQLite Database in ANDROID.
2. Using SQLite in ANDROID, A really simple example.

First thing you need to know is cocos2d.
Downlod a sample project for cocos2D from here and copy the libraries into your project
Assuming all are familiar with Cocos2D. I am starting this tutorial.

Create a fresh project named SaveDataDemo.
then create a class named SQlite.java and copy this code into it.
This file contains the table definition and methods for accessing the data in the table. All you need is call these functions in your main file and insert, update or get the data from the database.

SQlite.java

package com.coderzheaven.pack;

import java.util.Set;
import java.util.Map.Entry;

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;

class MyTable
{
	 private String TABLE_NAME = "my_table";
	 int DATABASE_VERSION = 1;
	 private String _ID = "id";
	 private String _SCORE = "score";

	public String getTableName(){			return TABLE_NAME;}
	public int getDatabaseVersion()	{		return DATABASE_VERSION;}

	public String getID()		{		return _ID;			}
	public String getScore()	{		return _SCORE;		}

	public String getDatabaseCreateQuery()
	{
		final String DATABASE_CREATE =
		    "create table IF NOT EXISTS " + TABLE_NAME + " (" + _ID + " INTEGER PRIMARY KEY, "
		    + _SCORE + " TEXT NOT NULL)";

		return DATABASE_CREATE;

	}
}

class dbOperation
{
		static String DB_TABLE ;
		static int DB_VERSION = GlobalClass.DATABASE_VERSION;
		static String[] DATABASE_CREATE;
	    private Context context;
	    private DatabaseHelper DBHelper;
	    private SQLiteDatabase db;

	    public dbOperation(Context ctx,String[] query)
	    {
	    	this.context = ctx;
 	        DATABASE_CREATE = query;
 	        DBHelper = new DatabaseHelper(context);
	    }
	    public dbOperation(Context ctx)
	    {
	    	this.context = ctx;
	    	DBHelper = new DatabaseHelper(context);
	    }

	    public dbOperation(String tablename)  //for inner calling
	    {
	    	DB_TABLE = tablename;
	    	DBHelper = new DatabaseHelper(context);
	    }

		public dbOperation open() throws SQLException
	    {
	        db = DBHelper.getWritableDatabase();
	        return this;
	    }
	    public void close()
	    {
	        DBHelper.close();
	    }
	    private static class DatabaseHelper extends SQLiteOpenHelper
	    {
	        DatabaseHelper(Context context)
	        {
	            super(context, GlobalClass.DBNAME, null, DB_VERSION);
	        }
	        public void onCreate(SQLiteDatabase db)
	        {
	            try
	            {
	            	for (String s  : DATABASE_CREATE)
	            	{
	            		db.execSQL(s);
					}
				}
	            catch (Exception e) {
					System.out.println("Error creating items Per screen in the constructor" + e.getMessage());
				}
	        }
	        public void onUpgrade(SQLiteDatabase db, int oldVersion,
	        int newVersion)
	        {
	        	db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
	            onCreate(db);
	        }
	    }

	    public long insertTableData(String tablename,ContentValues values)  throws SQLException
	    {
	    	DB_TABLE = tablename;
	    	ContentValues initialValues2 = new ContentValues();
	        Set<Entry<String, Object>> s =  values.valueSet();
	        String new_val = "";
	        for (Entry<String, Object> entry : s) {
	            new_val = values.getAsString(entry.getKey());
	            initialValues2.put(entry.getKey(), new_val);
	        }
	        return db.insert(DB_TABLE, null, initialValues2);
	    }
	    public boolean deleteTableData(String tablename,String condition)  throws SQLException
	    {
	    	DB_TABLE = tablename;
	    	return db.delete(DB_TABLE, condition, null) > 0;
	    }
	    public Cursor getAllTableData(String tablename,String[] fields)  throws SQLException
	    {
	    	DB_TABLE = tablename;
				return db.query(DB_TABLE, fields,null, null, null, null, null);
	    }
	    public Cursor getTableRow(String tablename,String[] dbFields, String condition,String order,String limit) throws SQLException
	    {
	    	DB_TABLE = tablename;
	        Cursor mCursor =    db.query(false, DB_TABLE, dbFields,condition,
	                			null,null,null, order, limit);

	        if (mCursor != null) {
	            mCursor.moveToFirst();
	        }
	        return mCursor;
	    }
	    public boolean updateTable(String tablename,ContentValues args,String condition)
	    {
	    	DB_TABLE = tablename;
	    	return db.update(DB_TABLE, args,condition , null) > 0;

	    }
	    public int lastInsertedID(String tablename)
	    {
	    	int retVar=0;
	    	Cursor mCursor = db.rawQuery("select max(id) from "+tablename, null);

			if (mCursor != null) {
				mCursor.moveToFirst();
				retVar =Integer.parseInt(mCursor.getString(0));
			}
			mCursor.close();
			mCursor.deactivate();
			return retVar ;
	    }
}

Now create a file named “GameLayer.java” file and copy this code into it.
GameLayer.java

package com.coderzheaven.pack;

import org.cocos2d.actions.instant.CCCallFuncN;
import org.cocos2d.actions.interval.CCMoveTo;
import org.cocos2d.actions.interval.CCSequence;
import org.cocos2d.layers.CCColorLayer;
import org.cocos2d.layers.CCScene;
import org.cocos2d.nodes.CCDirector;
import org.cocos2d.nodes.CCLabel;
import org.cocos2d.nodes.CCSprite;
import org.cocos2d.types.CGPoint;
import org.cocos2d.types.CGSize;
import org.cocos2d.types.ccColor3B;
import org.cocos2d.types.ccColor4B;

import android.content.ContentValues;
import android.database.Cursor;
import android.view.MotionEvent;

public class GameLayer extends CCColorLayer
{
	protected CCLabel _label = null;
	CGSize winSize = CCDirector.sharedDirector().displaySize();
	int myscore = 0;

	public static CCScene scene()
	{
		CCScene scene = CCScene.node();
		CCColorLayer layer = new GameLayer(ccColor4B.ccc4(255, 255, 255, 255));
		scene.addChild(layer);
		return scene;
	}

	protected GameLayer(ccColor4B color)
	{
		super(color);
		this.setIsTouchEnabled(true);
		DBOperations();
	}

	public void DBOperations(){
		addAndroid();
		createAndInitializeTables();
		insertData(myscore);
		myscore = getDataFromTable();
		System.out.println("SCORE : " + myscore);
		updateTable(myscore);
		myscore = getDataFromTable();
		System.out.println("SCORE : " + myscore);
		showLabel(myscore);
	}

	public void createAndInitializeTables(){
        try{
        	MyTable mytable = new MyTable();
        	String[] tableCreateArray = {mytable.getDatabaseCreateQuery()};
    		dbOperation operation = new dbOperation(CCDirector.sharedDirector().getActivity(),tableCreateArray);
			operation.open();
			operation.close();
        }catch(Exception e){
           System.out.println("Error creating table " + e.getMessage());
        }
        System.out.println("Table successfully created!!");
	}
	public int getDataFromTable(){
		dbOperation operationObj = new dbOperation(CCDirector.sharedDirector().getActivity());
        operationObj.open();
		MyTable mytable = new MyTable();
		int score = 0;
		String  condition2 = mytable.getID() +" = 1 ";
        String[] dbFields4 = {mytable.getScore()};
        Cursor cursor =  operationObj.getTableRow(mytable.getTableName(),dbFields4,condition2,mytable.getID() + " ASC ",1 +"");
        if(cursor.getCount()>0)
        {
        	 cursor.moveToFirst();
        	 do{
        		 score = cursor.getInt(0);
        	 }while(cursor.moveToNext());
        }
        cursor.close();
		cursor.deactivate();
		operationObj.close();

		return score;
	}
	public void insertData(int score){
		MyTable mytable = new MyTable();
		dbOperation operationObj = new dbOperation(CCDirector.sharedDirector().getActivity());
        operationObj.open();
		ContentValues initialValues = new ContentValues();
    	initialValues.put(mytable.getScore(),score+"");
        operationObj.insertTableData(mytable.getTableName(),initialValues);
        int maxID = operationObj.lastInsertedID(mytable.getTableName());
        System.out.println("LAST INSERTED ID : " + maxID);
        operationObj.close();
	}
	public void updateTable(int scr){
		MyTable mytable = new MyTable();
		dbOperation operationObj = new dbOperation(CCDirector.sharedDirector().getActivity());
        operationObj.open();
        String condition = mytable.getID() + " = 1";
		ContentValues initialValues = new ContentValues();
    	initialValues.put(mytable.getScore(),scr+"");
        operationObj.updateTable(mytable.getTableName(),initialValues,condition);
        operationObj.close();
	}
	public void showLabel(int scr){

		if(_label != null){
			this.removeChild(_label,true);
		}
		_label = CCLabel.makeLabel("Score : " + scr, "Verdana", 20);
		_label.setColor(ccColor3B.ccBLACK);
		_label.setPosition(5 5f, winSize.height - 15);
		addChild(_label);
	}
	public void addAndroid(){
		CGSize winSize = CCDirector.sharedDirector().displaySize();
		CCSprite player = CCSprite.sprite("android.png");
		player.setPosition(CGPoint.ccp(player.getContentSize().width / 2.0f, winSize.height / 2.0f));
		addChild(player);

		CCMoveTo actionMove = CCMoveTo.action(3, CGPoint.ccp(winSize.getWidth(), winSize.getHeight()/2.0f));
		CCCallFuncN actionMoveDone = CCCallFuncN.action(this, "spriteMoveFinished");
		CCSequence actions = CCSequence.actions(actionMove, actionMoveDone);

		player.runAction(actions);
	}

	public void spriteMoveFinished(Object sender)
	{
		CCSprite sprite = (CCSprite)sender;
		this.removeChild(sprite, true);
		myscore++;
		updateTable(myscore);
		showLabel(myscore);
		addAndroid();
	}
	@Override
	public boolean ccTouchesBegan(MotionEvent event)
	{
		return true;
	}
}

Note : copy a file named “android.png” into the assets folder.

Now create a file named “GlobalClass.java” and copy this code into it.
GlobalClass.java

package com.coderzheaven.pack;

public class GlobalClass
{
	  public static String DBNAME = "mytest.db";
	  public static final int DATABASE_VERSION = 1;
}

Now this is the main file that calls this gamelayer which is named “SaveDataDemo.java”

package com.coderzheaven.pack;

import org.cocos2d.layers.CCScene;
import org.cocos2d.nodes.CCDirector;
import org.cocos2d.opengl.CCGLSurfaceView;

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

public class SaveDataDemo extends Activity
{
	protected CCGLSurfaceView _glSurfaceView;

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

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

		_glSurfaceView = new CCGLSurfaceView(this);
		setContentView(_glSurfaceView);
	}

	@Override
	public void onStart()
	{
		super.onStart();
		CCDirector.sharedDirector().attachInView(_glSurfaceView);
		CCDirector.sharedDirector().setDeviceOrientation(CCDirector.kCCDeviceOrientationLandscapeLeft);
		CCDirector.sharedDirector().setDisplayFPS(true);
		CCDirector.sharedDirector().setAnimationInterval(1.0f / 60.0f);
		CCScene scene = GameLayer.scene();
		CCDirector.sharedDirector().runWithScene(scene);
	}

	@Override
	public void onPause()
	{
		super.onPause();
		CCDirector.sharedDirector().pause();
	}

	@Override
	public void onResume()
	{
		super.onResume();
		CCDirector.sharedDirector().resume();
	}

	@Override
	public void onStop()
	{
		super.onStop();
		CCDirector.sharedDirector().end();
	}
}

Inside the GameLayer class check these functions that loads the data from the database or insert or update the database.

public void DBOperations(){
		addAndroid();
		createAndInitializeTables();
		insertData(myscore);
		myscore = getDataFromTable();
		System.out.println("SCORE : " + myscore);
		updateTable(myscore);
		myscore = getDataFromTable();
		System.out.println("SCORE : " + myscore);
		showLabel(myscore);
	}

Here are the screenshots.





Download the complete source code from here.

If you find this post useful please leave your valuable comments and +1 this post to share more and give me encouragement for future posts.

Join the Forum discussion on this post

Problem with touch in Corona on multiple views solved.

Hello everyone..
There has been a problem with corona that when you place one view over the other and when you touch the object in front of the other, touch will be migrated to the object below it. To prevent this there is a mechanism in corona.
Here is how we solve this in corona.

display.getCurrentStage():setFocus( your_touched_obj)

here is a sample code.


local img1 = display.newImage("android_1.png")
local img2 = display.newImage("android_2.png")

function touchedImageOne()
	print ("touched Image One")
end

function touchedImageTwo()
	print ("touched Image two")
end

display.getCurrentStage():setFocus( img2 )
img1:addEventListener("tap",touchedImageOne);
img2:addEventListener("tap",touchedImageTwo);

Check the console for the output
Here is a source code example for this project.

Controlling android emulator with keypad.

Emulator Keyboard Mapping

The table below summarizes the mappings between the emulator keys and and the keys of your keyboard.

Emulated Device Key Keyboard Key
Home HOME
Menu (left softkey) F2 or Page-up button
Star (right softkey) Shift-F2 or Page Down
Back ESC
Call/dial button F3
Hangup/end call button F4
Search F5
Power button F7
Audio volume up button KEYPAD_PLUS, Ctrl-5
Audio volume down button KEYPAD_MINUS, Ctrl-F6
Camera button Ctrl-KEYPAD_5, Ctrl-F3
Switch to previous layout orientation (for example, portrait, landscape) KEYPAD_7, Ctrl-F11
Switch to next layout orientation (for example, portrait, landscape) KEYPAD_9, Ctrl-F12
Toggle cell networking on/off F8
Toggle code profiling F9 (only with -trace startup option)
Toggle fullscreen mode Alt-Enter
Toggle trackball mode F6
Enter trackball mode temporarily (while key is pressed) Delete
DPad left/up/right/down KEYPAD_4/8/6/2
DPad center click KEYPAD_5
Onion alpha increase/decrease KEYPAD_MULTIPLY(*) / KEYPAD_DIVIDE(/)

How to encrypt a string in Android Using Base64?

package com.coderzheaven.encryptstring;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Base64;

@SuppressLint({ "WorldReadableFiles", "WorldWriteableFiles" })
public class MainActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		saveText("CoderzHeaven");
		System.out.println(getText());
	}

	public void saveText(String text) {
		SharedPreferences myPrefs = this.getSharedPreferences("myPrefs",
				MODE_WORLD_READABLE);
		SharedPreferences.Editor editor = myPrefs.edit();
		text = Base64.encodeToString(text.getBytes(), Base64.DEFAULT);
		editor.putString("some_text", text);
		editor.commit();
	}

	public String getText() {
		SharedPreferences myPrefs = this.getSharedPreferences("myPrefs",
				MODE_WORLD_WRITEABLE);
		String text = myPrefs.getString("some_text", null);
		text = new String(Base64.decode(text, Base64.DEFAULT));
		return text;
	}
}

Please check the LogCat for output.

Join the Forum discussion on this post

Single Selection ListView in android

Hello all…..

In today’s post I will show you how to create a single selection list in android.

Here is the main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
     <ListView
		 	android:id="@android:id/list"
			android:cacheColorHint="#00000000"
			android:scrollbars="none"
			android:fadingEdge="vertical"
			android:soundEffectsEnabled="true"
			android:dividerHeight="1px"
			android:padding="5dip"
			android:smoothScrollbar="true"
		    android:layout_width="fill_parent"
		    android:layout_height="wrap_content"
		    android:drawSelectorOnTop="false"
		    android:layout_marginLeft="10dip"
		    android:layout_marginRight="10dip"
		    android:layout_marginBottom="10dip"
		    android:layout_weight="1"/>

</LinearLayout>

Now this line in the java file creates the single choice.

setListAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_single_choice,
android.R.id.text1, names));

Now this is the full java code

package com.coderzheaven.pack;

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

public class ListView1 extends ListActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        String[] names = new String[] { "Android", "Windows7", "Symbian", "iPhone",
        		"Android", "Windows7", "Symbian", "iPhone",
        		"Android", "Windows7", "Symbian", "iPhone" };
		setListAdapter(new ArrayAdapter<String>(this,
					   android.R.layout.simple_list_item_single_choice,
					   android.R.id.text1, names));
		ListView listView = getListView();
		listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

    }
}

Single Choice ListView

Single Selection ListView in android

How to create Image Reflection in Android?

Reflection in Android

This simple Activity creates a reflection of the provided image.

package com.coderzheaven.imagereflection;

import android.app.Activity;
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.os.Bundle;
import android.view.Menu;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;

public class ImageReflection extends Activity {

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

		Bitmap originalImage = BitmapFactory.decodeResource(getResources(),
				R.drawable.coderzheaven_logo);

		// Create an Image view and add our bitmap with reflection to it
		ImageView imageView = new ImageView(this);
		imageView.setImageBitmap(getRefelection(originalImage));

		// Add the image to a linear layout and display it
		LinearLayout linLayout = new LinearLayout(this);
		linLayout.addView(imageView, new LinearLayout.LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

                linLayout.setBackgroundColor(Color.BLACK);
		// set LinearLayout as ContentView
		setContentView(linLayout);
	}


	public Bitmap getRefelection(Bitmap image) {
		// The gap we want between the reflection and the original image
		final int reflectionGap = 4;

		// Get you bit map from drawable folder
		Bitmap originalImage = image;

		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 matix 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 the reflection Image
		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);
		return bitmapWithReflection;
	}

}

Download the complete source code for above example from here.

How to check whether a video has completed playing in android?

Hello all…

Today I will show you how to get notified when a video completes playing in android.
PLease check this post for playing a video and the resources.
First create a folder named “raw” inside the “res” folder and copy a video inside it.
Now copy the xml from this link.

For listening to the video completion add a setOnCompletionListener to the VideoView Object.
Here is hoe we do this.

package com.coderzheaven.pack;

import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;

public class VideoViewDemo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	           setContentView(R.layout.main);
    	           showVideo();
    	       }
    	    private void showVideo()
    	    {
    	        VideoView vd = (VideoView)findViewById(R.id.videoview);
    	        Uri uri = Uri.parse("android.resource://"+ getApplication().getPackageName() +"/"+R.raw.asal);
    	        MediaController mc = new MediaController(this);
    	        vd.setMediaController(mc);
    	        vd.setVideoURI(uri);
    	        vd.start();
    	        vd.setOnCompletionListener(new OnCompletionListener() {
					@Override
					public void onCompletion(MediaPlayer mp) {
						Toast.makeText(getApplicationContext(), "Video completed", Toast.LENGTH_LONG).show();
					}
				});
    	    }
}

Starting PhoneGap for ANDROID.

Hello everyone….
In today’s tutorial I will show how to start with a HelloWorld Application in PhoneGap for ANDROID.

So what is PhoneGap

PhoneGap is an HTML5 app platform that allows you to author native applications with web technologies and get access to APIs and app stores.

Follow these steps exactly to build the helloworld application.
1.If you don’t have eclipse then download Eclipse Classic from http://www.eclipse.org
For installing eclipse you need to install java.

After installing eclipse run it and set the android directory (If you are not familiar with android please check how to install Android using eclipse)

2.Now download the PhoneGap latest SDK from http://phonegap.com/

3.Open eclipse and create a new project named “phoneGapDemo” as shown in the screenshot below.

4.Now create a folder named “www” inside “assets” as shown in the screenshot

5.Now create a file named “index.html” inside “www” folder and copy this code into it.

<!DOCTYPE HTML>
<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
<script type="text/javascript" charset="utf-8" src="phonegap.js"></script>
</head>
<body>
<h1>Hello World, PhoneGapDemo from CoderzHeaven</h1>
</body>
</html>

6.Copy the “phonegap-1.3.0.js” file inside the “www” folder as shown in the screenshot.

7. Create a folder named “libs” inside the project root folder and copy the “phonegap-1.3.0.jar” inside this directory from the zip you downloaded from the above.
Now add this jar to the build path.
Right Click on the project folder and click “Build Path” and add jars and locate the jar inside your project and click ok.

8. Now create a folder named “xml” inside res directory and create two xml inside it.

phonegap.xml

<?xml version="1.0" encoding="utf-8"?>
<phonegap>
    <access origin="http://127.0.0.1*"/>
    <log level="DEBUG"/>
</phonegap>

plugins.xml

<?xml version="1.0" encoding="utf-8"?>
<plugins>
    <plugin name="App" value="com.phonegap.App"/>
    <plugin name="Geolocation" value="com.phonegap.GeoBroker"/>
    <plugin name="Device" value="com.phonegap.Device"/>
    <plugin name="Accelerometer" value="com.phonegap.AccelListener"/>
    <plugin name="Compass" value="com.phonegap.CompassListener"/>
    <plugin name="Media" value="com.phonegap.AudioHandler"/>
    <plugin name="Camera" value="com.phonegap.CameraLauncher"/>
    <plugin name="Contacts" value="com.phonegap.ContactManager"/>
    <plugin name="Crypto" value="com.phonegap.CryptoHandler"/>
    <plugin name="File" value="com.phonegap.FileUtils"/>
    <plugin name="Network Status" value="com.phonegap.NetworkManager"/>
    <plugin name="Notification" value="com.phonegap.Notification"/>
    <plugin name="Storage" value="com.phonegap.Storage"/>
    <plugin name="Temperature" value="com.phonegap.TempListener"/>
    <plugin name="FileTransfer" value="com.phonegap.FileTransfer"/>
    <plugin name="Capture" value="com.phonegap.Capture"/>
</plugins>

9. Now in the java file copy this code

package com.coderzheaven.pack;

import android.os.Bundle;

import com.phonegap.DroidGap;

public class phoneGapDemo extends DroidGap {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.loadUrl("file:///android_asset/www/index.html");
    }
}

Now go on and run it. You just created a helloworld application with HTML for android using PhoneGap.

Using WebView to call a function in android java code or How to use a WebViewClient in android?

Hello everyone

Today I will explain how will you call a function that is defined inside the java android code from a webview.
For this we need to add a webviewclient in android for the WebView we are adding in the xml.

Then we have to register the webviewclient with the WebView we are creating using this method.

 myWebView.setWebViewClient(new MyWebViewClient());

Now we will start….

Create a new project and name it WebViewDemo.

Now in the main.xml copy this code.
This file contains the webview only.

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

Now create a file named test.html inside the assets folder and copy this code into it. This is the html file that we are loading into the webview.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN"
    "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">
<html>
<body>
<a href="http://www.coderzheaven.com">CoderzHeaven</a>
<input type="button" value="Click Me" onClick="showAndroidToast('Hello CoderzHeaven!')" />
<script type="text/javascript">
    function showAndroidToast(toast) {
    	Android.showToast(toast);
    }
</script>
</body>
</html>

Now in the java code refer the webview and load the html file

WebView myWebView;
 myWebView = (WebView) findViewById(R.id.webview);
 myWebView.loadUrl("file:///android_asset/test.html");

Now enable the javascript by calling this function

 WebSettings webSettings = myWebView.getSettings();
 webSettings.setJavaScriptEnabled(true);

Now we have to add the javascript interface for listening to the javascript functions that we define in the webview html file.

  myWebView.addJavascriptInterface(new JavaScriptInterface(this), "Android");

// outside oncreate
 public class JavaScriptInterface {
        Context mContext;

        /** Instantiate the interface and set the context */
        JavaScriptInterface(Context c) {
            mContext = c;
        }

        /** Show a toast from the web page */
        public void showToast(String toast) {
            Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
            startActivity(new Intent(WebViewDemo.this, WebViewDemo.class));
        }
    }

Now create a webview client for listening to the browser activities and doing specific function.

 myWebView.setWebViewClient(new MyWebViewClient());

 private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (Uri.parse(url).getHost().equals("www.coderzheaven.com")) {
               	Toast.makeText(getApplicationContext(), "www.coderzheaven.com", Toast.LENGTH_SHORT).show();
                return false;
            }
            // Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
            return true;
        }
    }

Now we listen to the backbutton.

 @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // Check if the key event was the BACK key and if there's history
        if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
            myWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

Now the project is over . Now run and see the result.
Here is the full java code for this example

package com.coderzheaven.pack;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class WebViewDemo extends Activity {

	WebView myWebView;
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        myWebView = (WebView) findViewById(R.id.webview);
        myWebView.loadUrl("file:///android_asset/test.html");
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        myWebView.addJavascriptInterface(new JavaScriptInterface(this), "Android");

       // myWebView.setWebViewClient(new WebViewClient());
        myWebView.setWebViewClient(new MyWebViewClient());
    }

    public class JavaScriptInterface {
        Context mContext;

        /** Instantiate the interface and set the context */
        JavaScriptInterface(Context c) {
            mContext = c;
        }

        /** Show a toast from the web page */
        public void showToast(String toast) {
            Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
            startActivity(new Intent(WebViewDemo.this, WebViewDemo.class));
        }
    }

    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (Uri.parse(url).getHost().equals("www.google.com")) {
                // This is my web site, so do not override; let my WebView load the page
            	Toast.makeText(getApplicationContext(), "www.google.com", Toast.LENGTH_SHORT).show();
                return false;
            }
            // Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
            return true;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // Check if the key event was the BACK key and if there's history
        if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
            myWebView.goBack();
            return true;
        }
        // If it wasn't the BACK key or there's no web page history, bubble up to the default
        // system behavior (probably exit the activity)
        return super.onKeyDown(keyCode, event);
    }
}
Calling an android function from javascript

Calling an android function from javascript

please leave your valuable comments if this post was useful.