Wednesday, March 19, 2014

Buttons - II

OnClick functionality of buttons can be written in three different ways
  1. By making activity implement OnClickListener and writing onClick method in the activity
  2. By writing an anonymous inner class
  3. Using android:onClick in xml file

Activity implementing OnClickListener

In the first line of your activity, add implements OnClickListener at the end.

    public  class MyActivity extends Activity implements OnClickListener

You will be prompted to import View.OnClickListener. 

When you hover over the classname   you will be prompted to implement onclick method

Select Add unimplemented methods

Editor adds onClick method in the activity. Add the action inside the method.


 @Override  
   public void onClick(View v) {  
     // TODO Auto-generated method stub 
    //Add your code here 
 }  

Now you should link your button to this listener by saying

btn.setOnClickListener(this);

If your class has multiple buttons, they can all use same listener. Then when any of these buttons are pressed, the onClick method is activated. Hence to specify action for your particular button, get the id and check against id of the button.

       public void onCreate(Bundle b){
       ----
       ---
 
           btn = (Button)findViewById(R.id.button1);  
           btn.setOnClickListener(this); 
      }  
      @Override  
      public void onClick(View v) {  
           int id = v.getId();  
           switch(id){  
           case R.id.button1: //your code goes here  
                          
           }  
      }  


 Writing anonymous inner class

In the code add "mybtn.setOnClickListener(new OnClickListener(){---});

 public void onCreate(Bundle b)  
 {  
    ------  
    -------  
    btn = (Button)findViewById(R.id.button1);  
    btn.setOnClickListener(new OnClickListener(){  
         public void onClick(View v){  
           //add your code here 
         }  
   });  

Again editor puts the template of the anonymous class for you :)

Specifying onClick Method in xml file

In the layout file, for the button, add android:onClick value.
  <Button  
     android:id="@+id/button1"  
     style="?android:attr/buttonStyleSmall"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_alignLeft="@+id/textView1"  
     android:layout_below="@+id/textView1"  
     android:layout_marginTop="29dp"  
     android:onClick="changeText"  
     android:text="Button" />  

Now define the onclick method  in the format public void methodName(View v)

      public void changeText(View v){
  Button b = (Button)v;
  String str = b.getText().toString() ;
  str = str+"clicked    ";
  b.setText(str);
 }


Thursday, October 10, 2013

Buttons

Let us try to create an activity with a button and a textview

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:tools="http://schemas.android.com/tools"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent" >  
   <TextView  
     android:id="@+id/textView1"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:text=" "  
     android:textSize="30sp" />  
   <Button  
     android:id="@+id/button1"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_alignParentLeft="true"  
     android:layout_below="@+id/textView1"  
     android:layout_marginTop="18dp"  
     android:text="Click Me" />  
 </RelativeLayout>  



We are using relative layout and we are putting the button below the textview using the xml line android:layout_below="@+id/textView1" for button. 

Let us run the program. 

We do not see any textview. That is because text is set to empty.

 






When the button is clicked, onClick event is fired. We should write a method to handle this event.

Let us write OnClicklistener for the button.


Let us add three lines to the onCreate method of the activity.

        btn = (Button) findViewById(R.id.button1);
        tv = (TextView) findViewById(R.id.textView1);
        btn.setOnClickListener(this);


 and define these two class variables.
        Button btn;
        TextView tv; 

variables. We are defining the OnClickListener of the button to this viz the current activity. So our activity should implement OnClickListener. Modify the class definition to something like

public class MainActivity extends Activity implements OnClickListener

Finally add onClick method to the class

 
   @Override  
   public void onClick(View arg0) {  
     if (arg0.getId() == R.id.button1) {  
       tv.setText( "Button clicked");  
     }  
   }  




This can be even done using xml. In the xml file, we can add this one line for the button -  
android:onClick="somemethodname"
 <Button  
     android:id="@+id/button1"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_alignParentLeft="true"  
     android:layout_below="@+id/textView1"  
     android:onClick="showString"  
     android:layout_marginTop="18dp"  
     android:text="Click Me" />  

Now we must define showString method in the activity.

public void showString(View v){
       tv.setText("Button clicked");
}

