Android : Using Button & Click-Event with example


Introduction :

In this article we will learn, how to use Button and Listen for Click-Events. We shall take an example to understand all these . To make the example clear and easy to understand we shall use another control called EditText.

Implementation using  Example :

  • Create a new android project with name ButtonTutorial.
    [If you are a beginner and don’t know how to create a project then read it here Creating HelloWorld Application in Android]
  • Type you application name as My Button Tutorial.
  • Provide package name as com.suvendu.tutorials.button
  • Open main.xml and delete the single TextView already present in the page(may be with a text ‘Hello World, ButtonTutorialActivity!’.
  • Drag a EditText and a Button on to the layout.
  • Change the id of the EditText to ‘@+id/txtShowCurTime
  • Change the id of the Button to ‘@+id/btnGenCurTime
  • Add a new string to strings.xml with Name ‘button’ and Value Generate Current Time
  • Change the text of the Button to ‘@string/button’
    [Your layout is ready now and the main.xml should look like this]

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:orientation="vertical" >
    
    <EditText
     android:id="@+id/txtShowCurTime"
     android:layout_width="match_parent"
     android:layout_height="wrap_content" >
     <requestFocus />
     </EditText>
    
     <Button
     android:id="@+id/btnGenCurTime"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:text="@string/button" />
    
    </LinearLayout>
    
    
  • Open your default activity file (Ex: ButtonTutorialActivity.java)
  • Declare two global variables
    Button btnCTime;
     EditText txtCTime;
    
    
  •  import respective packages
    import android.widget.Button;
    import android.widget.EditText;
    
    
  •  Link these variables to the layout in OnCreate() as follows
    btnCTime=(Button)findViewById(R.id.btnGenCurTime);
     txtCTime=(EditText)findViewById(R.id.txtShowCurTime);
    
    
  • We don’t want the OnScreenKeyBoard to appear when the cursor is on EditText so, let disable this.
    txtCTime.setInputType(InputType.TYPE_NULL);
    </li>
    	<li>Set the OnClickListener for the Button
    
    btnCTime.setOnClickListener(new OnClickListener() {
    
     @Override
     public void onClick(View vw) {
    
     }
     });
    
    
  • import the package for OnClickListener
    import android.view.View.OnClickListener;
    
  • Now do the logic inside onClick() to show the current time
    txtCTime.setText(new Date().toString());
    
  • You need to import java package for using Date
    import java.util.Date;
    
  • Finally, the default activity file should look like
    package com.suvendu.tutorials.button;
    
    import java.util.Date;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.text.InputType;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    
    public class ButtonTutorialActivity extends Activity {
        Button btnCTime;
        EditText txtCTime;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            btnCTime=(Button)findViewById(R.id.btnGenCurTime);
            txtCTime=(EditText)findViewById(R.id.txtShowCurTime);
            txtCTime.setInputType(InputType.TYPE_NULL);
            btnCTime.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View vw) {
                    txtCTime.setText(new Date().toString());
                }
            });
        }
    }
    

Downloads :

You can download the full project here. Download

Or, you can just download the apk here.Download

Conclusion :

We are able to use a Button control in Android and can use its OnClick event to do various activities.
I hope  you enjoyed this tutorial.

Please give your valuable feedback and stay tuned for more ..

You may also like-

Simple example of Intent in Android 

If you are a beginner then you may also like following articles-

Android : Simple example of Intent


In this post we will see how to write a simple android application to show usage of Intent.

