Monthly Archives: March 2012

Trim a string in Javascript.

Below is a simple function to implement this.

function trim(str)
{
        if(!str || typeof str != 'string')
        {
            return null;
        }
        return str.replace(/^[s]+/,'').replace(/[s]+$/,'').replace(/[s]{2,}/,' ');
}

Uploading audio, video or image files from Android to server

Hello everyone,

Check out the popular posts from Coderzheaven.com

Uploading and Downloading of files – Popular and Useful posts from CoderzHeaven

In one of the previous posts I have shown one method to upload an image in android.
Here is another method to upload a media file like images,audio or video in android.
Here is the main java file that does the upload.
Here I am trying to open audio from the gallery. However you can change it to image or video according to your need.
The code for upload will not change since we change only the code for opening the gallery. We use only the path of the selected file whether it is image or video or audio to upload.

These are for downloading files from the server.

1. How to Download an image in ANDROID programatically?
2. How to download a file to your android device from a remote server with a custom progressbar showing progress?

package pack.coderzheaven;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

public class UploadAudioDemo extends Activity {

	private static final int SELECT_AUDIO = 2;
	String selectedPath = "";

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

        openGalleryAudio();
    }

    public void openGalleryAudio(){

   	Intent intent = new Intent();
        intent.setType("audio/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent,"Select Audio "), SELECT_AUDIO);
   }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {

	    if (resultCode == RESULT_OK) {

	        if (requestCode == SELECT_AUDIO)
	        {
	        	System.out.println("SELECT_AUDIO");
	            Uri selectedImageUri = data.getData();
	            selectedPath = getPath(selectedImageUri);
	         	System.out.println("SELECT_AUDIO Path : " + selectedPath);
	         	doFileUpload();
	        }

	    }
	}

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

    private void doFileUpload(){
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        DataInputStream inStream = null;
        String lineEnd = "rn";
        String twoHyphens = "--";
        String boundary =  "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1*1024*1024;
        String responseFromServer = "";
        String urlString = "http://your_website.com/upload_audio_test/upload_audio.php";
        try
        {
         //------------------ CLIENT REQUEST
        FileInputStream fileInputStream = new FileInputStream(new File(selectedPath) );
         // open a URL connection to the Servlet
         URL url = new URL(urlString);
         // Open a HTTP connection to the URL
         conn = (HttpURLConnection) url.openConnection();
         // Allow Inputs
         conn.setDoInput(true);
         // Allow Outputs
         conn.setDoOutput(true);
         // Don't use a cached copy.
         conn.setUseCaches(false);
         // Use a post method.
         conn.setRequestMethod("POST");
         conn.setRequestProperty("Connection", "Keep-Alive");
         conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
         dos = new DataOutputStream( conn.getOutputStream() );
         dos.writeBytes(twoHyphens + boundary + lineEnd);
         dos.writeBytes("Content-Disposition: form-data; name="uploadedfile";filename="" + selectedPath + """ + lineEnd);
         dos.writeBytes(lineEnd);
         // create a buffer of maximum size
         bytesAvailable = fileInputStream.available();
         bufferSize = Math.min(bytesAvailable, maxBufferSize);
         buffer = new byte[bufferSize];
         // read file and write it into form...
         bytesRead = fileInputStream.read(buffer, 0, bufferSize);
         while (bytesRead > 0)
         {
          dos.write(buffer, 0, bufferSize);
          bytesAvailable = fileInputStream.available();
          bufferSize = Math.min(bytesAvailable, maxBufferSize);
          bytesRead = fileInputStream.read(buffer, 0, bufferSize);
         }
         // send multipart form data necesssary after file data...
         dos.writeBytes(lineEnd);
         dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
         // close streams
         Log.e("Debug","File is written");
         fileInputStream.close();
         dos.flush();
         dos.close();
        }
        catch (MalformedURLException ex)
        {
             Log.e("Debug", "error: " + ex.getMessage(), ex);
        }
        catch (IOException ioe)
        {
             Log.e("Debug", "error: " + ioe.getMessage(), ioe);
        }
        //------------------ read the SERVER RESPONSE
        try {
              inStream = new DataInputStream ( conn.getInputStream() );
              String str;

              while (( str = inStream.readLine()) != null)
              {
                   Log.e("Debug","Server Response "+str);
              }
              inStream.close();

        }
        catch (IOException ioex){
             Log.e("Debug", "error: " + ioex.getMessage(), ioex);
        }
      }
}

