72
Two Day Workshop on Android 13/03/2014 1 ANDROID:

ANDROID Workshop Mahesh

Embed Size (px)

DESCRIPTION

android workshop....

Citation preview

  • Two Day Workshop on Android

    13/03/2014

    1

    ANDROID:

  • Two Day Workshop on Android

    13/03/2014

    2

    What is Android?

    Android Is a mobile Operating System developed by Google.

    Android Os is based on open Linux kernal.

    Unlike iPhone Os, Android Os is Open source, meaning the developers can modify and customize

    the os for each phone.

    Developers can create programs for Android by using the Android SDK(Software Development

    Kit).

    Android programs are written in java and run through Googles Davlik virtual machine, which

    optimized for mobile devices.

    Android Architecture :

    The Main Components in the Android Architecture are

    1. Android Application

    2. Application Framework

  • Two Day Workshop on Android

    13/03/2014

    3

    3. Libraries(Core & Native)

    4. Runtime Android (DVM- Dalvik Virtual Machine)

    5. Kernel Linux

    1. Android Applications: These are applications written in Java. Some of basic applications

    includes an calendar, email client, SMS program, maps, making phone calls, accessing the Web

    browser, accessing your contacts list and others.

    2. Application FrameWork: This is the skeleton or framework which all android developers has

    to follow. The developers can access all framework APIs an manage phones basic functions like

    resource allocation, switching between processes or programs, telephone applications, and

    keeping track of the phones physical location.

    3. Libraries: a. Core Libraries: The Android runtime layer which includes set of core java

    libraries and DVM (Dalvik Virtual Machine) is also located in same layer.

    b. Native Libraries: This layer consists of Android libraries written in C, C++, and used by various

    system. These libraries tells the device how to handle different kinds of data and are exposed to Android

    developers via Android Application framework. Some of these libraries includes media , graphics,

    3d,SQLite,web browser library etc.

    4. Runtime Android (Dalvik virtual Machine): This layer includes set of base libraries that are

    required for java libraries. Every Android application gets its own instance of Dalvik virtual machine.

    Dalvik has been written so that a device can run multiple VMs efficiently and it executes files in

    executable (.Dex) optimized for minimum memory.

  • Two Day Workshop on Android

    13/03/2014

    4

    5. Kernel Linux: This layer includes Androids memory management programs, security settings,

    power management software and several drivers for hardware , file system access, networking and inter-

    process-communication. The kernel also acts as an abstraction layer between hardware and the rest of

    the software stack.

    Android Versions:

    First Major version of Android is 1.5 (CupCake) may 2009

    Android 1.6 (Donut)

    Android 2.1(clair)

    Android 2.2(Froyo)

    Android 2.3,2.3.2,2.3.3,.(GingarBread)

    Android 3.1,3.2,3.2.1,3.2.2,3.2.3.(HoneyComb)

    Android 4.0(ice Cream Sandwitch)

    Android Features:

    The following are the advantages of Android

    Application framework enabling reuse and replacement of components

    Dalvik virtual machine optimized for mobile devices

    Optimized graphics

    SQLite for structured data storage

    Media support for common audio, video, and still image formats (MPEG4, H.264, MP3, AAC,

    AMR, JPG, PNG, GIF)

    Android 1.0 (API level 1)

    Android 1.1 (API level 2)

    Android 1.5 Cupcake (API level 3)

    Android 1.6 Donut (API level 4)

    Android 2.0 Eclair (API level 5)

    Android 2.0.1 Eclair (API level 6)

    Android 2.1 Eclair (API level 7)

    Android 2.22.2.3 Froyo (API level 8)

    Android 2.32.3.2 Gingerbread (API level 9)

    Android 2.3.32.3.7 Gingerbread (API level 10)

    2.11 Android 3.0 Honeycomb (API level 11)

    2.12 Android 3.1 Honeycomb (API level 12)

    2.13 Android 3.2 Honeycomb (API level 13)

    2.14 Android 4.04.0.2 Ice Cream Sandwich (API

    level 14)

    2.15 Android 4.0.34.0.4 Ice Cream Sandwich (API

    level 15)

    2.16 Android 4.1 Jelly Bean (API level 16)

    2.17 Android 4.2 Jelly Bean (API level 17)

    2.18 Android 4.3 Jelly Bean (API level 18)

    2.19 Android 4.4 KitKat (API level 19)

    Android 2.3.32.3.7 Gingerbread (API level 10)

    Android 3.0 Honeycomb (API level 11)

    Android 3.1 Honeycomb (API level 12)

    Android 3.2 Honeycomb (API level 13)

    Android 4.04.0.2 Ice Cream Sandwich (API level 14)

    Android 4.0.34.0.4 Ice Cream Sandwich (API level 15)

    Android 4.1 Jelly Bean (API level 16)

    Android 4.2 Jelly Bean (API level 17)

    Android 4.3 Jelly Bean (API level 18)

    Android 4.4 KitKat (API level 19)

    http://en.wikipedia.org/wiki/Android_version_history#Android_1.0_.28API_level_1.29http://en.wikipedia.org/wiki/Android_version_history#Android_1.1_.28API_level_2.29http://en.wikipedia.org/wiki/Android_version_history#Android_1.5_Cupcake_.28API_level_3.29http://en.wikipedia.org/wiki/Android_version_history#Android_1.6_Donut_.28API_level_4.29http://en.wikipedia.org/wiki/Android_version_history#Android_2.0_Eclair_.28API_level_5.29http://en.wikipedia.org/wiki/Android_version_history#Android_2.0.1_Eclair_.28API_level_6.29http://en.wikipedia.org/wiki/Android_version_history#Android_2.1_Eclair_.28API_level_7.29http://en.wikipedia.org/wiki/Android_version_history#Android_2.2.E2.80.932.2.3_Froyo_.28API_level_8.29http://en.wikipedia.org/wiki/Android_version_history#Android_2.3.E2.80.932.3.2_Gingerbread_.28API_level_9.29http://en.wikipedia.org/wiki/Android_version_history#Android_2.3.3.E2.80.932.3.7_Gingerbread_.28API_level_10.29http://en.wikipedia.org/wiki/Android_version_history#Android_3.0_Honeycomb_.28API_level_11.29http://en.wikipedia.org/wiki/Android_version_history#Android_3.1_Honeycomb_.28API_level_12.29http://en.wikipedia.org/wiki/Android_version_history#Android_3.2_Honeycomb_.28API_level_13.29http://en.wikipedia.org/wiki/Android_version_history#Android_4.0.E2.80.934.0.2_Ice_Cream_Sandwich_.28API_level_14.29http://en.wikipedia.org/wiki/Android_version_history#Android_4.0.E2.80.934.0.2_Ice_Cream_Sandwich_.28API_level_14.29http://en.wikipedia.org/wiki/Android_version_history#Android_4.0.3.E2.80.934.0.4_Ice_Cream_Sandwich_.28API_level_15.29http://en.wikipedia.org/wiki/Android_version_history#Android_4.0.3.E2.80.934.0.4_Ice_Cream_Sandwich_.28API_level_15.29http://en.wikipedia.org/wiki/Android_version_history#Android_4.1_Jelly_Bean_.28API_level_16.29http://en.wikipedia.org/wiki/Android_version_history#Android_4.2_Jelly_Bean_.28API_level_17.29http://en.wikipedia.org/wiki/Android_version_history#Android_4.3_Jelly_Bean_.28API_level_18.29http://en.wikipedia.org/wiki/Android_version_history#Android_4.4_KitKat_.28API_level_19.29http://en.wikipedia.org/wiki/Android_version_history#Android_2.3.3.E2.80.932.3.7_Gingerbread_.28API_level_10.29http://en.wikipedia.org/wiki/Android_version_history#Android_3.0_Honeycomb_.28API_level_11.29http://en.wikipedia.org/wiki/Android_version_history#Android_3.1_Honeycomb_.28API_level_12.29http://en.wikipedia.org/wiki/Android_version_history#Android_3.2_Honeycomb_.28API_level_13.29http://en.wikipedia.org/wiki/Android_version_history#Android_4.0.E2.80.934.0.2_Ice_Cream_Sandwich_.28API_level_14.29http://en.wikipedia.org/wiki/Android_version_history#Android_4.0.3.E2.80.934.0.4_Ice_Cream_Sandwich_.28API_level_15.29http://en.wikipedia.org/wiki/Android_version_history#Android_4.1_Jelly_Bean_.28API_level_16.29http://en.wikipedia.org/wiki/Android_version_history#Android_4.2_Jelly_Bean_.28API_level_17.29http://en.wikipedia.org/wiki/Android_version_history#Android_4.3_Jelly_Bean_.28API_level_18.29http://en.wikipedia.org/wiki/Android_version_history#Android_4.4_KitKat_.28API_level_19.29

  • Two Day Workshop on Android

    13/03/2014

    5

    GSM Telephony (hardware dependent),Bluetooth, EDGE, 3G, and WiFi (hardware

    dependent),Camera, GPS, compass, and accelerometer (hardware dependent)

    Rich development environment

    To Create , Test and build Android applications we need the following Softwares:

    1. Eclipse IDE (is optional can use any other tool. But Eclipse is recommended ) + added with

    Android Development plugin

    2. Android SDK(Software Development Kit

    we can download these s/w from this site http://www.android.com

    Required Softwares:

    The android app can be developed on any OS such as Windows, Linux, and MAC Os

    The following are the resources that are required to set up into the system for android application

    development

    1. An IDE (Integrated Development Environment) : The Eclipse is the most prefered IDE. We can

    download the Eclipse IDE from

    the following website. http://www.eclipse.org

    2. Add a plugin making the eclipse aware of Android.

    The Android Development Tool(ADT) is the Eclipse plugin doing this. For this we want to use the

    Install plugin option of the Eclipse IDE.

    http://www.android.com/http://www.eclipse.org/

  • Two Day Workshop on Android

    13/03/2014

    6

    Alternatively we can get the ADT zip file downloaded from http://www.android.com and

    manually copy the features and plugins folders into the eclipse root folder , which we got

    extracting the ADT zip file.

    3. In addition to the IDE and its plugin simplifying creating the android applications we want

    to have an android SDK for building, and testing the android applications, we can download the

    SDK from http://www.android.com After extracting the downloaded zip file for the SDK we need

    to run the SDK Manager whicj is found in the this find & install various

    available packages.

    The Android Application:

    The Android Application is basically composed of the following 3 type of components.

    1. Activity

    2. Service

    3. BroadCast Receiver

    4.Content Providers

    Activity:

    The Activity is the one of the core components of Android App

    This is crated as a Java Object subtype ofandroid.app.Activity

    This component is managed by the Android App Framework

    http://www.android.com/http://www.android.com/android.app.Activity

  • Two Day Workshop on Android

    13/03/2014

    7

    The Following are the possible methods that we can override the Activity Object.

    The onCreate() :

    The onCreate() methos is used to implement initialization code like presenting the View for the

    Activity.

    The onStart():

    The onStart() method allows writing the code executing on getting the activity foreground

    The onRestart() :

    The onRestart() method can initialize the resources that are closed in the onStop().

    The onStop() :

    The onStop() method can use the resources that are not required on paused activity. This may

    even required to solve the start of the activity.

    The onResume() :

  • Two Day Workshop on Android

    13/03/2014

    8

    The onResume() can create the resources and / or get the saved state of the activity to get into

    foreground.

    The onDestroy() : The onDestroy() can perform the finilizations for the activity.

    The Life Cycle of Activity is:

    Or

    Creating an Activity: While creating/starting the activity the following methods are invoked.

    onCreate()

    onStart()

  • Two Day Workshop on Android

    13/03/2014

    9

    onResume()

    Some other Activity wants to come to ForeGround:

    At this stage onPause() of this activity is invoked and then the other activity is started. In

    case of the other activity is taking the complete screen the onScreen() is invoked getting the activity to

    background(stopped). Otherwise it gets paused.

    The Activity is getting into the foreground:

    This activity which is paused or stopped because of some other activity is foreground, is now

    coming foreground because of the existing foreground activity is destroyed.

    At this stage the onResume() is the only method invoked in case of getting from paused.

    If it was stopped the following methods are invoked.

    onRestart()

    onStart()

    onResume()

    The Activity Destroying:

    The Activity while destroying from foreground invokes the following methods.

    onPause()

    onStop()

    onDestroy()

  • Two Day Workshop on Android

    13/03/2014

    10

    Point to Note : The android system can destroy the stopped activity without a user request, just

    invoking onDestroy()

    he Startup Application : For the first time want to take the following points to check

    Install with Android SDK with necessary APIs

    Create a AVD(Android Virtual Device), we can do this using SDK Manager which you find in the

    Android SDK installed.

    Eclipse is installed with ADT Plugin, and for the first time we want to set the Android SDK location

    in Eclipse-window- Preferences.

    Select Android from the left side tree.

    Browse the Android SDK Install Folder

    Eg: d:\android\SDK-windows

    Once Creating the Android project we find the project is created with one activity bydefault.

  • Two Day Workshop on Android

    13/03/2014

    11

    The following are the few important documents or folders to observe.

    Creating an Activity:

    The activity class needs to be a subtype of android.app.Activity

    The onCreate() method is one basic method which minimum we want to override . Like

    we may want to create / locate the View and set it to the Activity.

    The following methods of Activity are used to set the View

    When you create a new Android project, you get several items in the project's root directory:

    src A folder that holds the Java source code

    gen This is where Android's build tools will place source code that they generate. R.java" is a generated class which contains the text and the UI elements. Android projects come with this free class 'R' which is short for Resource. This is an automatically generated class that we can use to reference resources in our project. We should not try to modify this class manually.

    assets A folder that holds other static files you wish packaged with the application for deployment onto the device.

    bin In Eclipse, the ADT plugin incrementally builds our project as we make changes to the source code. Eclipse outputs an .apk file automatically to the bin folder of the project, so we do not have to do anything extra to generate the .apk.

    res A folder that holds resources such as icons, graphic user interface (GUI) layouts, etc. that are packaged with the compiled Java in the application.

    AndroidMainFest.xml An XML file describing the application being built and which components (activities, services, and so on) are being supplied by the application. This file is the foundation for any Android application. This is where you declare what is inside your application. You also indicate how these pieces attach themselves to the overall Android systems; for example, you can indicate which activity or activities should appear on the device's main menu (a.k.a. the launcher). When you create your application, a starter manifest will be generated for you automatically. For a simple application, offering a single activity and nothing else, the auto generated manifest will probably work out fine, or perhaps require a few minor modifications. But on the other spectrum, the manifest file for the Android API demo suite is more that 1,000 lines long. Your production applications will probably falls somewhere in the middle. Most of the manifest will be describes detail in later chapters.

    project.properties Property files used by the Ant build script.

    http://www.bogotobogo.com/Android/android2MyFirstApplication.phphttp://www.bogotobogo.com/Android/android2MyFirstApplication.phphttp://www.bogotobogo.com/Android/android2MyFirstApplication.php

  • Two Day Workshop on Android

    13/03/2014

    12

    o setContentView(View)

    o setContentView(int)

    The first allows to set the View Object may be created in the program here. And the later

    allows setting the view defined in the XML document.

    The FirstActivity.java :

    package com.durgasoft.android;

    import com.durgasoft.android.R;

    import .;

    public class FirstActivity extends Activity {

    @Override

    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    }}

    Main.xml:

  • Two Day Workshop on Android

    13/03/2014

    13

    The android application includes a generated resource file named R which lists all the resources defined with unique identity. And this xml View is also given with a unique id to refer in the program. The id can be accessed using R.layout.Main.

    Thus the activity can have this View set as shown below

    public class FirstActivity extends Activity {

    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    } }

    It is found in most cases creating a complex view it is convenient to go for XML style How ever we can get View created in xml into the activity and do necessary changes .

    Example:

    Public void onCreate(){

    setContentView(R.layout.main);

    TextView tv=(TextView)findViewById(R.id.tv1);

    Tv.setText(New Text); }

    To run the above code could give an error as in the main.xml file the TextView is not specified with any id. To run this above code successfully add the following attribute into the Tag.

    andrioid:id=@+id/tv1

    The + in the value of the attribute describes add the is resource into the R file if not available

    The android application support multiple type of resource such as layouts, ids and Strings The String resource is can be added into strings.xml file res/values folder

    Eg: Text String Message These resources are added into the R file for convenient access. To access the resources in xml documents we use the following syntax.

    Syntax: @/

  • Two Day Workshop on Android

    13/03/2014

    14

    Eg: @String/test

    In case the same is required to access in the program we use. R..

    We can use the following method for getting the string resource declared in the xml.

    String s1=getResources().getString(R.String.test);

    Similar to String we can have a Boolean resource .this is declared using tag.

    Starting an Activity:

    The activity with ACTION_MAIN, and CATEGORY_LAUNCHER is main activity to run on accessing the application.

    In addition we may want to start another activity from such main activity. We use startActivity(Intent) method of the Activity to do this.

    The Intent Object:

    The Intent is a value object describing a message to the android system to perform an action.

    Like we may want to describe the android system to start an activity or background service

    The Intent Object describes following six methods 1. Component Name 4. Data 2. Action 5. Extras 3. Categories 6. Flags

    The Intents are of two types. 1. Explicit Intents 2. Implicit Intents

    Explicit Intents:

    These type of intents are started with component name, which directly locates a Activity by its name. Example: Lets add a new activity in the previous class

    Public class Activity2 extends Activity

    { Public void onCreate(Bundle b)

  • Two Day Workshop on Android

    13/03/2014

    15

    { super.onCreate(b);

    setContentView(R.layout.main1.xml);

    }

    }

    This new Activity is requited to register into the AndroidManifest.xml

    In the existing Activity: Lets consider the main.xml is the layout document and has the following tag.

    The following method needs to added into the existence Activity

    public void myMethod(View view)

    {

    Intent i=new Intent();

    i.setComponentName(new ComponentName(getApplicationContext(),Activity2.class));

    startActivity(i); }

    Implicit Intents:

    Although the explicit intents are simple but are useful only to locate the activities whose names are known to us, which is generally with the activities of our application.

    In case if we want to access the activities of some other applications in the system explicit would not meet our requirement

    In this case the android system is responsible to find the suitable activities to handle this intent. In case if none found the ActivityNotFoundException would be thrown.

  • Two Day Workshop on Android

    13/03/2014

    16

    To do this the intent object is matched with the configured intent filter for the activities .The following tag is used in the tag to configure the intent filter.

    ........................

    Implicit Intent:

    In Case if the Intent without a component is given , the f/w needs to use the package manager conduct the following 3 tests to find the suitable activities that can handle this intent.

    Action:

    Here the intent action is match with the actions of the intent filters of the activities.

    If the intent doesnt has an action(ies it is null) in such case every activity with an intent filter atleast with one action will passes this test.

    Android includes multiple builtin actions such as ACTION_CALL

    We can create our own action, It is recommended to use package name as prefix for the action name. For example

    com.durgasoft.android.GAME_START o Data:

    Once if the activity passes the action test then it is checked for data test. Here the MIME type and / or path is matched to find is the activity matching to handle the intent with the given data.

    o Category:

    The intent and intent filter can have multiple categories added.

    All the categories describes in the intent should match the intent filter categories passing this test.

    Note: The category android.intent.category.DEFAULT is mandatory to include into the intent filter to have any implicit intents locating this activity. This is excempttion for LAUNCHER activity.

    Intent and Intent Filters:

    The intent filters for an activity are declared in the android manifest.xml file as part of configuring the activity.

    The can have , and

  • Two Day Workshop on Android

    13/03/2014

    17

    Note:

    Having at least one is mandatory to choose this activity using implicit intent

    Having the with the namae android.intent.category.DEFAULT is also mandatory for locating using implicit intents. Example for the LAUNCHER and ALTERNATIVE category intent.

    The implicit intents requires to identify the appropriate activity to handle the intent.

    To do this it matches the intent info(such as action, type, data, and category) with the intent filters info of the activity.

    If the intent info matches with the intent filter info then the enclosing activity is chosen to handle this intent Example

    Intent i=new Intent();

    i.setAction(Intent.ACTION_DIAL);

    startActivity(i);

    This starts a phone dialer activity allowing us to dial the number and make a call.

    Intent i=new Intent();

    i.setAction(Intent.ACTION_DIAL);

    Uri.Builder u=new Uri.Builder();

    u.scheme(tel);

    u.path(1234567890);

    i.setData(u.build());

    startActivity(i);

    This starts the phone dialer activity with the number 1234567890 entered directly to make a call.

    Alternative to ACTION_DIAL we can use ACTION_CALL for directly making a call. Intent i=new Intent(); i.setAction(Intent.ACTION_GET_CONTENT);

  • Two Day Workshop on Android

    13/03/2014

    18

    Uri.Builder u=Uri.Builder(); u.scheme(content); u.path(/contact); i.setData(u.build());

    In addition to startActivity() we can use the startActivityForResult() method to start an activity.

    The start ActivityForResult () method is used to start an activity that can carry some data returning to the parent activity.

    This method takes 2 arguments.

    First Arg: Intent

    Second Arg: int(specifies the request code, this is used diffentiate between the multiple child activities that are possible to start from the activity)

    This code is used in onActivityResult() method to find the result from which child activity.

    The child Activity can use the following method for sending the result.

    setResult(int resultcode,Intent data)

    Once the childActivity is finished then the following method of the parent activity is invoked.

    onActivityResult(int requestcode,int resultcode,Intent data)

    Note:

    In Case if the child activity finished without setting the result , the data will be null.

    Sample Program on Intents:

    SecondActiivity.java:

    package com.durgasoft.android;

    import com.durgasoft.android.R;

    import .................................................................;

    public class SecondActivity extends Activity {

    /** Called when the activity is first created. */

  • Two Day Workshop on Android

    13/03/2014

    19

    @Override

    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    }

    // Code for explicit Intents

    public void MyMethod(View view)

    {

    Intent i=new Intent();

    // Register the Activity2 class in the android manifest.xml file inside tag

    //

    i.setComponent(new ComponentName(getApplicationContext(),Activity2.class));

    startActivity(i);

    }

    // Code for implicit Intents

    public void MyMethod1(View view)

    {

    Intent i=new Intent();

    i.setAction(Intent.ACTION_DIAL);

    startActivity(i); } }

  • Two Day Workshop on Android

    13/03/2014

    20

    Activity2.java

    package com.durgasoft.android;

    import --------------------------------------------;

    public class Activity2 extends Activity {

    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main1); } }

    Main.xml

  • Two Day Workshop on Android

    13/03/2014

    21

    Main1.xml

    AndroidManifest.xml

    Understanding the Views:

    The Userinterface of an activity is defined using a View Object.

  • Two Day Workshop on Android

    13/03/2014

    22

    The View group is one special View type that allows us compose multiple Views into a single view, thus we can have multiple views to present in a single screen (ies a single View).

    The following method of an Activity is used to set the View for this Activity. setContentView(android.View.View) setContentView(int ViewID)

    The View can be described in two styles. o Into XML declarative

    o In Activity( Java Code) programmatic. We can use both in combination. It is recommended use XML style , which can simplify creating the View and allows take

    the advantage of first design using click and drag supported by the IDE.

    Usign XML Style: In this case we create an XML documents into res/layouts folder

    An XML document can describe only one View. Note the View here can be a View group thus a tree of Views

    Here we have an XML tag one for each concrete View type to use defining the View. Example:

    Example:

    To set this view as User Interface for the Activity we can have the following code in the onCreate() method of the activity.

    setContentView(R.layout.simpleButton);

    Note:

    The android XML file names cannot have uppercase and special and white space characters.

    If we want have multiple view components into a UI we shall work with ViewGroup such as Layouts.

  • Two Day Workshop on Android

    13/03/2014

    23

    The Linear Layout:

    This supports arranging multiple View components one after the other Vertical/Horizontal.

    The Orientation property of this component specifies is the child View components to arrange in Vertical/Horizontal.

    If vertical only one View component is allowed with each row. If Horizontal- All the Views are arranged into a single row.

    Example:

  • Two Day Workshop on Android

    13/03/2014

    24

    android:layout_height="wrap_content" android:text="E"> The Button:

    We use the android.View.Button class to create this component. Or tag in the XML document. Example: Button b=new Button(this);

    b.setText(Submit); In XML:

    Configuring the Button to listen for Click event:

    Programatic: In Case we use the following method of Button to set the listener for

    onClick event. setOnClickListener(View.onClickListener)

    The View.OnClickListener is an interface that declares only one method. public void onClick(View v)

    This method is invoked by the View component when a user clicks the component.

    We can create a class implementing this interface . most of the time we prepare creating an anonymous class Example: Button b1=new Button(this); OnClickListener l=new OnClickListener(){ public void onClick(View v) { .......................... }; b1.setOnClickListener(l);

    Declarative : This is simple ,here we want to use android:onClick attribute specifying

    the name of the method to listen for this event. The method needs to be implemented in the content of this Buutton , with

    the following signature public void (View v)

  • Two Day Workshop on Android

    13/03/2014

    25

    The Relative Layout: In this case the components in the view can be placed with respect to the other

    components in the view or with respect to this layout (ies parent) view. We can use the following attributes to configure the component align with respect to the

    layout.

    android:layout_alignParentBottom: specifies whether the component is to be placed at the bottom of the layout. true describes to place to the Bottom.

    android:layout_alignParentTop

    android:layout_alignParentLeft

    android:layout_alignParentRight The following attributes can be used to place the component with respect to the another

    components.

    android:layout_below : specifies the id of the component below which this component has to be arranged.

    android:layout_toLeftOf

    android:layout_toRightOf

    Example:

  • Two Day Workshop on Android

    13/03/2014

    26

    Sample Program on Relative Layout & Button: package com.durgasoft.android; import com.durgasoft.android.R; import ----------------------------------------------; public class FourthActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button b1=(Button)findViewById(R.id.b1); b1.setOnClickListener(new OnClickListener() { public void onClick(View v) { Toast.makeText(getApplicationContext(),"Hi This is From Button",Toast.LENGTH_LONG).show(); }}); } } Main.xml:

  • Two Day Workshop on Android

    13/03/2014

    27

    android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="This is the Activity from Relative Layout" android:id="@+id/tv2" > The EditText:

    This is a text field that allows taking the text content input from the user.

    Example: In The Activity Class: public void onClickB1(View v) { EditText v1=(EditText)findViewById(R.id.v1); String value=v1.getText().toString();

    Toast.makeText(getApplicationContext(), value, Toast.LENGH_LONG).show();

    } View ViewGroup TextView LinearLayout EditText RelativeLayout Button TableLayout ToggleButton FrameLayout CheckBox ListView RadioButton ScrollView Spinner TableView DatePicker RadioGroup

  • Two Day Workshop on Android

    13/03/2014

    28

    TimePicker ProgressBar DigitalTime ImageButton AnalogTime Image The TextView autolink option ,this is used to have links automatically created for the phone numbers , email ids and website address supporting us to click performing necessary action. We use android:autolink attribute to configure this. This defaults to none, and we can specify phone, email, web, map, or all. The AutoCompleteTextView:

    This is a subtype of EditView , this allows us get the help content listing to choose the values from . we can use the following tag to declare this component.

    Example: In the Activity onCreate() method we can have the following code for describing the autocomplete words. AutoCompleteTextView act=(AutoCompleteTextView)findViewById(R.id.act1); String[] str=new String[]{"SVU","OU","JNTUK","JNTUH","ANDHRA","SKU","YVU","VSU","PALAMURU","MAHATMA","OTHER"}; ArrayAdapter< String> aa=new ArrayAdapter(getApplicationContext(),android.R.layout.simple_dropdown_item_1line,str); act.setThreshold(1); act.setAdapter(aa); The Toggle Button:

    This is a subtype of button , this is a special type similar to the CheckBox allowing us present the a view taking data like yes or no from the user.

    We use the following tag to have this view.

  • Two Day Workshop on Android

    13/03/2014

    29

    android:layout_height="wrap_content" android:taxtOn=yes android:textOff=No/>

    The android:textOn specifies the text to display when this button Check (ies on) and textOff for content to displaying on unchecked(ies off).

    The CheckBox:

    This is also a subtype of button allows us to take checked/unchecked decisions from the user.

    We use the following tag to declare this view.

    In the activity class we can have the following method. public void CheckBox(View view) { CheckBox cb1,cb2; cb1=(CheckBox)findViewById(R.id.cb1); cb2=(CheckBox)findViewById(R.id.cb2); if(cb1.isChecked()) { Toast.makeText(getApplicationContext(), "MCA is Selectd",Toast.LENGTH_LONG).show(); } else if(cb2.isChecked()) { Toast.makeText(getApplicationContext(), "BTech is Selectd",Toast.LENGTH_LONG).show(); } } The RadioButton & Radio Group:

    The RadioGroup allows having multiple RadioButtons to choose between This allows setting

    onCheckedChangeListener() Where this listener support only one method

    onCheckedChange(RadioGroup, int) The second arfument described that id of the checked radio button , and -1 in case of the clearing the check of the group.

  • Two Day Workshop on Android

    13/03/2014

    30

    To make none of the radio button to check we can use clearCheck() method of RadioGroup.

    In XML Document: In The Activity Class: public void RadioBox(View view) RadioButton rb1,rb2; rb1=(RadioButton)findViewById(R.id.rb1); rb2=(RadioButton)findViewById(R.id.rb2); if(rb1.isChecked()) { Toast.makeText(getApplicationContext(), "male is Selectd",Toast.LENGTH_LONG).show(); }else if(rb2.isChecked()) {Toast.makeText(getApplicationContext(), "Female is Selectd",Toast.LENGTH_LONG).show(); } } The Spinner:

    This is a list box type allowing us to choose between the given values. We use the following tag for defining this type of View.

    We can add the String array resources using the following tag.

  • Two Day Workshop on Android

    13/03/2014

    31

    Value1 Value2

    Now we want to set the values for the spinner we write the following code in the activity class onCreate() method. String values[]=getResources.getStringArray(R.array.myarray); ArrayAdapter aa=new ArrayAdapter(getApplicationContext(),android.R.layout.simple_list_item,values); Spinner sp1=(Spinner)findViewById(R.id.sp1); sp1.setAdapter(aa); we can add these entries declaratively also using the following attribute android:entries=@array/myarray We can have a OnItemSelectedListener configured to this component, This supports the following method. onItemSelectedListener(AdapterView v,View selectedView, int position,long len) we use setOnItemSelectedListener(OnItemSelectedListener) method of Spinner to set this listener. The Scroll View :

    This allows us define the view with large height like may be with many components into it. We use tag to describe having the Scroll support.

    The ListView:

    This View allows us to have set of values to list.We use tag to define this view. Example: Add the following tag in main layout. In the onCreate() method of the activity we can have the following code for setting a list of values.

    ListView lv=(lv)findViewById(R.id.mylist); String values[]={value1,value2}; ArrayAdapter aa=new ArrayAdapter(getApplicationContext(),android.R.layout.simple_list_item,values); lv.setAdapter(aa);

  • Two Day Workshop on Android

    13/03/2014

    32

    The onItemClickListener: We can configure this listener to the ListView this declares only one method.

    public void onItemClickListener(AdapterView Parent,View v,int position,long id ) we can have a text filtering for the ListView we can be enable using the following method of the

    ListView. setTextFilterEnabled(Boolean)

    we can use ListActivity as a utility for creating the Activity that just needs a ListView as a View. public class MyActivity extends ListActivity { public void onCreate(Bundle b)

    { super.onCreate(b); ListView lv=getListView();

    .. } }

    The GridView:

    This is similar to the ListView , but supports arranging the elements into rows and columns.

    The following tag is used to define this View.

    We use android:numColumns attribute specifying the number of columns, and the number of rows is decided decided based on the items.

    Like done with the ListView we set the adapter for the items,and can set thee OnItemClickListenr

    The DatePicker: This allows us to have a view that can take the date from the user. The following tag is

    used to configure this view And the init() method of the DatePickerDialog is used to set

    the initiated date and the onDateChangedListener. If the method is not invoked it by default sets the date to the system date.

    The TimePicker:

  • Two Day Workshop on Android

    13/03/2014

    33

    Similar to the DatePicker this view allows us to select the time that includes hours and minutes.

    This is alsosupported with a listener to get the notification on the change in the time, just like with DatePicker, this supports onTimeChangedListener with one method described below. void onTimeChanged(TimePicker,int hours,int minutes)

    Progress Bar:

    This is the View that supports to describe the end user that some long process is being taking up and you may want to wait for completing process.

    We generally can categorize the Progress Bar into two types. 1.Indetermine ProgressBar 2. Determine ProgressBar Indetermine ProgressBar: In this case the progress bar doesnt describes the status of the work completed and/or the balance work, this is used in case if we are not known like that amount of work is completed and how much still balance. Determined ProgressBar: The following tag is used to describe the progress bar, and by default this is Indeterminent. We use the setVisibility(int) method to show or make this View invisible . like may be once the long running work is got completed . we can make this invisible. Example: ProgressBar pb=(ProgressBar)findViewById(R.id.pb); pb.setVisibility(ProgressBar.GONE);

    we can have this progress bar on the title bar itself . To have this we want to request for the respective window feature. We use the following code in the activity before setting the ContentView to do this. requestWindowFeature(Window.FEATURE_INDETERMINE_PROGRESS)

    (before setContentView(.............)) And the following method of the Activity can support us to show the visibility of

    this feature. setProgressBarIndeterminate Visibility(boolean)

    Note : This method e want to use after setting the ContentView Similarly we have determinate ProgressBar also on to the title bar. For this we

    want to request for the following window Feature.

  • Two Day Workshop on Android

    13/03/2014

    34

    requestWindowFeature(Window.FEATURE_PROGRESS); And same like earlier we use the following method for setting the visibility of this

    view. setProgressBarVisibility(boolean)

    In addition here we can set the progress using the following method of activity. setProgress(int)

    The maximum progress is defined as 10000. Meaning 5000 progress values describes 50% of progress.

    Sample Program on all Views: FifthActivity.java package com.durgasoft.android; import ; public class FifthActivity extends Activity { private static int DATE_PICKER_DIALOG=1; private static int TIME_PICKER_DIALOG=2; /* Example for All The View ---> EditText,Buttons, Radio Buttons,CheckBox,Spinners,ToggleButtons, AutoCompleteTextView,DatePickerDialog,TimePickerDialog AnalogTime,ScrollView,ProgressBar,ImageButton,ListView,RadioGroup */ /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); AutoCompleteTextView act; act=(AutoCompleteTextView)findViewById(R.id.act1); String[] str=new String[]{"SVU","OU",,"SKU","YVU",}; ArrayAdapter< String> aa=new ArrayAdapter(getApplicationContext(),android.R.layout.simple_dropdown_item_1line,str); act.setThreshold(1); act.setAdapter(aa); Spinner sp1=(Spinner)findViewById(R.id.sp1); String[] str1=getResources().getStringArray(R.array.myarray);

  • Two Day Workshop on Android

    13/03/2014

    35

    ArrayAdapter< String> aa1=new ArrayAdapter(getApplicationContext(),android.R.layout.simple_dropdown_item_1line,str1) sp1.setAdapter(aa1); } public void CheckBox(View view) { CheckBox cb1,cb2; cb1=(CheckBox)findViewById(R.id.cb1); cb2=(CheckBox)findViewById(R.id.cb2); if(cb1.isChecked()) { Toast.makeText(getApplicationContext(), "MCA is Selectd",Toast.LENGTH_LONG).show(); } else if(cb2.isChecked()) { Toast.makeText(getApplicationContext(), "BTech is Selectd",Toast.LENGTH_LONG).show(); } } public void RadioBox(View view) { RadioButton rb1,rb2; rb1=(RadioButton)findViewById(R.id.rb1); rb2=(RadioButton)findViewById(R.id.rb2); if(rb1.isChecked()) { Toast.makeText(getApplicationContext(), "male is Selectd",Toast.LENGTH_LONG).show(); } else if(rb2.isChecked()) { Toast.makeText(getApplicationContext(), "Female is Selectd",Toast.LENGTH_LONG).show(); } } public Dialog onCreateDialog(int index) { if(index==DATE_PICKER_DIALOG) { OnDateSetListener dl=new OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

  • Two Day Workshop on Android

    13/03/2014

    36

    Button b1=(Button)findViewById(R.id.dp); b1.setText(dayOfMonth+"-"+(monthOfYear+1)+"-"+year); } }; DatePickerDialog dpd=new DatePickerDialog(this,dl,2012,04,24); return dpd; } else if(index==TIME_PICKER_DIALOG) { OnTimeSetListener tl=new OnTimeSetListener() { public void onTimeSet(TimePicker view, int hourOfDay, int minute) { Button b1=(Button)findViewById(R.id.tp); b1.setText(hourOfDay+"-"+minute); } }; TimePickerDialog tpd=new TimePickerDialog(this,tl,10,12,false); return tpd; } return null; } public void StartDialog(View view) { showDialog(DATE_PICKER_DIALOG); } public void TimeDialog(View view) { showDialog(TIME_PICKER_DIALOG); }} The Main.xml:

  • Two Day Workshop on Android

    13/03/2014

    37

  • Two Day Workshop on Android

    13/03/2014

    38

    android:text="Female" android:onClick="RadioBox" >

    Dialog Box:

    The android.app.DialogInterface is the base interface representing any dialog. The android.app.Dialog class supports declaring a dialog . This is the base class for

    any dialog. Example:

    Dialog d=new Dialog(this); d.setContentView(R.layout.dialog_layout);

    The dialog_layout describes the view for the dialog just as done for the activity. d.setOwnerActivity(MyActivity,this); d.show(); // This will show the dialog we can add onCancelListener and onDismissListeners set to the Dialog. We use any of the following methods of Dialog to choose the dialog box. Cancel(); Dismiss(); Android includes the following builtin dialogs implementation simplifying creating the dialog box for most common requirements.

  • Two Day Workshop on Android

    13/03/2014

    39

    The AlertDialog: This supports us to create a dialog that meets the most common requirement of having a dialog for showing some alert, this includes

    - A Optional Title - Message Text - Zero, one, two, or three buttons - List of items We use a AlertDialog.Builder object to crate this Dialog . The following methods of this object allows us setting the details for the dialog.

    - setTitle(String) - setMessage(String) - setPositiveButton(String lable,DialogInterface.OnClickLIstener listener) - setNegiveeButton(String lable,DialogInterface.OnClickLIstener listener) - setNutralButton(String lable,DialogInterface.OnClickLIstener listener) - setItems(String[]) Once setting all the details , we can invoke create() method for the AlertDialog object and further show() method for showing. The following methods of Activity can be used to show and remove the Dialog boxes.

    showDialog(int): This shows the Dialog.

    removeDialog(int): Removes the dialog from the Activity

    The OnCreateDialog(int): method is invoked for the first time when a dialog is requested to show. This method is responsible to create a dialog for the given index to show.

    The onPrepareDialog(int): method is invoked each time(including firsttime) when a dialog is required to show.

    Note: The Activity retains the state of the dialog even on cancelled / dismiss of the dialog is requested to show again . However invoking remove Dialog(int) will release the dialog state with the activity.

    The Menu:

    Alert Dialog

    ProgressBar Dialog

    DatePicker Dialog

    TimePicker Dialog

  • Two Day Workshop on Android

    13/03/2014

    40

    The following methods Activity are invoked to create the menu for the activity. OnCreateOptionsMenu(menu): This method is invoked for the first time the user clicks on the menu for the activity.

    Note: From Android 3.0 this is invoked at the time starting the Activity as the menu here is always visible. OnPrepareOptionsMenu(menu): This is called each time when the menu is required to be show. To Listen for the menu item click we can override the following method. boolean onMenuItemSelected(int featureId,MenuItem m) Sample Program on Dialog Boxes and Menus: package com.durgasoft.android; import ......................................................................; public class DialogsExampleActivity extends Activity { private EditText time_et; private Button date_button; // Example for Dialog Boxes and the Menu @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); time_et=(EditText)findViewById(R.id.time_et); date_button=(Button)findViewById(R.id.b2); } private static int BASIC_DIALOG=1; private static int DATE_PICKER_DIALOG=2; private static int TIME_PICKER_DIALOG=3; private static int ALERT_DIALOG1=4; private static int ALERT_DIALOG2=5;

  • Two Day Workshop on Android

    13/03/2014

    41

    public void button1Click(View v){ // Remove the comments One by One and check the result //showDialog(BASIC_DIALOG); //showDialog(ALERT_DIALOG2); showDialog(ALERT_DIALOG1); ; } public void button2Click(View v){ showDialog(DATE_PICKER_DIALOG); } public void button3Click(View v){ showDialog(TIME_PICKER_DIALOG); } public Dialog onCreateDialog(int index){ if(index==BASIC_DIALOG){ final Dialog d=new Dialog(this); d.setContentView(R.layout.dialog1_layout); Button b=(Button)d.findViewById(R.id.b2); b.setOnClickListener( new View.OnClickListener() { public void onClick(View v) { d.dismiss();} }); return d; }else if (index==DATE_PICKER_DIALOG){ OnDateSetListener dl= new OnDateSetListener() { public void onDateSet( DatePicker view, int year, int monthOfYear, int dayOfMonth) { Toast.makeText(getApplicationContext(), "Date : "+dayOfMonth+"-"+(monthOfYear+1)+"-"+year, Toast.LENGTH_SHORT).show(); date_button.setText("New : "+ dayOfMonth+"-"+(monthOfYear+1)+"-"+year); } };

  • Two Day Workshop on Android

    13/03/2014

    42

    DatePickerDialog dpd=new DatePickerDialog(this, dl, 2011, 10, 12); return dpd; }else if (index==TIME_PICKER_DIALOG){ OnTimeSetListener dl=new OnTimeSetListener() { public void onTimeSet(TimePicker tp, int arg1,int arg2) { Toast.makeText(getApplicationContext(), "Time : "+arg1+":"+arg2, Toast.LENGTH_SHORT).show(); String text=""; if (arg1

  • Two Day Workshop on Android

    13/03/2014

    43

    Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show(); } }; AlertDialog.Builder ab= new AlertDialog.Builder(this); ab.setTitle("Alert Dialog Sample"); ab.setMessage("You opened AlertDialog"); ab.setPositiveButton("OK", listener); //ab.setNegativeButton("Not OK", listener); //ab.setNeutralButton("Neutral", listener); return ab.create(); }else if (index == ALERT_DIALOG2){ AlertDialog.Builder ab=new AlertDialog.Builder(this); ab.setTitle("Alert Dialog Sample"); final String[] items={"Abc1", "Abc2","Abc3", "Abc4"}; DialogInterface.OnClickListener listener= new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int which) { Toast.makeText( getApplicationContext(), items[which], Toast.LENGTH_SHORT).show(); dialog.dismiss(); } }; ab.setItems(items, listener); return ab.create(); }else{ return null; } } public void onPrepareDialog(int index, Dialog d){ if (index==BASIC_DIALOG){ EditText ev=(EditText)d.findViewById(R.id.et1); TextView tv=(TextView)d.findViewById(R.id.tv1); tv.setText(tv.getText()+":"+ ev.getText());

  • Two Day Workshop on Android

    13/03/2014

    44

    } } @Override public boolean onCreateOptionsMenu( Menu menu) { MenuInflater mi=new MenuInflater(this); mi.inflate(R.menu.menu1, menu); return true; } @Override public boolean onMenuItemSelected( int featureId, MenuItem item) { Toast.makeText(getApplicationContext(), item.getTitle(), Toast.LENGTH_SHORT).show(); return true; } } Main.xml:

  • Two Day Workshop on Android

    13/03/2014

    45

    android:orientation="horizontal"> dialog1_layout.xml:

  • Two Day Workshop on Android

    13/03/2014

    46

    android:layout_width="match_parent" android:layout_height="wrap_content" android:text="This is a dialog box" > my_tabs_view.xml:

  • Two Day Workshop on Android

    13/03/2014

    47

    android:layout_width="match_parent" android:layout_height="match_parent" /> Menu1.xml: Storage Methods: 1. Shared Preferences 2. SQLite Databse 3. XML 1). Shared Preferences : Interface for accessing and modifying preference data returned by getSharedPreferences(String, int). SharedPreferences

    spf=getSharedPreferences("mypreferences",Context.MODE_PRIVATE); SharedPreferences.Editor Interface used for modifying values in a SharedPreferences object. Create a new Editor for these preferences, through which you can make modifications to the data in the

  • Two Day Workshop on Android

    13/03/2014

    48

    preferences and atomically commit those changes back to the SharedPreferences object. SharedPreferences.Editor editor=spf.edit(); Note : to get the data from shared prefernces shared prefrences object is enough but to insert data or to modify data we need to create Shared Preferences.Editor Object. The data is stored using key,value pairs you need pass a unique key for each value and you can insert Boolean, Float , Long , String , int data type values. Sample Program on Shared Preferences : main.xml < EditText android:id="@+id/editText1" android:layout_width="100dp" android:layout_height="wrap_content" android:layout_alignBottom="@+id/textView1" android:layout_marginLeft="27dp" android:layout_toRightOf="@+id/textView1" > < EditText android:id="@+id/editText2" android:layout_width="100dp" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/textView2" android:layout_alignBottom="@+id/textView2" android:layout_alignLeft="@+id/editText1" />

  • Two Day Workshop on Android

    13/03/2014

    49

    TestProjectActivity.java package com.mahesh.test; import ................; public class TestProjectActivity extends Activity { SharedPreferences spf; SharedPreferences.Editor spe; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); spf=getSharedPreferences("myprefs", Context.MODE_PRIVATE); spe=spf.edit(); } public void Save(View v){ EditText et1=(EditText)findViewById(R.id.editText1); EditText et2=(EditText)findViewById(R.id.editText2); spe.putString("name", et1.getText().toString()); spe.putString("pass", et2.getText().toString()); spe.commit(); } public void getDetails(View v){ String name=spf.getString("name","There is no value with this key"); String pass=spf.getString("pass", "There is no value with this key"); Toast.makeText(getApplicationContext(),"User Name is :"+name+" Pass is :"+pass ,Toast.LENGTH_LONG ).show(); } } to explore persisted shared preferences select DDMS-data-data-select your package open shared

    preferences you will get an xml with the preferences name. 2). SQLite DataBase : SQLiteDatabase has methods to create, delete, execute SQL commands, and perform other common database management tasks. Note : Database names must be unique within an application, not across all applications. openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory) Equivalent to openDatabase(path, factory, CREATE_IF_NECESSARY). Is used to create the SQLite Object if the data base is not available creates a new database if database is already available then it opens the database . SQLiteDatabase db=openOrCreateDatabase("mydb",Context.MODE_PRIVATE, null); Cursor : This interface provides random read-write access to the result set returned by a database query. db.execSQL("create table employee(eid varchar2(20),ename varchar2(20),desig varchar2(20),dept varchar2(20));"); This statement creates a new table with employee if table is not there it will create a new table. If table is already available it will through u an exception u need to handle it. try{ db.execSQL("create table employee(eid varchar2(20),ename varchar2(20),desig varchar2(20),dept varchar2(20));"); }catch(Exception e){e.printStackTrace();} Sample Program on SQLite Database : sqlite.xml

  • Two Day Workshop on Android

    13/03/2014

    50

    < EditText android:id="@+id/editText1" android:layout_width="100dp" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignTop="@+id/textView1" android:layout_marginLeft="35dp" android:layout_toRightOf="@+id/textView2" > < EditText android:id="@+id/editText2" android:layout_width="100dp" android:layout_height="wrap_content" android:layout_alignLeft="@+id/editText1" android:layout_alignParentRight="true" android:layout_alignTop="@+id/textView2" /> < EditText android:id="@+id/editText3" android:layout_width="100dp" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/textView3" android:layout_alignBottom="@+id/textView3" android:layout_alignLeft="@+id/editText2" android:layout_alignParentRight="true" /> < EditText android:id="@+id/editText4" android:layout_width="100dp" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/textView4"

  • Two Day Workshop on Android

    13/03/2014

    51

    android:layout_alignBottom="@+id/textView4" android:layout_alignLeft="@+id/editText3" android:layout_alignParentRight="true" /> TestProjectActivity .java sqlite.xml :

  • Two Day Workshop on Android

    13/03/2014

    52

    android:layout_alignParentLeft="true" android:layout_below="@+id/textView2" android:layout_marginTop="54dp" android:text = "Desig :" android:textAppearance="?android:attr/textAppearanceMedium" /> < EditText android:id="@+id/editText1" android:layout_width="100dp" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignTop="@+id/textView1" android:layout_marginLeft="35dp" android:layout_toRightOf="@+id/textView2" > < EditText android:id="@+id/editText2" android:layout_width="100dp" android:layout_height="wrap_content" android:layout_alignLeft="@+id/editText1" android:layout_alignParentRight="true" android:layout_alignTop="@+id/textView2" /> < EditText android:id="@+id/editText3" android:layout_width="100dp" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/textView3" android:layout_alignBottom="@+id/textView3" android:layout_alignLeft="@+id/editText2" android:layout_alignParentRight="true" /> < EditText android:id="@+id/editText4" android:layout_width="100dp" android:layout_height="wrap_content" android:layout_alignLeft="@+id/editText3" android:layout_alignParentRight="true" android:layout_centerVertical="true" />

  • Two Day Workshop on Android

    13/03/2014

    53

    android:layout_below="@+id/button2" android:onClick="Delete" android:text = "Delete" /> TestProjectActivity. Java package com.mahesh.test; import ............; public class TestProjectActivity extends Activity { SQLiteDatabase db; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sqlite); db=openOrCreateDatabase("mydb",Context.MODE_PRIVATE, null); try{ db.execSQL("create table employee(eid varchar2(20),ename varchar2(20),desig varchar2(20),dept varchar2(20));"); }catch(Exception e){ e.printStackTrace(); } } public void Insert(View v){ EditText et1,et2,et3,et4; et1=(EditText)findViewById(R.id.editText1); et2=(EditText)findViewById(R.id.editText2); et3=(EditText)findViewById(R.id.editText3); et4=(EditText)findViewById(R.id.editText4); ContentValues cv=new ContentValues(); cv.put("eid",et1.getText().toString()); cv.put("ename", et2.getText().toString()); cv.put("desig", et3.getText().toString()); cv.put("dept", et4.getText().toString()); db.insert("employee",null,cv);

    et1.setText(""); et2.setText(""); et3.setText(""); et4.setText(""); } public void Update(View v){ EditText et1,et2,et3,et4; et1=(EditText)findViewById(R.id.editText1); et2=(EditText)findViewById(R.id.editText2); et3=(EditText)findViewById(R.id.editText3); et4=(EditText)findViewById(R.id.editText4); ContentValues cv=new ContentValues(); cv.put("ename", et2.getText().toString()); cv.put("desig", et3.getText().toString()); cv.put("dept", et4.getText().toString()); db.update("employee", cv, "eid=?", new String[]{et1.getText().toString()}); et1.setText(""); et2.setText(""); et3.setText(""); et4.setText(""); } public void Delete(View v){ EditText et1; et1=(EditText)findViewById(R.id.editText1); db.delete("employee", "eid=?", new String[]{et1.getText().toString()}); et1.setText(""); } public void getDetails(View v){ EditText et1; et1=(EditText)findViewById(R.id.editText1); Cursor c=db.query("employee", new String[]{"eid","ename","desig","dept"}, "eid=?", new String[]{et1.getText().toString()}, null, null, null); while (c.moveToNext()) {

  • Two Day Workshop on Android

    13/03/2014

    54

    Toast.makeText(getApplicationContext(), "Eid is :"+c.getString(0)+"\n Ename is :"+c.getString(1)+"\n Desig is :"+c.getString(2)+"\n Dept is :"+c.getString(3),Toast.LENGTH_LONG).show(); } } } If you want explore the db file select DDMS- data data select your package inside package u will find a database folder and select u r db file u can pull that one to ur system by selecting pull a file from the device icon . SQLite browser is used to explore your sqlite dbfile . Using XML : You can persist the data as a XML file . The advantage if u persist the data in xml u can store the data into ur external and internal storage and xml interapable language . If you want share your to some other technologies use XML format. To read and write the data into xml file we need XML parsers. There are two types of parser are available 1). JAXP ( DOM (read-write) , SAX (Read-only)) 2). JAXB Android does not support JAXB. For the above Activity instead of persisting the data into SQLite we will store the data in to XML Working with DOM : to run this application u need to add the below permission in the AndroidManifest.xml file

    Before run this application u need to create a xml file in your sdcard as the following structure mnt/sdcard/xml/ Employees.xml with root tag as package com.mahesh.test; import java.io.File; import .........................; public class TestProjectActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sqlite); } public void Insert(View v){ try{ EditText et1,et2,et3,et4; et1=(EditText)findViewById(R.id.editText1); et2=(EditText)findViewById(R.id.editText2); et3=(EditText)findViewById(R.id.editText3); et4=(EditText)findViewById(R.id.editText4); DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); DocumentBuilder db=dbf.newDocumentBuilder(); File f=new File(Environment.getExternalStorageDirectory()+"/xml/Employees.xml"); // to parse the file there xml file should be available with root tag < /employees> otherwise create a new document element Document d=db.parse(f); Element e1=d.createElement("employee"); Element e2=d.createElement("eid"); Element e3=d.createElement("ename"); Element e4=d.createElement("desig");

  • Two Day Workshop on Android

    13/03/2014

    55

    Element e5=d.createElement("dept"); String eid,ename,desig,dept; eid=et1.getText().toString(); ename=et2.getText().toString(); desig=et3.getText().toString(); dept=et4.getText().toString(); Node n1=d.createTextNode(eid); Node n2=d.createTextNode(ename); Node n3=d.createTextNode(desig); Node n4=d.createTextNode(dept); e2.appendChild(n1); e3.appendChild(n2); e4.appendChild(n3); e5.appendChild(n4); e1.appendChild(e2); e1.appendChild(e3); e1.appendChild(e4); e1.appendChild(e5); d.getDocumentElement().appendChild(e1); TransformerFactory tfr=TransformerFactory.newInstance(); Transformer tf=tfr.newTransformer(); DOMSource ds=new DOMSource(d); // AssetManager am=getAssets(); StreamResult sr=new StreamResult(f); // StreamResult sr=new StreamResult(openFileOutput("Employees.xml",Context.MODE_WORLD_WRITEABLE)); tf.transform(ds, sr); et1.setText(""); et2.setText(""); et3.setText(""); et4.setText(""); }catch(Exception e){ e.printStackTrace(); } } public void Update(View v){

    // Note : i want to update the data whose name is mahesh i want change the data to Rajesh try{ DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); DocumentBuilder db=dbf.newDocumentBuilder(); File f=new File(Environment.getExternalStorageDirectory()+"/xml/Employees.xml"); // to parse the file there xml file should be available with root tag < /employees> otherwise create a new document element Document d=db.parse(f); NodeList nl=d.getElementsByTagName("ename"); for(int i=0;i

  • Two Day Workshop on Android

    13/03/2014

    56

    public void Delete(View v){ // i want remove the ename from the employee record whose name is Rajesh try{ DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); DocumentBuilder db=dbf.newDocumentBuilder(); File f=new File(Environment.getExternalStorageDirectory()+"/xml/Employees.xml"); // to parse the file there xml file should be available with root tag < /employees> otherwise create a new document element Document d=db.parse(f); NodeList nl=d.getElementsByTagName("employee"); for(int i=0;i

  • Two Day Workshop on Android

    13/03/2014

    57

    Before performing delete operation after delete operation SAX Parser : SAX Parser is the read only parser compare to DOM Parser reading the data using SAX Parser is easy and having move advantages than DOM Parser . Code to get the data using SAX Parser : add this method in the previous example public void getDataUsingSAX(View v){ try{ File f=new File(Environment.getExternalStorageDirectory()+"/xml/Employees.xml"); SAXParserFactory spf=SAXParserFactory.newInstance(); SAXParser sp=spf.newSAXParser(); sp.parse(f, new DefaultHandler(){ Boolean eid,ename,desig,dept; @Override public void characters(char[] ch, int start, int length) throws SAXException { // TODO Auto-generated method stub super.characters(ch, start, length); if(eid){ Toast.makeText(getApplicationContext(), "Employee id is :"+new String(ch, start, length), Toast.LENGTH_SHORT).show(); } if(ename){ Toast.makeText(getApplicationContext(), "Employee Name is :"+new String(ch, start, length), Toast.LENGTH_SHORT).show(); } if(desig){

    Toast.makeText(getApplicationContext(), "Employee Desig is :"+new String(ch, start, length), Toast.LENGTH_SHORT).show(); } if(dept){ Toast.makeText(getApplicationContext(), "Employee Dept is :"+new String(ch, start, length), Toast.LENGTH_SHORT).show(); } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { // TODO Auto-generated method stub super.endElement(uri, localName, qName); if(qName.equals("eid")){ eid=false; } if(qName.equals("ename")){ ename=false; } if(qName.equals("desig")){ desig=false; } if(qName.equals("dept")){ dept=false; } } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { // TODO Auto-generated method stub

  • Two Day Workshop on Android

    13/03/2014

    58

    super.startElement(uri, localName, qName, attributes); System.out.println(qName); if(qName.equals("eid")){ eid=true; } if(qName.equals("ename")){ ename=true; } if(qName.equals("desig")){ desig=true; } if(qName.equals("dept")){ dept=true; } } }); }catch(Exception e){ e.printStackTrace(); } } Android With Restful WebServices Communication : Android SDK inbuild is having supporting libraries to communicate with Restful WebServices Sample code to interact With Restful WebServices : (My Intension is I will pass two parameters to server, get the response from the server display the response message using Toast) login.xml < EditText android:id="@+id/editText1" android:layout_width="100dp" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/textView1" android:layout_alignBottom="@+id/textView1" android:layout_toRightOf="@+id/button1" >

  • Two Day Workshop on Android

    13/03/2014

    59

    < EditText android:id="@+id/editText2" android:layout_width="100dp" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/textView2" android:layout_alignBottom="@+id/textView2" android:layout_toRightOf="@+id/button1" /> WebServicesTest . Java package com.mahesh.xml; import ........................; public class WebServicesTest extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void Login(View v){ try{ // Calling Restful WebServices as a path Params DefaultHttpClient httpClient=new DefaultHttpClient(); // we need to add the request type get | post if it is a get request call HttpGet if it is Post request HttpPost // Here specify your webservice URL address my web service is running on this IPAddress and the port Number and i am passing the parameters as a path parameters HttpGet get=new HttpGet("http://192.168.137.1:8888//rest/welcome/mahesh/bened"); /* In case of Query Paramaters

    * HttpGet get=new HttpGet("http://192.168.137.1:8888//rest/welcome? name=mahesh&pass=bened); * * InCase of Matrix Parameters * * HttpGet get=new HttpGet("http://192.168.137.1:8888//rest/welcome/name:mahesh;pass=bened); * */ // Here I am getting the text/plain as a response we need add as header get.addHeader("accept", "text/plain"); /* * Header are different based on your response if your getting a image file * get.addHeader("accept","image/jpg"); * if ur getting a XML as Output * get.Header("accept","application/xml"); * if ur getting a JSON as Output * get.Header("accept","application/json"); */ HttpResponse response=httpClient.execute(get); InputStream isr=response.getEntity().getContent(); int i=isr.read(); String msg=""; while(i!=-1){ msg=msg+(char)i; i=isr.read(); } Toast.makeText(getApplicationContext(), "Response from the server is :"+msg, Toast.LENGTH_LONG).show(); }catch(Exception e){ e.printStackTrace();

  • Two Day Workshop on Android

    13/03/2014

    60

    } } } If you are calling a Java or Other WebComponent : public void Login(View v){ URL u=new URL("http://192.168.137.1:8888//Android?uname=mahesh&pass=bened"); InputStream isr=response.getEntity().getContent(); int i=isr.read(); String msg=""; while(i!=-1){ msg=msg+(char)i; i=isr.read(); } Toast.makeText(getApplicationContext(), "Response from the server is :"+msg, Toast.LENGTH_LONG).show(); } To Work with above application you need add the following permissions in the AndroidManifest.xml file Working With WebView: A View that displays web pages. This class is the basis upon which you can roll your own web browser or simply display some online content within your Activity. It uses the WebKit rendering

    engine to display web pages and includes methods to navigate forward and backward through a history, zoom in and out, perform text searches and more. To enable the built-in zoom, set WebSettings.setBuiltInZoomControls(boolean) (introduced in API version 3). Note that, in order for your Activity to access the Internet and load web pages in a WebView, you must add the INTERNET permissions to your Android Manifest file: Sample Application on WebView : Take the input from the user through edittext and when you press go button load the web page in the webview WebServicesTest.java WebServicesTest.java package com.mahesh.xml; import ..................; public class WebServicesTest extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.main);

  • Two Day Workshop on Android

    13/03/2014

    61

    } public void Go(View v){ EditText et1=(EditText)findViewById(R.id.editText1); WebView wv=(WebView)findViewById(R.id.webView1); wv.getSettings().setJavaScriptEnabled(true); wv.getSettings().setBuiltInZoomControls(true); wv.getSettings().setUseWideViewPort(true); wv.getSettings().setAllowFileAccess(true); wv.getSettings().getLoadsImagesAutomatically(); wv.setDownloadListener(new DownloadListener() { @Override public void onDownloadStart(String arg0, String arg1, String arg2, String arg3, long arg4) { Intent i=new Intent(Intent.ACTION_VIEW); startActivity(i); } }); final ProgressDialog pdialog=new ProgressDialog(this); pdialog.setTitle("Message..."); pdialog.setIcon(R.drawable.ic_launcher); pdialog.setMessage("Pls wait page is loading......."); pdialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); wv.setWebViewClient(new WebViewClient(){ @Override public void onPageFinished(WebView view, String url) { // TODO Auto-generated method stub super.onPageFinished(view, url); pdialog.dismiss(); } @Override

    public void onPageStarted(WebView view, String url, Bitmap favicon) { // TODO Auto-generated method stub super.onPageStarted(view, url, favicon); pdialog.show(); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // TODO Auto-generated method stub view.loadUrl(url); return super.shouldOverrideUrlLoading(view, url); } }); wv.loadUrl("http://"+et1.getText().toString()); } } Working With Wifi : WifiManager : This class provides the primary API for managing all aspects of Wi-Fi connectivity. Get an instance of this class by calling Context.getSystemService(Context.WIFI_SERVICE). It deals with several categories of items: The list of configured networks. The list can be viewed and updated, and attributes of individual entries can be modified. The currently active Wi-Fi network, if any. Connectivity can be established or torn down, and dynamic information about the state of the network can be queried. Results of access point scans, containing enough information to make decisions about what

  • Two Day Workshop on Android

    13/03/2014

    62

    access point to connect to. It defines the names of various Intent actions that are broadcast upon any sort of change in Wi- Fi state. To work with this application you need to add the following persmissions in the manifest.xml WifiConfiguration : A class representing a configured Wi-Fi network, including the security configuration. Sample Code to Work With Wifi : wifi.xml: WifiExample . java package com.mahesh.xml; import ..................; public class WifiExample extends Activity { WifiManager wManager; Button button; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); wManager=(WifiManager)getSystemService(Context.WIFI_SERVICE); setContentView(R.layout.wifi); button=(Button)findViewById(R.id.toggleButton1); if(wManager.getWifiState()==wManager.WIFI_STATE_DISABLED){ button.setText("Wifi On"); }else if(wManager.getWifiState()==wManager.WIFI_STATE_ENABLED){ button.setText("Wifi Off"); } } public void Wifi(View v){ if(wManager.getWifiState()==wManager.WIFI_STATE_DISABLED){ wManager.setWifiEnabled(true); button.setText("Wifi Off");

  • Two Day Workshop on Android

    13/03/2014

    63

    }else if(wManager.getWifiState()==wManager.WIFI_STATE_ENABLED){ wManager.setWifiEnabled(false); button.setText("Wifi On"); } } public void getWifiList(View v){ List wificonfig=wManager.getConfiguredNetworks(); for(WifiConfiguration wifi:wificonfig){ Toast.makeText(getApplicationContext(), " SSID : "+wifi.SSID +" \n BSSID :"+wifi.BSSID+"\n Status :"+wifi.status+"\n Priority :"+wifi.priority,Toast.LENGTH_LONG).show(); } } } Notification Manager : class to notify the user of events that happen. This is how you tell the user that something has happened in the background. Notifications can take different forms: A persistent icon that goes in the status bar and is accessible through the launcher, (when the user selects it, a designated Intent can be launched), Turning on or flashing LEDs on the device, or Alerting the user by flashing the backlight, playing a sound, or vibrating. Each of the notify methods takes an int id parameter. This id identifies this notification from your app to the system, so that id should be unique within your app. If you call one of the notify methods with an

    id that is currently active and a new set of notification parameters, it will be updated. For example, if you pass a new status bar icon, the old icon in the status bar will be replaced with the new one. This is also the same id you pass to the cancel(int) method to clear this notification. You do not instantiate this class directly; instead, retrieve it through getSystemService(String). Notification : Notification A Notification object defines the details of the notification message that is displayed in the status bar and "Notifications" window, and any other alert settings, such as sounds and blinking lights. A status bar notification requires all of the following: An icon for the status bar A title and expanded message for the expanded view (unless you define a custom expanded view) A PendingIntent, to be fired when the notification is selected Optional settings for the status bar notification include: A ticker-text message for the status bar An alert sound A vibrate setting A flashing LED setting Vibrator : Class that operates the vibrator on the device. If your process exits, any vibration you started with will stop. You do not instantiate this class directly; instead, retrieve it through getSystemService(String).

  • Two Day Workshop on Android

    13/03/2014

    64

    Vibrator vibrator=(Vibrator)getSystemService(Context.VIBRATOR_SERVICE); Need to add the following permission in the AndroidManifest.xml Develop a sample code to display notification and Vibrate the device when wifi is switch on or wifi switch off for the above application. package com.mahesh.xml; import java.util.List; import ............................; public class WifiExample extends Activity { WifiManager wManager; Button button; NotificationManager nManager; Notification notification; Vibrator vibrator; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.wifi); wManager=(WifiManager)getSystemService(Context.WIFI_SERVICE); button=(Button)findViewById(R.id.toggleButton1); nManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); vibrator=(Vibrator)getSystemService(Context.VIBRATOR_SERVICE); if(wManager.getWifiState()==wManager.WIFI_STATE_DISABLED){ button.setText("Wifi On");

    }else if(wManager.getWifiState()==wManager.WIFI_STATE_ENABLED){ button.setText("Wifi Off"); } } public void Wifi(View v){ if(wManager.getWifiState()==wManager.WIFI_STATE_DISABLED){ wManager.setWifiEnabled(true); button.setText("Wifi Off"); notification=new Notification(R.drawable.ic_launcher, "Wifi State Changed", System.currentTimeMillis()); notification.setLatestEventInfo(getBaseContext(), "Wifi State Changed","Wifi Enabled", getPendingIntent()); nManager.notify(1, notification); vibrator.vibrate(1000); }else if(wManager.getWifiState()==wManager.WIFI_STATE_ENABLED){ wManager.setWifiEnabled(false); button.setText("Wifi On"); notification=new Notification(R.drawable.ic_launcher, "Wifi State Changed", System.currentTimeMillis()); notification.setLatestEventInfo(getBaseContext(), "Wifi State Changed","Wifi Disabled", getPendingIntent()); nManager.notify(1, notification); vibrator.vibrate(1000); } } private PendingIntent getPendingIntent() { Intent i=new Intent(getBaseContext(), WifiExample.class);

  • Two Day Workshop on Android

    13/03/2014

    65

    PendingIntent pi=PendingIntent.getActivity(getBaseContext(), 0,i, 0); return pi; } public void getWifiList(View v){ List wificonfig=wManager.getConfiguredNetworks(); for(WifiConfiguration wifi:wificonfig){ Toast.makeText(getApplicationContext(), " SSID : "+wifi.SSID +" \n BSSID :"+wifi.BSSID+"\n Status :"+wifi.status+"\n Priority :"+wifi.priority,Toast.LENGTH_LONG).show(); } } } LocationManager : This class provides access to the system location services. These services allow applications to obtain periodic updates of the device's geographical location, or to fire an application-specified Intent when the device enters the proximity of a given geographical location. You do not instantiate this class directly; instead, retrieve it through Context.getSystemService(Context.LOCATION_SERVICE). you need to add the following permissions in AndroidManifest.xml

    public void requestLocationUpdates ( String provider, long minTime, float minDistance, LocationListener listener) Registers the current activity to be notified periodically by the named provider. Periodically, the supplied LocationListener will be called with the current Location or with status updates. It may take a while to receive the most recent location. If an immediate location is required, applications may use the getLastKnownLocation(String) method. In case the provider is disabled by the user, updates will stop, and the onProviderDisabled(String) method will be called. As soon as the provider is enabled again, the onProviderEnabled(String) method will be called and location updates will start again. The frequency of notification may be controlled using the minTime and minDistance parameters. If minTime is greater than 0, the LocationManager could potentially rest for minTime milliseconds between location updates to conserve power. If minDistance is greater than 0, a location will only be broadcasted if the device moves by minDistance meters. To obtain notifications as frequently as possible, set both parameters to 0. Background services should be careful about setting a sufficiently high minTime so that the device doesn't consume too much power by keeping the GPS or wireless radios on all the time. In particular, values under 60000ms are not recommended.

  • Two Day Workshop on Android

    13/03/2014

    66

    The calling thread must be a Looper thread such as the main thread of the calling Activity. Parameters provider the name of the provider with which to register minTime the minimum time interval for notifications, in milliseconds. This field is only used as a hint to conserve power, and actual time between location updates may be greater or lesser than this value. minDistance the minimum distance interval for notifications, in meters listener a {#link LocationListener} whose onLocationChanged(Location) method will be called for each location update Sample Code to Work with LocationBasedServices : package com.mahesh.xml; import ..............................; public class LocationTest extends Activity{ LocationManager lManager; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.location); lManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE); lManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, new LocationListener() { @Override public void onStatusChanged(String arg0, int arg1, Bundle arg2) { // TODO Auto-generated method stub

    } @Override public void onProviderEnabled(String arg0) { // TODO Auto-generated method stub } @Override public void onProviderDisabled(String arg0) { // TODO Auto-generated method stub } @Override public void onLocationChanged(Location l) { // TODO Auto-generated method stub Toast.makeText(getApplicationContext(), "Latitude value is :"+l.getLatitude()+"Logitude value is :"+l.getLongitude(), Toast.LENGTH_SHORT).show(); } }); } public void getLocation(View v){ Location l=lManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); Toast.makeText(getApplicationContext(), "Latitude value is :"+l.getLatitude() +"Logitude value is :"+l.getLongitude(), Toast.LENGTH_SHORT).show(); } } ListActivity : An activity that displays a list of items by binding to a data source such as an array or Cursor, and exposes event handlers when the user selects an item. ListActivity hosts a ListView object that can be bound to different data sources, typically either an array or a Cursor holding query results. Binding, screen layout, and row layout are discussed in the

  • Two Day Workshop on Android

    13/03/2014

    67

    following sections. Screen Layout ListActivity has a default layout that consists of a single, full-screen list in the center of the screen. However, if you desire, you can customize the screen layout by setting your own view layout with setContentView() in onCreate(). To do this, your own view MUST contain a ListView object with the id "@android:id/list" (or list if it's in code) Optionally, your custom view can contain another view object of any type to display when the list view is empty. This "empty list" notifier must have an id "android:empty". Note that when an empty view is present, the list view will be hidden when there is no data to display. The following code demonstrates an (ugly) custom screen layout. It has a list with a green background, and an alternate red "no data" message.

    Base Adapter : Common base class of common implementation for an Adapter that can be used in both ListView (by implementing the specialized ListAdapter interface} and Spinner (by implementing the specialized SpinnerAdapter interface. Sample Program to display image names in SDCARD using ListActivity: package com.mahesh.xml; import java.io.File; import ..................; public class ListActivityTest extends ListActivity{ @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); String path=Environment.getExternalStorageDirectory()+"/images"; File f=new File(path); if(f.exists()){ String[] images=f.list(); ArrayAdapter adapter=new ArrayAdapter(getApplicationContext(), android.R.layout.simple_gallery_item,images); setListAdapter(adapter); }else{ Toast.makeText(getApplicationContext(), "There is no file with the given path",Toast.LENGTH_LONG).show();

  • Two Day Workshop on Android

    13/03/2014

    68

    } } } Sample program on creating own CustomView Adapter and display image , image name and image size from SDCARD/images directory: main.xml < ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher" /> ListActivityImagesActivity. Java package com.mahesh.listimages;

    import ................; public class ListActivityImagesActivity extends ListActivity implements AdapterView.OnItemSelectedListener{ /** Called when the activity is first crea