Steps to be performed :

  • Add a new project
  • Open main.xml and drag and drop three Button controls and then rename their ids.
    Or, Clear all the contents and paste the code provided below.

    
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:orientation="vertical" >
    
     <Button
     android:id="@+id/btnGallery"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:text="Show My Gallery" />
    
     <Button
     android:id="@+id/btnCallLog"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:text="Show My Call Log" />
    
     <Button
     android:id="@+id/btnContact"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:text="Show My Contacts" />
    
     <Button
     android:id="@+id/btnSearch"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:text="Show My Search" />
    
    </LinearLayout>
    
  • Now lets code for these 4 buttons.
  • Open your Activity file.
  • Now code for each button like the code provided below.
    </pre>
    package com.suvendu.tutorial;
    
    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    
    public class IntentDemoActivity extends Activity {
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);
    
     Button myGalleryBtn=(Button)findViewById(R.id.btnGallery);
     Button myCallLogBtn=(Button)findViewById(R.id.btnCallLog);
     Button myContactBtn=(Button)findViewById(R.id.btnContact);
     Button mySearchBtn=(Button)findViewById(R.id.btnSearch);
    
     myGalleryBtn.setOnClickListener(new Button.OnClickListener(){
    
    @Override
     public void onClick(View v) {
    
     Intent myIntent=new Intent();
     myIntent.setAction(Intent.ACTION_VIEW);
     myIntent.setData(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
     startActivity(myIntent);
    
     }});
    
     myCallLogBtn.setOnClickListener(new Button.OnClickListener(){
    
    @Override
     public void onClick(View v) {
    
     Intent myIntent=new Intent();
     myIntent.setAction(Intent.ACTION_CALL_BUTTON);
     startActivity(myIntent);
    
     }});
     myContactBtn.setOnClickListener(new Button.OnClickListener(){
    
    @Override
     public void onClick(View v) {
    
     Intent myIntent=new Intent();
     myIntent.setAction(Intent.ACTION_VIEW);
     myIntent.setData(android.provider.Contacts.People.CONTENT_URI);
     startActivity(myIntent);
    
     }});
     mySearchBtn.setOnClickListener(new Button.OnClickListener(){
    
    @Override
     public void onClick(View v) {
    
     Intent myIntent=new Intent();
     myIntent.setAction(Intent.ACTION_SEARCH);
     startActivity(myIntent);
    
     }});
    
     }
    }
    

    [Note: You have to change the package name with your original package name, you provided at the time of creating the project. Similarly, you have to change the class name too.]

Result :

Clicking on the ‘Show My Gallery’ button should open your phone’s gallery.

Clicking on ‘Show My CallLog’ button will open you call log.

Clicking on ‘Show My Contact’ will open your Contact Book.

Clicking on ‘Show My Search’ will open action window to perform search using different options.

Downloads :

If you want to download the code, you can download it here Download

If you want see it quickly you can download it here Download

References :

If you are a beginner then you may also like following articles-

Android: Creating ‘HelloWorld’ application in Android with Eclipse Indigo


Introduction:

Another ‘HelloWorld’ application ???

Yes, the name ‘HelloWorld’ is chosen because it is one of the most searched word when a fresher starts doing a program with a language/platform which is new to him/her. I didn’t really code a great logic for this application except a very few lines of code- just to show some text(lets say: ‘HelloWorld’) on the screen.

Prerequisites:

As I am going to develop an android application so, I need android SDK and Eclipse to be already installed on my system. For a quick installation guide you may read my post on Installing Android SDK on windows: Complete steps.

Target Readers:

I have made this post specially to code on Eclipse Indigo as I assume, the readers of this post are freshers in Android apps development. I am going to explain it right from the New Project dialogue box to   the message on Emulator Screen and I have Eclipse Indigo installed on my system as well. With a different version of Eclipse the code will be same but, the instruction may vary a little bit.

What to Do?

  1. Open Eclipse
  2. Open the Emulator
    [if you don’t have created an AVD then create one using below few steps otherwise you can skip till Step 3]
    *Go to Window menu and click on AVD Manager, which will open Android Virtual Device Manager in  a new window.
    *Click on New button
    *A new window will be opened and will ask for Name.
    *Type a name there.[Ex: MyDevice]
    *Then choose target android version from dropdown Target. [Ex: Android 2.2 -API Level 8]
    *Now click on Create AVD
    *OK, your AVD is now ready to run which you can see in the AVD list on the AVD Manager window.
    *Now, choose the device you just have created and then click on Start button.
  3. Go to File –>New
  4. Click on Project.
  5. Select Android Project from Android directory/folder.
  6. Click Next button.
  7. Type your project name. [Ex: HelloWorld]
  8. Click Next.
  9. Select a build target. [Ex: Android 2.2]
  10. Click Next.
  11. Type a valid Package Name. [Ex: com.demo.mydemo]
  12. Make sure that Create Activity checkbox is checked.
  13. Click Finish.
  14. Now the project can be seen, listed on the Navigator.
  15. It contains some pre-generated files and folders.
  16. Open the Activity file located under src folder .[Ex: src –> com –> demo –> mydemo –>]
  17. Delete the entire contents from it.
  18. Now, Paste following code-
    
    package com.demo.mydemo;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.TextView;
    public class HelloWorldActivity extends Activity {
     TextView tv;
     @Override
     public void onCreate(Bundle bndl) {
     super.onCreate(bndl);
     tv=new TextView(this);
     setContentView(tv);
     tv.setText("This is a simple HelloWorld android application !");
     }
    
    }
    

    [Note: Change the package name if you  have typed a different name earlier while creating project and similarly change the activity name if you have defined with a different name ]

  19. Run the project from menu Run –> Run
    or, right click on the project on Navigator and then click on Run As –> Android Application
  20. Now you can see the result on the emulator screen.