Now the server side , the code is written in Php.

<?php
// Where the file is going to be placed
$target_path = "uploads/";

/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['uploadedfile']['name']).
    " has been uploaded";
} else{
    echo "There was an error uploading the file, please try again!";
    echo "filename: " .  basename( $_FILES['uploadedfile']['name']);
    echo "target_path: " .$target_path;
}
?>

Things to keep in mind
1. Make sure your server is running.
2. Your server file path should be right.
3. Check your folder write permission in the server.

Please leave your valuable comments.
Enjoy.

Adding Links in Menu in Adobe AIR/ FLEX.

Hi all…

In this tutorial I will show you how to add links in a menu in Adobe AIR/ FLEX.
It is really simple. Just add a normal menu item and on the click handler for menu items match the label and navigate to the URL, that’s all.
Check out this example.
Change the mx:Application to mx:windowedApplication to work this example as AIR application.



	
		
					
						
						
					
					
						
					
				;

			// create menu items
			private function init():void {
				menuCollection = new XMLListCollection(menubarXML);
			}

			// click handler for menubar
			private function menuHandler(event:MenuEvent):void
			 {
				if(event.item.@label=="Google.com")
				{
					var url:URLRequest = new URLRequest('http://www.google.com');
					navigateToURL(url,'_parent');
				}
				else if(event.item.@label=="Yahoo.com")
				{
					url = new URLRequest('http://www.yahoo.com');
					navigateToURL(url,'_parent');
				}
			}
		]]>
	
	
	
	

Link in menu example in Adobe AIR

Passing data between Intents or classes in ANDROID?

Many of our application reqiures sending data from one intent to another.
This is done by putting data into one intent using putExtras() and getting it in the other intent using the getExtras() which matches the string value. However you can pass string, boolean, integer etc between intents.
For passing data between intents you need atleast two intents.
Here the two activities are named DataBetweenIntentsExample and Result
Make sure to add the two activities in your manifest file, otherwise your application will force close.
Here is an example showing how to pass data between intents in ANDROID.
First we create the layout.
Here I am crearting a simple layout with only one button and a textBox in it.
The main.xml file looks like this.

<?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:text="Site Name : "
	android:id="@+id/TV1"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content">
</TextView>

<EditText
	android:text=""
	android:id="@+id/site_name"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content">
</EditText>

<Button
	android:text=" Send Data "
	android:id="@+id/B1"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content">
</Button>

</LinearLayout>

Then you create a java file named Result.xml and place it inside the current package.
Then create a layout for the Result.xml file and name it result.xml and place it in the layout directory.

The result.xml file will look like this

<?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:text=""
	android:id="@+id/result_tv"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content">
</TextView>

</LinearLayout>

Then we go to the main java file DataBetweenIntentsExample.java and copy this code into it.

package pack.DataBetweenIntents;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class DataBetweenIntentsExample extends Activity {

	public Button B1;
	public EditText T1;
	public Intent intent;

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

        B1 = (Button)findViewById(R.id.B1);
        T1 = (EditText)findViewById(R.id.site_name);

        intent = new Intent();
		intent.setClass(this,Result.class);

        B1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				intent.putExtra("site_name",T1.getText().toString());
				startActivity(intent);

			}
		});
    }
}

Now copy the following code to Result.java file.

package pack.DataBetweenIntents;

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

public class Result extends Activity {

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

	        TV = (TextView)findViewById(R.id.result_tv);
	        Bundle bundle = getIntent().getExtras();

	        if(bundle.getString("cancel") != null){
	        	TV.setText("Cancelled");
	        }else{
	        	String txt1 = bundle.getString("site_name");
	        	TV.setText("Data send from previous intent nSite Name = " + txt1 );
	        }
	    }
}

Androidmanifest.xml file.

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

        <activity android:name=".Result"
         		  android:label="Results"
        />
</manifest>

Listening to keyBoard in Adobe AIR/FLEX….

Hi all….

We all need to know which key is pressed in an application up on which we may need to take an action. For example if the user presses “Ctrl + s” we know he want to save. So for that we need to listen to keyBoard events. For this we use the keyBoard event Listener. First we register our application with the KeyBoard eventListener. After that we will implement the callback function associated with the event. Here the callback function is named “keyListener”. See how it works.
Copy and paste to your MXML file and view the console for the output after pressing any key in the keyboard.




    
        

