Monday, 23 February 2015

Layout's in Android

Layout in simple terms determines how the items are being displayed for the user in an activity in the app or widget. The layout can be fixed either at the design time or at the run time. Following are the few basic layouts in Android

1.       Linear Layout
Linear layout is used to align all its child elements in a specific direction either horizontally or vertically.

2.       Relative Layout
Relative layout is used to align all its child elements based on the position of other element within it. If no relative positioning is given all the elements will be in the same place.

3.       Table Layout
Table layout is used to group the elements as rows and columns. Where each rows has zero or one cells, where each cell can have a view object.

4.       Grid Layout
Grid layout is used to display a 2-dimensional scrollable grid, generally the items to the list are added using a List Adapter.

5.       Frame Layout
Frame layout is generally used to as a placeholder on the screen for displaying an item. It generally blocks out an area in the screen to display the single item.

6.       List View
List layout is used to display a list of items with a scrollable option, generally the items to the list are generally added using an Adapter. The list of items can be a text or custom designed by extending the Base Adapter.


These are the main layout which we will be working on. 

Friday, 30 January 2015

Android application key components

This tutorial explains some of the basic key components of an Android application, which will be helpful in creating an Android project.

Activities: An activity is a single screen in which a user interacts in an android application. An application can have more than one activity. When an application starts it calls the default activity mentioned in AndroidManifest.xml (Refer HelloWorld example in the previous blog) as highlighted below, this can be changed at any point of design time.
<activity
            android:name=".MainActivity"
            android:label="@string/app_name" >

An activity can call / start another activity when required.

Services: Service is the component that is used to perform action in the background for an application without any user interaction. It can used for logging or to perform work for remote process.  

Content Provider: It’s the standard interface to share data between processes and provide mechanism for defining data security. Used to store data in the file system or use SQL Lite. For example using the content provider the app can read and modify the contact details using the Android provided content provider.

Broadcast Services: It’s a way to listen to system wide even happening in your Android device which is accessible to all apps. Some of the Android provided broadcast services are Screen turned on, battery is low, call/SMS is received, phone is booted etc.

Intents: It’s a messaging object you can use to request an action from another component. An Intent is the key component to call one activity from another activity. For example from our app we can request camera app to take a picture.
Explicit Intent: Specify the component to start by name like call another activity in the same app.
Implicit Intent: Does not specify the component to start instead declare a general action to perform which allows a component from another app to handle that.

Fragments: Fragment is the section of the activity which represents the behavior or a portion of user interface in an activity. An activity can have more than one fragment. A fragment has its own life cycle which can be removed or added at any point when an activity is running.

Views: It’s the place where all the UI elements are being placed in the android application.

Layouts: Layout in Android describes how the UI should look in an activity. This can be declared in the UI XML and/or instantiate the layout at runtime. This can be customized as per required. There are various types of layouts like Linear, Relative, List, Grid etc.


Resources: Resource is a component of the Android application which is used to keep track of all the non-code assets of the application. Resources can be a XML file, images, audio files, etc. 

Friday, 31 October 2014

Message box on Button Click in Android (TOAST)

This tutorial explains how to show a message box on button click of an Android application.

Create a new Android project:

Create a new project as in the Hello World Android tutorial.

Application Name:  Message Alert
Project Name: MessageAlert
Package Name: com.skk.messagealert

Minimum SDK:  API 8
Target SDK: API 20
Compile With: API 20
Theme: Holo Light with Dark Action Bar

Activity Name: Message_Alert

1)      Remove the existing TextView “HelloWorld”
2)      Drag and drop a button from the Forms Widget Pallet to Android Screen and rename the Text properties to “Show Alert”




3)      Response for the button click in Android can be done via any of the two following ways,

a.       By setting onClick event:
In the properties of the button change the onClick event value to sendMessage. This will update the XML as below

android:onClick="sendMessage"

 Complete XML File:

<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.skk.messagealert.MessageAlert" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="98dp"
        android:layout_marginTop="46dp"
        android:onClick="sendMessage"
        android:text="Show Alert" />

</RelativeLayout>

Now we need to write the code for showing the Message on button click i.e the event, go to the java file MessageAlert.java under src\com.skk.messageAlert\ add the following method in MessageAlert class

public void sendMessage(View view) {
              Toast.makeText(getApplicationContext(), "You have clicked me!", Toast.LENGTH_LONG).show();
       }

Typically in this method we set the text that needs to be displayed when button is clicked, and how long it should be shown and show the message to the user.

b.      Using onClickListener event:
In this method we set the Listener event for the button. The below is the code for the same.

       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_message_alert);
             
              Button bt1 = (Button) findViewById(R.id.button1);
              bt1.setOnClickListener(new View.OnClickListener() {
                    
                     @Override
                     public void onClick(View v) {
                           Toast.makeText(getApplicationContext(), "You have clicked me!", Toast.LENGTH_LONG).show();
                     }
              });
       }

Here we create a local variable to refer the button and add the EventHandler for that and on click of that we show the message using Toast.

4)      After creating the code as in any one of the methods above, save and run the code as Android Application Project. This will launch the android application. Once you click the button you should be able to see the message being show.


Successfully we have created and deployed the sample message box in Android.

Additional Details:

Toast: Toast is used to show a small popup upon a specific action in Android, while the current activity remains visible and interactable.
makeText(): This is used to create the text message that needs to be displayed , duration and the application context.
show(): This method is called to displayed the created text message.
R.java:  This is an auto generated file for all the Android project, it creates a unique ID for all the elements in the Android application i.e Button, title, logo etc. Sample value below.

public static final int button1=0x7f05003c;


Note: The value of the button might differ for you.

Sunday, 26 October 2014

Hello World in Android more details