That’s it !!!!

Analysis :
Here package is the one which you have defined earlier while creating the project. Then like Java, you have to import all the classes you reference. The onCreate() method is invoked when the activity starts. To initiate the activity we have to call super.onCreate(). You  need to call super.OnCreate(), every time when overriding the onCreate() method of an Activity. It should be the very first line in the overriding method. Then I have created an instance of TextView, where I am supposed to put some random text or, some message or, “HelloWorld” etc. Here setContentView() sets the TextView, which we have created earlier to the screen so that it can viewed by the user. Then I have assigned some text (i.e,This is a simple HelloWorld android application !”) to the TextView…Yes, I know- I am deviating from the Introduction of the article where I said that it will show ‘HelloWorld’ but, these text doesn’t matters really, what I wanted to show is a custom message or some random text on the emulator screen.  That’s all.

Conclusion :

Now, we are able to create a very simple application in android. I will post some more articles on Android Apps Development in my successive posts.. So, tuned.. In case any query you can comment here.

 

If you want install a .apk file in your emulator then you may read my post here for a easy solution.

https://suvendugiri.wordpress.com/2012/01/24/android-installing-dotapk-file-on-emulator-in-windows/

Android: Installing [dot]apk file on Emulator in Windows


If you want to install a .apk file on your emulator then you need Android Debug Bridge (adb)  which is a command line tool for Android.

Follow few simple steps for installation –

  • Download the required files for adb command line installation from www.suvendugiri.com/AndroidResources/adb.zip
  • Extract and copy all 3 files.
  • Paste to the tools sub-folder of root directory of Android SDK installation
    For Example: In my case – C:\Program Files\Android\android-sdk\tools
  • Start your emulator and wait till home screen has not come.
  • Now open command prompt.
  • Change directory to have the current directory till tool i,e, the folder where you have pasted the 3 extracted files in the above step.
    For Example:  In my case – C:\Program Files\Android\android-sdk\tools
  • Now type :
    adb install E:\AndroidAPKs\MyDemoProject.apk
    Where E:\AndroidAPKs\MyDemoProject.apk is the apk file I wanted to install with it’s detail folder path.
  • Then press enter.

That’s it !!!

[NOTE/DISCLAIMER: ALL THE ABOVE STEPS WORKS FINE FOR ME. BUT, I DON’T TAKE ANY RESPONSIBILITY FOR ANY HARDWARE/SOFTWARE DAMAGE CAUSED DUE TO THIS ARTICLE . YOU SHOULD DO IT ALL WITH YOUR OWN RISK. ]

https://suvendugiri.wordpress.com/2012/01/24/android-installing-dotapk-file-on-emulator-in-windows/

ASP.NET: Reference type as parameter to a method


Introduction :

This post is about passing reference type (like array) to a method. Whatever I have written below is purely based on my experiments and the knowledge I gained from MSDN etc. So, if somebody reading this post has a better idea then please comment.  Before I write something, let quickly look at the following 3 snippets of code. For a quick demo I have used Console Application but, the concept below holds good for either ASP.Net or Windows Application or any other. As C# is the most advanced and mostly used programming language, I have decided to use it for my demonstration.

Have a look at the code :

Snippet 1 :