Please leave your valuable comments if this post was useful…..

How to invoke a phone call in ANDROID?

The following code helps you to invoke a phone call in ANDROID without any user interaction.
This code uses intent to start the activity.
You know that intent can be used to start another acitivty from with in an application.

Dialing a number is done using this code…

Uri telephoneUri = Uri.parse("tel:100000");
my_intent = new Intent(Intent.ACTION_DIAL, telephoneUri);

and Calling number using

Uri calling = Uri.parse("tel:100000");
the_call = new Intent(Intent.ACTION_CALL, calling);

Custom Indeterminate progressBar for android?

Hello everyone…

Today we will see how to customize an indeterminate progressBar in android.
For that we have to create an xml with a progress animation.For this I used these three images





Inside the folder res/drawable create an xml named “progress_indeterminate_horizontal.xml” and copy this code into it

<?xml version="1.0" encoding="utf-8"?>
<animation-list
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:oneshot="false">
    <item android:drawable="@drawable/p1" android:duration="200" />
    <item android:drawable="@drawable/p2" android:duration="200" />
    <item android:drawable="@drawable/p3" android:duration="200" />
</animation-list>

Now the layout file containing the progressBar.I named it 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"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />

    <ProgressBar
    	android:id="@+id/progress_bar"
         android:layout_width="fill_parent"
         android:layout_height="20dip"
         android:indeterminateDrawable="@drawable/progress_indeterminate_horizontal"
     />
 </LinearLayout>

See the line

android:indeterminateDrawable=”@drawable/progress_indeterminate_horizontal”

where I have added the xml as drawable.

Done. Now goon and run the project. Nothing needs to be done in the java code. Enjoy.

Custom Indeterminate progressBar

Please leave your valuable comments if you find this post useful.

Here is another one for creating custom progressbars.

How to build a custom progressBar in android- Part 2?

Custom Title Bar in ANDROID

Hi all….

Today in this post I will show you how to give a custom layout for the titleBar in ANDROID.
You can place almost anything inside a title using your custom layout.

Now go on and create a fresh project and copy this code into the main java file

package pack.coderzheaven;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.widget.ProgressBar;
import android.widget.TextView;

public class CustomTitleDemo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Boolean customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.main);

        if (customTitleSupported) {
            getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.custom_title);
            TextView tv = (TextView) findViewById(R.id.tv);
            tv.setText("CoderzHeaven");

            ProgressBar titleProgressBar = (ProgressBar) findViewById(R.id.PB);
            //titleProgressBar.setVisibility(ProgressBar.GONE);
        }
    }
}

Now create a new xml file and name it custom_title.xml and copy the following code to it.

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

        <ImageView android:layout_width="40dip"
				android:id="@+id/ImageView01"
				android:background="@drawable/android_2"
				android:layout_height="40dip"
				>
		</ImageView>

        <TextView android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/tv"
                android:text="CoderzHeaven"
                android:layout_toRightOf="@+id/ImageView01"
                android:textColor="@drawable/red"
                android:textStyle="bold"
                android:layout_marginLeft="5dip"
                android:layout_marginRight="5dip">
        </TextView>

		 <ProgressBar android:id="@+id/PB"
                style="?android:attr/progressBarStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_toRightOf="@+id/tv"
                android:paddingLeft="3dip">
         </ProgressBar>
</RelativeLayout>

Note: remember to have images mentioned here in the drawable folder.

Now the strings.xml file where the color is defined.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, Custom Title Bar from CoderzHeaven</string>
    <drawable name="white">#ffffff</drawable>
    <drawable name="black">#000000</drawable>
	<drawable name="blue">#2554C7</drawable>
	<drawable name="green">#347C2C</drawable>
	<drawable name="orange">#ff9900</drawable>
	<drawable name="pink">#FF00FF</drawable>
	<drawable name="violet">#a020f0</drawable>
	<drawable name="grey">#778899</drawable>
	<drawable name="red">#C11B17</drawable>
	<drawable name="yellow">#FFFF8C</drawable>
	<drawable name="PowderBlue">#b0e0e6</drawable>
	<drawable name="brown">#2F1700</drawable>
	<drawable name="Hotpink">#7D2252</drawable>