This tutorial explains provides you some basic explanation about the Android application project.

Following are the list of items which needs to be known when creating a simple application.

1)      Activity:
Activity is the one which provides screen to the user where he can interact with the application. There should be at least one activity in your Android application to run. Whenever an application icon is clicked any one Activity will be started.

2)      Layout:
Layout is one which defines how your application screen should look like. The layout that we use in the HelloWorld application is RelativeLayout. Which sets the items in a sequence based on other items. In every Android project there will be a folder called LAYOUT in which all the layout design files are stored in XML format.

3)      AndroidManifest.XML:
This file contains the configuration details of our Android application, the minSDK and targetSDK. List of permission that the application need access i.e internet, camera etc.., the first activity that needs to be run when the application launches. What’s the display name of the application, the theme that needs to be used etc.

Below is the file sample file of an Android application.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.skk.helloWorld"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>


4)      Values folder:
This section in the Android project contains the strings, styles, format of the UI elements etc. Below is the sample strings.xml which contains the strings and its values.

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Hello Kumar</string>
    <string name="hello_world">Hello Kumar!</string>
    <string name="action_settings">Settings</string>

</resources>


5)      Drawable folders:
This section contains all the images that are used in the Android application. The images with various resolutions are kept in separate folders.

The above are the basic details that needs to be known for a sample application. Details in depth will be explained in separate posts.


Friday, 24 October 2014

Hello World application in Android


This tutorial explains how to create a hello world program in Android.

For setting up the Android development environment check out this blog.

Create a new Android project:

1)      Open the Eclipse IDE, Click on the menu item File à New à Android Application Project

 
2)      Once you select the menu, you will be able to find a screen to enter the details of the new project enter the details as show in the screenshot below.


Application Name: Name that appears to users after the app is installed.
Project Name: Name for uniquely identifying the project
Package Name: Package namespace for your files, this should be unique             across all packages installed on the Android system.
Minimum Required SDK: Lowest version of Android your application supports, to support as many devices as possible, you should set this to the lowest version available that allows your app to provide its core feature.
Target SDK: Indicated the highest version of Android you have tested the application.
Compile With: Indicated the version with using the program is compiled and build.
Theme: Specifies the Android UI for your App.

The Minimum Required SDK, Target SDK & Compile With are noted with the Android API number.

3)      Just Click on Next in Configure Project screen


4)      You can configure the icon for your application in this screen, select any image icon from your computer. This image will display as the icon for your android application and click Next.


5)      In the Create Activity screen click on Next leaving it to the default selected value “Blank Activity”


6)      Now provide the name for your activity, rename that to SayHello and click on Finish.


7)      This will open a screen similar as below,


8)      Under your project folder structure go to res à Values à strings.xml, change the value of the string hello_world to “Hello Kumar”,  i.e  <string name="hello_world">Hello Kumar!</string>

9)      Just Right Click on your project name select Run As à Android Application.


10)   Once the AVD is launched and the project is deployed you should be able to see the application running successfully as below.


If you go back to the application list page you will be able to see your application with the icon that you selected, sample screen shot below.


Finally successfully we have created the hello world application and ran it successfully.



Thursday, 23 October 2014

Setting my machine for Android Development


This tutorial explains how to set up your Windows machine for Android development. It also explains some of the basic things that you need to know when starting with your Android installation.

At the time of writing this article Android Lollipop is the latest version, so most of the tutorials will be based on that. 

Downloading and opening the IDE:

Eclipse is one of the IDE (Integrated Development Environment) which is used to develop Android application. You can download Android SDK (Software Development Kit) with the Eclipse IDE from this link  Android Developer site

Once you download and extract the zip file inside that you should be able to find out folder structure as shown below.



The eclipse folder contains the IDE, the SDK folder contains the Android software. You can go into the eclipse folder and double click on eclipse.exe, this will open the Eclipse IDE and will ask for a default workspace location, and this is where all your code will be saved. Chose a location and click ok. You can change this location later.

Setting the Android SDK:

Once you open the IDE you should be able to see a screen similar to this, once done start the Android SDK Manager either by clicking the Icon or from Windows à Android SDK Manager menu



This will open the SDK manager as below, at this stage you need decide on which version you want your android application to run based on that you need to install SDK Platform and System Image. Below screenshot also shows that I have already installed the Android SDK and the system Image for Android version L this is a preview version, you can use Android 5.0. Once selected click on “Install 6 packages” button (6 may vary based on the items you select).



Note: To test the application in any other version you need to select the appropriate SDK and System Image of that version.
SDK Platform: This is the one which is used to develop the application and test them.
System Image: To run and test the application before deploying in any real Android device, Google provides an option to test it in a Virtual Device for creating the it we need this system image to be available.
AVD: Android Virtual Device are those actual virtual device created using Android System image.

Creating the Emulator:


Once we have completed the above download click on Android Virtual Device Manager icon or Window à Virtual Device Manager as below.


This opens the Android Virtual Device Manager as below, click on the Create button




Provide the following details,
AVD: Name for your device
Device: Any device available in the market to set the height, width and screen resolution.
Target: What’s the target OS that to be running on this device.
CPU/ABI: ARM (as per my knowledge most devices run based on this)
SD Card Size: Give a size for your SD card min size is enough.


Click on Ok, this will create the AVD for you and that will display in the list now you can select the AVD name and click on start. If it shows a Launch Option screen just click ok. Once done you can see your device is starting and getting ready after a couple of minutes you should be able to see the device ready as below.


Alternatively you can create a device by navigating to the tab “Device Definition” in AVD manager, select any existing device and click “Create AVD” which just creates the AVD with pre-configured details.


Finally we have completely set up our machine for Android Development, now lets start with developing the application and run in Android.