//Demonstration with Integer parameter
static void Main(string[] args)
{
  int num = 1000;
  Console.WriteLine("Initial Value in num: {0}", num);
  Console.WriteLine("______________________________");
  PlusPlus(num);
  Console.WriteLine("______________________________");
  Console.WriteLine("Final Value in num: {0}", num);
  Console.ReadLine();
}

static void PlusPlus(int numFormal)
{
  numFormal += 1;
  Console.WriteLine("Value in numFormal: {0}", numFormal);
}

Output Of Snippet 1 :

Initial Value in num: 1000

_____________________

Value in numFormal: 1001

_____________________

Final Value in num: 1000

Snippet 2 :


//Demonstration with Array(Int) parameter
static void Main(string[]  args)
{
  int[] arrNum = { 1000, 2000, 3000 };
  for(int i=0;i  {
    Console.WriteLine("Initial Value in arrNum["+i+"] : {0}", arrNum[i]);
  }
  Console.WriteLine("_________________________________________");
  PlusPlus(arrNum);
  Console.WriteLine("_________________________________________");
  for (int i = 0; i < 3; i++)
  {
    Console.WriteLine("Final Value in arrNum["+i+"] : {0}", arrNum[i]);
  }
  Console.ReadLine();
}

static void PlusPlus(int[] arrNumFormal)
{
  for (int i = 0; i < 3; i++)
  {
    arrNumFormal[i] += 1;
    Console.WriteLine("Value in arrNumFormal["+i+"]: {0}", arrNumFormal[i]);
  }
}

Output Of Snippet 2 :

Initial Value in arrNum[0]: 1000
Initial Value in arrNum[1]: 2000
Initial Value in arrNum[2]: 3000
__________________________
Value in arrNumFormal[0]: 1001
Value in arrNumFormal[1]: 2001
Value in arrNumFormal[2]: 3001
__________________________
Final Value in arrNum[0]: 1001
Final Value in arrNum[1]: 2001
Final Value in arrNum[2]: 3001

Snippet 3 :


//Demonstration with string parameter
static void Main(string[] args)
{
  string str = "original string";
  Console.WriteLine("Initial Value in str: {0}", str);
  Console.WriteLine("______________________________");
  ChangeString(str);
  Console.WriteLine("______________________________");
  Console.WriteLine("Final Value in str: {0}", str);
  Console.ReadLine();
}

static void ChangeString(string strFormal)
{
  strFormal = "changed string";
  Console.WriteLine("Value in strFormal: {0}", strFormal);
}

Output Of Snippet 3 :

Initial Value in str: original string
__________________________
Value Of numFormal: changed string
__________________________
Final Value Of num: original string

Analysis :

Analysis of Snippet 1 & its result :

In the Snippet no. 1, I have declared a local integer variable ‘num’ and assigned a value 1000 to it. Then after displaying(“Initial Value in num: 1000”) it on the screen I called a method PlusPlus(), which takes a single argument of type int. To this method I passed the variable ‘num’. The body of the static method PlusPlus() consists of only 2 lines of code. First line increments the formal parameter by 1 and then the second line of code prints(“Value in numFormal: 1001”) it on the screen.Then again I am printing(“Final Value in num: 1000”) the value hold by the variable ‘num’.
Thing to notice here is after passing the variable to the method PlusPlus() and there although I am incrementing it by 1, it did not change its original value. This is because when I am passing a int variable to a method, exactly I am passing the value hold by the variable as int is a value type and the method computes on the value passed to it, which is hold by the formal parameter not the actual parameter.

Analysis of Snippet 2 & its result :

I have repeated the same process as in the Snippet 1 except I have changed the local variable integer to a integer array. But, here the result is something different. The difference is- the changes I have done to the formal parameter in the method PlusPlus()  also reflects for the actual parameter or, the original integer array declared in the main() method. This is happened as array is a reference type so, when I am passing an array to a method, actually I am passing its reference and now the formal parameter holds the same reference as the actual parameter. So, when I am changing the value present in any of the indices of the array in the formal parameter it reflects in the actual parameter also.

Analysis of Snipet 2 & its result :

Once again I have repeated the same process as snippet 1 and 2 with the same little change in the datatype of the variable. Now, I want to see the result when I am using a string variable, which is of reference type. But the result is same as the snippet 1 where I had used integer variable.

Now, Question is- why this deviation ?

This is happened because, although string is a reference type but the class System.String or, its alias string is immutable. If you want to know more on immutable type you can search it in MSDN. I will discuss about mutable and immutable type in details in my next blog post but for now, you can consider the real meaning of the English word ‘immutable’ – ‘Not susceptible to change’. It means we can not change the value hold by a string variable. When we are changing the value hold by the string variable in the method ChangeString(), actually a new variable is created to store the new value. So, the changes did not reflect on the actual parameter or, the original variable.

Conclusion :

When we are passing an array as parameter we should understand that, the calling method can change its value.

Bookmark in Visual Studio


While developing application using Visual Studio, sometimes we need to navigate between different lines of code. If the page contains several lines(lets say 1000 or more) then it becomes very time consuming work to navigate between different sections. For instance, when developing web application using ASP.Net if somebody wants to put Javascript validation for the controls already used in the page, then he/she has to move the cursor from the Javascript function to the line where the control is declared to get the Control Id. In this case we can use Bookmark provided by Visual Studio IDE.

The very simple syntax to use Bookmark can be –
(i) move your cursor to the line where you want to put the Bookmark and then press key combination “Ctrl+K” twice. Now you can see a rounded-cornered square mark on its extreme left, which is nothing but the bookmark.
(ii) to remove a bookmark follow the same procedure as above.
(iii)to navigate to the next Bookmark press key combinations “Ctrl+K”,”Ctrl+N”
(iv) to navigate to the previous Bookmark press key combinations “Ctrl+K”,”Ctrl+P”

One can use it smartly to improve his/her coding speed using Visual Studio IDE.

For detail information you can read it here abhijitjana.net by Abhijit Jana, who is one of my favorite blogger on .Net Technology.

For more tips on Visual Studio IDE, you can refer codeproject.com

More Tips on Visual Studio –

Shortcut for Collapse/Expand Code blocks in Visual Studio

Smart-Work is better than Hard-Work

Installing Android SDK on Windows: Complete Steps


To begin with android apps development, you need to install the SDK and some other required components. Following are the steps one may follow to have the Android SDK installed in his/her system, although it is always advised that you should follow the instruction as per developer.android.com. If this not works for you then for any support and help you can mail me on suvendu.giri@live.com

  1. Download and install JDK if not installed already. [Download link] 
  2. Download and install Android SDK. [Download link]
  3. A pop-up will come out just after you finished installing the SDK, which is the SDK manager. If no pop-up window comes then you can manually open it from ‘All Program’.
  4. Download all or, required versions and components by checking them. For example, you can only check Android 2.2 and install it.
  5. Download & install eclipse. [Download link]
    n.b. :this is for 32 bit OS
  6. To Download and install ADT plugin for Eclipse –
    ->Start Eclipse, then select Help > Install New Software….
    ->Click Add, in the top-right corner.
    ->In the Add Repository dialog that appears, enter “ADT Plugin” for the Name and the following URL for the Location.
       

    https://dl-ssl.google.com/android/eclipse/

    ->Click OK
    ->Note: If you have trouble acquiring the plugin, try using “http” in the Location URL, instead of “https” (https is preferred for security reasons).
    ->In the Available Software dialog, select the checkbox next to Developer Tools and click Next.
    ->In the next window, you’ll see a list of the tools to be downloaded. Click Next.
    ->Read and accept the license agreements, then click Finish.
    ->Note: If you get a security warning saying that the authenticity or validity of the software can’t be established, click OK.
    ->When the installation completes, restart Eclipse.

  7. Configuring Android SDK:
    ->After you’ve successfully downloaded the ADT as described above, the next step is to modify your ADT preferences in Eclipse to point to the Android SDK directory:Select Window > Preferences… to open the Preferences panel (Mac OS X: Eclipse > Preferences).
    Select Android from the left panel.
    ->You may see a dialog asking whether you want to send usage statistics to Google. If so, make your choice and click Proceed. You cannot continue with this procedure until you click Proceed.
    ->For the SDK Location in the main panel, click Browse… and locate your downloaded SDK directory.
    ->Click Apply, then OK.
    ->Done! If you haven’t encountered any problems, then the installation is complete