</resources>

Atlast the AndroidManifest.xml file.

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

Custom TitleBar in ANDROID

Please leave your valuable comments if you found this post useful………

How to set a Bitmap Image as Source of an image in Windows Phone 7?

This is a sample code snippet that adds a Bitmap as Source of an image in windows phone 7.

            Uri uri = new Uri("Background.png", UriKind.Relative);
            StreamResourceInfo resourceInfo = Application.GetResourceStream(uri);
            BitmapImage bmp = new BitmapImage();
            bmp.SetSource(resourceInfo.Stream);
            image1.Source = bmp;

Assuming you have placed an image in the UI and named it image1.

How to check whether an application is installed in your ANDROID Phone?

This sample code comes handy when you have to check that an application is already installed in your ANDROID Phone.
Call the below function appInstalledOrNot() with the package name of the app installed on the ANDROID Device as a string parameter.

This function returns true if the app is installed otherwise returns false.

import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Bundle;

public class Example extends Activity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
    	super.onCreate(savedInstanceState);
    	setContentView(R.layout.main);
    	//Put the package name here...
    	boolean installed  =   appInstalledOrNot("com.Ch.Example.pack");
    	if(installed)
    	{
    	          System.out.println("App already installed om your phone");
    	}
    	else
    	{
    		System.out.println("App is not installed om your phone");
    	}
    }
    private boolean appInstalledOrNot(String uri)
    {
        PackageManager pm = getPackageManager();
        boolean app_installed = false;
        try
        {
               pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
               app_installed = true;
        }
        catch (PackageManager.NameNotFoundException e)
        {
               app_installed = false;
        }
        return app_installed ;
}
}

Hi,

Use the following simple lines of code to check whether a particular file exists or not using C#/C Sharp.

using System;
using System.IO;

static class MainClass
{
    static void Main(string[] args)
    {
           Console.WriteLine(File.Exists(&quot;c:yourFile.txt&quot;));
    }
}

It will return either True or False depending on whether your file exists or not.

:)

How to add click handler to a button dynamically in Windows Phone?

Hello everyone….

This post is a simple example showing how to add eventHandlers to a button dynamically in windows phone or windows mobile.
We know programming for windows phone is done in C# or Visual Basic. Here I am going to explain in C#.

I assume that you have dragged a button control in your interface.
Then in the code do this

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

namespace Dynamic_Events
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            addEventHandler();
        }

        void addEventHandler()
        {
            button1.Click += new RoutedEventHandler(button1_Click);
        }

        void button1_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Button Clicked");
        }
    }
}

This is the line that adds the dynamic click handler to the button named “button1″.

button1.Click += new RoutedEventHandler(button1_Click);

Just type button1.Click” and hit two tabs and Visual Studio does the rest for you.

Leave your comments if you like this post.

Starting with NDK for Android – A Simple example. OR How to run a C code in android?

Hello Friends….

Today I am going to talk about how to use ndk in android to run c code.

Note : These steps are for Mac and Linux Users not for Windows users.

Follow these step exactly to set up and run ndk in android.

1. I think that you are having your eclipse and android uptodate.
2. Go to this place “http://developer.android.com/sdk/ndk/index.html” and download the ndk for your operating system.


3. After downloading the zip, extract it and save it in your own location.

4. Now we are going to create the android Project.
I am naming it “NDKDemo” and the activity is named “NDKDemoActivity”.

Now create a folder named “jni” in the project.

5. Click on jni folder-> then go to “Run Menu” > external tools > external tools configuration.

6. Click on Program and click on the new icon (first icon) on the top. On the right side Give the NDK a name.

In the Next Location textbox Click on “Browse File System” and located the ndk-build that you just downloaded from “developer.android.com

7. Now in the Workspace location > Click on Browse Workspace and select your “jni” folder in the “NDKDemo” project directory.

This dialog comes when you click the Browse Workspace button and select the jni folder in your project and click OK.

8. Now create a file named “Android.mk” file inside the “jni” folder.

copy this code to “Android.mk” file.

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_LDLIBS := -llog

LOCAL_MODULE    := ndkdemo
LOCAL_SRC_FILES := native.c

include $(BUILD_SHARED_LIBRARY)

9. Now create another file named “native.c” inside the jni folder and copy this code into it.
This is our c code.
This don’t look purely like a c code because it has some java elements inside it.