The signature of the method must be exactly as shown above. It should be public void and it must have exactly one parameter of type View
 
We can set background image of the button to another image using android:background="@drawable/someimage"



Wednesday, July 17, 2013

Activity - I

An activity is the place where user interacts with your android app. For each screen of your app, there will be an activity.



Write your first activity


Select  File  - New - Class
from the menu
and fill in the details
 Select the superclass as android.app.Activity.

Your empty activity is ready. But what do you display in this activity?

Views to be used in an activity can be written using java or xml file. Let us a simple TextView.










Let us write the code now.

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText("Welcome to android");
tv.setTextColor(Color.BLUE);
setContentView(tv);
}

Now run the app on the emulator. Do you see your activity? Of course not. You have not called it. 
To call this activity, either call it using an intent from your main activity or make this as the main activity.  

When and how do you call this activity? May be on click of a button in our hello screen. So let us add a button to our first hello world activity. 

Button b1 = new Button(this);
b1.setText("Click");//how innovative
b1.setOnClickListener(this);
this.addContentView(b1,new LayoutParams(LayoutParams.match_parent, LayoutParams.wrap_content));

Add these lines at the end of your earlier activity (MainActivity.java) onCreate method. When you see an error in Button, import android.widget.button. And add implements OnClickListener to the title of MainActivity class

Now IDE has added an empty OnClick method in the class. Complete that method.

Intent i = new Intent(this, Myactivity.class);
        startActivity(i);



To start a new activity, we use intent. Second parameter to Intent constructor is the class name of new activity. 

After adding these two lines to onClick method, you are asking the program to start new activity onclick of the button. Run the app now. What do you see? 

Program crashed , right? OK, any activity to be used in the application must be specified in the android manifest file. As we did not add this activity in the android manifest file, we got error. 

Let us add the line 
   <activity android:name="com.example.hello.Myactivity"></activity>
    

just before </application> in AndroidManifest.xml

Now you run the application again and click on the button. You will see your activity finally. :)

  


















Layout files

It is not feasible to write code for complicated screen with multiple views. Hence you can define your screen layout in an xml file.

To create such a layout xml file,use
File - New - android xml file

Make sure the file is of the type .xml and it is in /res/layout folder.  You will see a graphical  layout. Drag and drop the required widgets in to the layout.

I have created myscreen.xml and  added two textviews  to the screen, second one center aligned. Here is how xml file looks like
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="TextView" />

</LinearLayout>


To use this screen for our activity, we should set the content view to the above xml file.

In the onCreate method, change setContentView(tv) to setContentView(R.layout.myscreen)

Accessing the views from xml file

If you want to access the widgets mentioned in xml file, you should access them using findViewById. For each resource used in the application, a unique resource id is created. Hence our first textview in the xml file has resource id of R.id.textView1 where textView1 is taken from android:id. 

TextView tv1 = (TextView)findViewById(R.id.textView1);
tv1.setText("Welcome");
TextView tv2 = (TextView)findViewById(R.id.textView2);
tv2.setText("to android");
tv1.setTextColor(Color.BLUE);

Saturday, June 15, 2013

Android Application and its components

In the last post we created an android application. Let us see some features of an android application.

  • Android OS is a multi-user Linux OS.
  • Each  application has its own user id.
  • Each process in the application runs in its own virtual machine. But android apps do not use JVM. They use a VM called dalvik virtual machine.
  • Every application runs in its own process
  • Android implements principle of least privilege. That is to say each application can access its own data and resources, but not the those of other applications.
  • But apps can access device data such as contacts, SMS etc by requesting permission from the user at install time.
Components of an application

An application can consist of
  • Activity : single screen with user interface. An app can start any of its activities and also activities of other apps. 
  • Service : It is a background component which does a long running operation like conversion from text to speech. It does not have a user interface.
  • Content provider : this manages shared data. Your app can store the data in file, sqlite database etc and other apps can access this data using content provider.
  • Broadcast receiver : receives system wide broadcast announcement like turning off of the display, arrival of a SMS message etc. Does not have user interface, but can display a message on status bar.