#include <jni.h>
#include <string.h>
#include <android/log.h>

#define DEBUG_TAG "NDKDemoActivity"

void Java_com_coderzheaven_pack__NDKDemoActivity_printLog(JNIEnv * env, jobject this, jstring logString)
{
    jboolean isCopy;
    const char * szLogString = (*env)->GetStringUTFChars(env, logString, &isCopy);

    __android_log_print(ANDROID_LOG_DEBUG, DEBUG_TAG, "NDK: %s", szLogString);

    (*env)->ReleaseStringUTFChars(env, logString, szLogString);
}

Note :
Please take a look the function name

Java_com_coderzheaven_pack__NDKDemoActivity_printLog

This naming should be in this format
“Java_packagename_funtionname(arguments)”

Also one more thing the “dots” (.) in the package name should be replaced by underscore in the function name”. This is important.

OK Everything needed for NDK is done.
10. Now what we have to do is to compile the c code. For that go to “Run” > external tools > select NDK you created and run.

Now the c code has been compiled.

11. Now in the java Activity copy this code

package com.coderzheaven.pack;

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

public class NDKDemoActivity extends Activity {
	  static {
	        System.loadLibrary("ndkdemo");
	    }

	    @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.main);
	        printLog("Hello Coderzheaven");
	    }

	    private native void printLog(String logThis);
}

12. Now run this project and check the Logcat for the message after calling the C function from android.

You can any number of c functions inside the native.c code and run it.
Make sure to put a declaration on top of the activity before calling.

Please leave your comments if this post was useful.

How to create a Custom ListBox in Windows Phone 7?

For creating Custom ListView First create a new project named “Lists” and the language is “C#” here.

Now open the “MainPage.xaml” and copy this code.

<phone:PhoneApplicationPage
    x:Class="Lists.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:controls="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="800"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait"  Orientation="Portrait"
    shell:SystemTray.IsVisible="False">

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">

                <ListBox Margin="12,75,12,0" Name="L1"  SelectionChanged="ListBox_SelectionChanged">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel Margin="0,0,0,17" Width="432" Height="78">
                                <TextBlock  TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
                                <TextBlock  TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
                            </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
        <TextBlock Height="33" HorizontalAlignment="Left" Margin="12,36,0,0" Name="textBlock1" Text="Custom ListBoxes In windows Phone 7" VerticalAlignment="Top" Width="456" FlowDirection="LeftToRight" Grid.RowSpan="1" Foreground="#FF1BEB8D" AllowDrop="False" />
    </Grid>
</phone:PhoneApplicationPage>

Now we have to create another xaml for each custom row in the List.
For that right click on the project folder in the solution explorer.
Please check the screenshot, then select Add->New Item.

.

Now select the “Windows Phone User control”.
See the Screenshot.

Now in the “List_row.xaml” file copy this code.

<UserControl x:Class="Lists.List_row"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    d:DesignHeight="480" d:DesignWidth="319">

    <Grid x:Name="LayoutRoot" Height="60" Width="480" Background="#FF382725">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="220*" />
            <ColumnDefinition Width="480*" />
        </Grid.ColumnDefinitions>
        <TextBlock Height="30" HorizontalAlignment="Left" Margin="66,6,0,0" Name="title" Text="TextBlock" VerticalAlignment="Top" Width="351" FontFamily="Times New Roman" Grid.ColumnSpan="2" Foreground="#FF00BE3A" />
        <Image Height="45" HorizontalAlignment="Left" Name="myimage" Stretch="Fill" VerticalAlignment="Top" Width="44" Margin="8,5,0,0" Source="/Lists;component/images/coderzheaven.png" />
        <TextBlock Height="15" HorizontalAlignment="Left" Margin="67,33,0,0" Name="sub" Text="TextBlock" VerticalAlignment="Top" Width="384" FontSize="14" FontStyle="Normal" FontFamily="Times New Roman" Grid.ColumnSpan="2" Foreground="#FFD15F3E" />
    </Grid>
</UserControl>

Copy five image files into a folder named images in the solution explorer as shown in the first screenshot.

Now we go to the C# code.

Open MainPage.cs from the solution explorer and copy this code into it.

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

namespace Lists
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            string[] arr1 = new string[] { "CoderzHeaven", "Google", "Android","Apple", "Windows" };
            string[] sub = new string[] { "www.coderzheaven.com", "www.google.com", "www.android.com", "www.apple.com", "www.microsoft.com" };
            string[] images = new string[] { "coderzheaven", "google", "android", "apple", "windows" };

            for(int i = 0; i < arr1.Length ; ++i){
                List_row row = new List_row();
                row.title.Text = arr1[i];
                row.sub.Text = sub[i];
                row.myimage.Source = (ImageSource)new ImageSourceConverter().ConvertFromString("images/" + images[i] + ".png");
                L1.Items.Add(row);

            }
            for (int i = 0; i < arr1.Length; ++i)
            {
                List_row row = new List_row();
                row.title.Text = arr1[i];
                row.sub.Text = sub[i];
                row.myimage.Source = (ImageSource)new ImageSourceConverter().ConvertFromString("images/" + images[i] + ".png");
                L1.Items.Add(row);

            }
            for (int i = 0; i < arr1.Length; ++i)
            {
                List_row row = new List_row();
                row.title.Text = arr1[i];
                row.sub.Text = sub[i];
                row.myimage.Source = (ImageSource)new ImageSourceConverter().ConvertFromString("images/" + images[i] + ".png");
                L1.Items.Add(row);

            }

            this.Loaded += new RoutedEventHandler(MainPage_Loaded);

        }

        // Load data for the ViewModel Items
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }
    }
}

android listview

Please leave your valuable comments on this post.

Download the complete source code from here.

How to set an image in an Image Control in Windows Phone 7?

Hello everyone……

Windows Phone 7 with it’s simplicity has become really easy to study and code. In today’s tutorial I will show you how to set an image in an image control in windows phone 7.
Assuming you have place the image control in the xaml file. I will first show you how to set the image source in the xaml file.

<image Name=”imgMyImage” Source=”images/coderzheaven.png” />

Assuming that you have placed an imaged named “coderzheaven.png” inside images folder in the solution explorer.

Now if we want to dynamically set the image in code we do this.

myimage.Source = (ImageSource)new ImageSourceConverter().ConvertFromString(“images/coderzheaven.png”);

Since the result from ConvertFromString is an object we have to cast it to an ImageSource.

You can also set it in the properties window of the image. Click on the image control and in the properties window. do this..

Adding image source in windows phone 7

Adding image source in windows phone 7

Please leave your valuable comments on this post.

Page Navigation in Windows Phone

Hello everyone…

This is my first post on windows phone. I have just started windows mobile programming.
In this post I will show you how to go from one Page to another in windows.

First I am creating a C# project and in the MainPage.xaml

Open the phone interface and then drag a button into it. Double click on the button and write this code inside it.

  this.NavigationService.Navigate(new Uri("/Page1.xaml", UriKind.Relative));

Here is the complete code in MainPage.xaml

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

namespace PhoneApp1
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/Page1.xaml", UriKind.Relative));
        }
    }
}

Now right click on the solution explorer root and add->existing item , then add a portrait page. Then name it Page1.xaml

here is the code inside the Page1.xaml

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

namespace PhoneApp1
{
    public partial class Page1 : PhoneApplicationPage
    {
        public Page1()
        {
            InitializeComponent();
        }
    }
}

How to play video in fullscreen in android?

Hello all……

Someone has been asking me how to play a video in android in fullscreen. Then I made some surfing in the internet and found a solution.

You can check out how to play a video in android here and to check whether the video has completed playing here.
The only change was to do in the xml.

This is the xml code of the layout containing the videoview.

<?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
           android:layout_width="fill_parent"
           android:layout_height="fill_parent" >
   <VideoView android:id="@+id/myvideoview"
             android:layout_width="fill_parent"
             android:layout_alignParentRight="true"
             android:layout_alignParentLeft="true"
             android:layout_alignParentTop="true"
             android:layout_alignParentBottom="true"
             android:layout_height="fill_parent">
    </VideoView>
 </RelativeLayout>

Please leave your comments on this post.

You can download the complete source code here. Please include a video in res/raw folder and try.

How to save CheckBox values in SQlite Database and Load it later?

Hello……..

This post is just a simple demonstration to show a way to store a checkbox value in a database and reload it. Here I am storing only a value of a single checkbox and reloading it. But you can make changes in the code to save the id and value of the checkbox in the database and reload the values accordingly.