Starting application components :

     Activity, Service or Broadcast receivers are started by sending an asynchronous message called intent. Content provider is started when it is targeted by a content resolver. In some cases, if the intent object is provided with the action to perform, the android system selects appropriate activity and starts it. e.g. if the intent specifies view action for a web page, then the browser is started.


Manifest file :

 All components of an activity must be mentioned in a file called AndroidManifest.xml file. This manifest file must be located at the root of the android application. If a component is not mentioned in this manifest file, then android system can not start that component.

A sample manifest file looks like this
 As you can see, the manifest file also specifies the minimum sdk version, the permissions for the app, the hardware requirements like bluetooth, camera etc.

Resources

If you look at the app in package explorer, you can see along with src (source) folder, another folder res (resource). The resource folder contains the images for the app, layout files for activities, menus, styles, colors etc. Resources are stored in different sub-folders such as res/layout/main_activity.xml, res/drawable/ldpi/logo.png etc. Sdk tools will create a unique resource id for each of the resources in the form - R.drawable.logo, R.layout.main_activity etc.





















And to end our discussion, let us see what are the various components android sdk provides us for development.

SDK Tools

Emulator:
You can test run your apps on emulator, instead of actual phones. You can select a virtual device with different versions of android, different hardware configuration. The emulator can be started from eclipse or from shell. The emulator can even emulate sms messages, internet etc, but not camera or bluetooth.

DDMS : Dalvik debug monitoring service lets you debug your application. You can inspect the memory, you can kill any process, you can set break points etc.

ADB : Android debug bridge lets you communicate with the android emulator or device. Adb provides you commands to install and uninstall an app, push or pull a file, start a linux shell for the device or virtual device.

AAPT : Android asset packaging tool converts all the resource file of android application into aidl file. Java compiler converts aidl file and java source file together into .class files.

dex :  dex tool converts .class file into dalvik byte code called .dex file.

apk builder : converts .dex file into file .apk file which can be installed on the phones.

Don't worry too much about these terminology. Eclipse will take care of all these tools. And if you want to debug the application, you can use ddms perspective.


Saturday, June 1, 2013

Create your first android application

I am not going to bore you with details like what is android and how it is better than other platforms etc. Since you have already decided to learn android, you have done your homework and got some introduction about these topics.

Let me instead start with what are the hardware and software you need to learn android.

Hardware
  1.  You need a PC. The OS does not matter. You can use windows machine, or Linux machine or mac.
 That's all. At this stage you do not need a phone running android.

Software 
  1. Since android applications are written in Java, you need a Java Development Kit. You can download this from oracle site http://www.oracle.com/technetwork/java/javase/downloads/index.html
  2. You need android software development kit (SDK). This can be downloaded from android developer website http://developer.android.com/sdk/index.html
  3. It is preferable to use an IDE. Eclipse is very convenient. You can download latest version of eclipse from http://www.eclipse.org/downloads/
Download these software and install them. And you are almost ready to learn android.

Do you have some basic knowledge of Java programming? If not, learn  Java now. Since android programs are written in Java, you need to know Java.

You will again ask me- what about emulator, where do I get emulator from. Android SDK comes with emulator and DDMS -Dalvik debug monitor server. 

Earlier it was necessary to download ADT - android developer tools, in eclipse IDE. But now android sdk comes bundled with ADT.

Once you install android sdk, you should decide which version of android - 4.2 Jelly Bean being the latest, you want to work on. Run SDK manager and download the corresponding sdk platform

You should download platform-tools and SDK platform form whichever version of android you want to use. It is advisable to download documentation which will help you in syntaxes.  Here I have selected android 4.0.3 to download and samples for the same.

Create  your first android application

You have armed yourself with all the tools necessary. Now plunge into water. Start eclipse and start a new android project

In Eclipse menu select File-New-Android Application Project.

In latest eclipse version, this is how the menu looks like


Change the application name and package name. In the next screen, select create Activity and create application in workspace. In third screen, select create blank activity and in fourth screen give activity name and xml name and click finish.
Your first android app is ready. Now build the project. Right click on the project name in project explorer and select run as android application. 
A new emulator is started and your app will be installed and executed in it. 



This is how your first app looks in android 4.2 emulator. Now grab a cuppa and enjoy. Because second lesson will not be this easy.