For the Sqlite functions I am creating a file that has the table and the function for inserting and other manipulations.

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 _CHK_VALUES = "checkbox_value";

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

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

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

		return DATABASE_CREATE;
	}
}

class dbOperation
{
		static String DB_TABLE ;
		static int DB_VERSION = 1;
		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, "mydb.db", 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 ;
	    }
}

Noe the main java source code for implementing this.

package com.coderzheaven.pack;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class SaveCheckBoxDemo extends Activity {

	CheckBox ch;
	Button save, reload;
	int checked = 0;

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

        initializeDB();

        save = (Button)findViewById(R.id.Button01);
        reload = (Button)findViewById(R.id.Button02);

        ch = (CheckBox)findViewById(R.id.CheckBox01);
        ch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(isChecked){
					checked = 1;
				}else{
					checked = 0;
				}
			}
		});

        save.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				updateTable(checked);
				Toast.makeText(getApplicationContext(), "Saved '"+ checked + "' in DB", Toast.LENGTH_SHORT).show();
			}
		});

        reload.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				System.out.println("getData(1) : " + getData(1));
				Toast.makeText(getApplicationContext(), "value from DB : " + getData(1), Toast.LENGTH_SHORT).show();
				if(getData(1).equalsIgnoreCase("0"))
					ch.setChecked(false);
				else
					ch.setChecked(true);
			}
		});
    }


	public  void initializeDB(){
		MyTable user = new MyTable();
	    String[] tableCreateArray = { user.getDatabaseCreateQuery() };
	    dbOperation operation = new dbOperation(this,tableCreateArray);
	    operation.open();
	    operation.close();
	}

	/*** SAVE THE DATA IN DB - GIVE FILENAME AND DATA ***/
	public  void saveData(int data){
			dbOperation operationObj = new dbOperation(this);
	        operationObj.open();
	        MyTable Fields = new MyTable();
	        ContentValues initialValues = new ContentValues();
	        initialValues.put(Fields.getScore(), data);
	        operationObj.insertTableData(Fields.getTableName(),initialValues);
	        operationObj.close();
	}

	/*** GET THE DATA FROM DB ,PARAMS - FILENAME -> GET THE DATA ***/
	public String getData(int id){
		String _data = "";
		dbOperation operationObj = new dbOperation(this);
		operationObj.open();
		MyTable fields = new MyTable();
		String  condition2 = fields.getID() + " ='" + id + "'";
        String[] dbFields4 = {fields.getScore()};
        Cursor cursor2 =  operationObj.getTableRow(fields.getTableName(),dbFields4,condition2,fields.getID() + " ASC ","1");
        if(cursor2.getCount() > 0)
        {
        	 cursor2.moveToFirst();
        	 do{
        		 _data = cursor2.getString(0);
        	 }while(cursor2.moveToNext());
        }else{
        	_data = "error";
        }
        cursor2.close();
        cursor2.deactivate();
        operationObj.close();
        return _data;
	}

	/*** SAVE OR UPDATE DB -> GIVE THE FILENAME AND DATA ***/
	public void updateTable(int updt_data){
		 	dbOperation operationObj = new dbOperation(this);
	        operationObj.open();
	        MyTable Fields = new MyTable();
	        //check for the value to update if no value then insert.
	        String file_ = getData(1);
	        if(file_.equals("error")){
	        	saveData(updt_data);
	        }else{
		        String  condition = Fields.getID() +" = '1'";
		        ContentValues initialValues = new ContentValues();
		        initialValues.put(Fields.getScore(), updt_data);
		        operationObj.updateTable(Fields.getTableName(),initialValues,condition);
	        }
	        operationObj.close();
	}
}

Now the xml file 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"
    >
	<TextView
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="Saving CheckBox Value in database and reloading it."
	    />
	<CheckBox
		android:text="Coderzheaven"
		android:id="@+id/CheckBox01"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content">
	</CheckBox>
	<Button
		android:text="Save CheckBox Value in DB"
		android:id="@+id/Button01"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content">
	</Button>
	<Button
		android:text="Load CheckBox Value from DB"
		android:id="@+id/Button02"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content">
	</Button>
</LinearLayout>

OK Done. Here what I have done is simply saving ‘1’ if the checkbox is checked and ‘0’ if not checked.

Apple late in China – Samsung already has almost triple share.

Apple Inc. (AAPL) got a partner to sell the iPhone in the world’s biggest mobile-phone market, China. The may be too late to catch Samsung with a market share that’s three times larger and growing.
Samsung controlled 24.3 percent of the market for phones in China.
“I don’t expect Apple to replace Samsung any time soon,” Gartner analyst Sandy Shen said in an interview. “China Telecom is the nation’s smallest carrier, so the extent to which they can help Apple is quite limited.”

Read more about this story from here.
http://www.bloomberg.com/news/2012-03-11/iphone-fails-to-gain-china-share-as-samsung-lead-triples-tech.html

Send Data when Clicking on a Notification in Android?

Hello everyone…

I have shown in my previous tutorials on how to create notification in android and cancel it.
This is the post showing this .

Now today I am going to show how to send data when you click on the notification message.

Here I am creating two activities. One the main activity that creates the notification and the other one is used when you click on the notification.
i.e the second activity is called when you click on the notification.

Here is the main activity that sends the notification.

java source code.

NotificationDemo .java

package com.coderzheaven.pack;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class NotificationDemo extends Activity implements View.OnClickListener{
	private Button buttonSend, clear;
	private static final int NOT_ID = 1;

	@Override
	public void onCreate(Bundle savedInstanceState) {

	  super.onCreate(savedInstanceState);
	  setContentView(R.layout.main);
	  buttonSend = (Button) this.findViewById( R.id.send);
	  clear = (Button) this.findViewById( R.id.cancel);
	  buttonSend.setOnClickListener(this);
	  clear.setOnClickListener(this);

	}

	@Override
	public void onClick(View v) {
		String ns = Context.NOTIFICATION_SERVICE;
	 	NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

		if(v == buttonSend){
	 		int icon = R.drawable.icon;
	 		CharSequence tickerText = "Hello ";
	 		long when = System.currentTimeMillis();

	 		int requestID = (int) System.currentTimeMillis();
	 		Notification notification = new Notification(icon, tickerText, when);
	 		Context context = getApplicationContext();
	 		Intent notificationIntent = new Intent(this, GoToNotification.class);
	 		notificationIntent.putExtra("data1", "My Data 1");
	 		notificationIntent.putExtra("data2", "My Data 2");
	 		notificationIntent.setAction("myString"+ requestID);
			PendingIntent contentIntent = PendingIntent.getActivity(this, requestID, notificationIntent, 0);
			notificationIntent.setData((Uri.parse("mystring"+requestID)));
	    	        notification.setLatestEventInfo(context, "Notification Demo", requestID + "", contentIntent);
        	    	notification.flags += Notification.FLAG_ONGOING_EVENT;
        	    	notification.flags += Notification.FLAG_AUTO_CANCEL;
	        	mNotificationManager.notify(NOT_ID, notification);
		}else{
			Toast.makeText(getApplicationContext(),"Cancelling", Toast.LENGTH_SHORT).show();
			mNotificationManager.cancel(NOT_ID);
		}

	}
}

The main.xml that creates the layout for the above activity.

<?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:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
<Button
	android:text="Send Notification"
	android:id="@+id/send"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content">
</Button>
<Button
	android:text="Cancel Notification"
	android:id="@+id/cancel"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content">
</Button>
</LinearLayout>

Now the second activity that is called when you click on the notification.

package com.coderzheaven.pack;

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

public class GoToNotification extends Activity{

	TextView tv = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		System.out.println("onCreate");

		setContentView(R.layout.notification);
		tv = (TextView)findViewById(R.id.tv);

		Bundle extras = getIntent().getExtras();

		if(extras != null){
			String data1 = extras.getString("data1");
			String data2 = extras.getString("data2");
			System.out.println("Ddata1 : " + data1);
			tv.setText("Data Sent from Clicking Notification nData 1 : " + data1 + "nData 2 : " + data2);
		}
	}

}

This is the layout for the second activity.
It simply contains a textview to show the passed data.

<?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:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    android:id="@+id/tv"
    />

</LinearLayout>

Also declare the activity in the manifest.xml

<?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=".NotificationDemo"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

	 <activity android:name=".GoToNotification"
                  android:label="@string/app_name" />
    </application>
</manifest>

Download the complete source code here.

Please leave your valuable comments.