Presentation is loading. Please wait.

Presentation is loading. Please wait.

Android -By Yogita Nirmal.

Similar presentations


Presentation on theme: "Android -By Yogita Nirmal."— Presentation transcript:

1 Android -By Yogita Nirmal

2 What is Android? 1]Android is an open source and Linux-based Operating System for mobile devices such as smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by Google, and other companies. 2]Android offers a unified approach to application development for mobile devices which means developers need only develop for Android, and their applications should be able to run on different devices powered by Android. 3]The first beta version of the Android Software Development Kit (SDK) was released by Google in 2007 where as the first commercial version, Android 1.0, was released in September 2008. 4]On June 27, 2012, at the Google I/O conference, Google announced the next Android version, 4.1 Jelly Bean. Jelly Bean is an incremental update, with the primary aim of improving the user interface, both in terms of functionality and performance.

3 Android Applications Android applications are usually developed in the Java language using the Android Software Development Kit. Once developed, Android applications can be packaged easily and sold out either through a store such as Google Play or the Amazon Appstore. Android powers hundreds of millions of mobile devices in more than 190 countries around the world. It's the largest installed base of any mobile platform and growing fast. Every day more than 1 million new Android devices are activated worldwide.

4 You will be glad to know that you can start your Android application development on either of the following operating systems: Microsoft Windows XP or later version. Mac OS X or later version with Intel chip. Linux including GNU C Library 2.7 or later. Second point is that all the required tools to develop Android applications are freely available and can be downloaded from the Web. Following is the list of software's you will need before you start your Android application programming. Java JDK5 or JDK6 Android SDK Eclipse IDE for Java Developers (optional) Android Development Tools (ADT) Eclipse Plugin (optional)

5 Versions of Android

6 Android Application Life Cycle
An activity represents a single screen with a user interface. For example, an application might have one activity that shows a list of new s, another activity to compose an , and another activity for reading s. If an application has more than one activity, then one of them should be marked as the activity that is presented when the application is launched. If you have worked with C, C++ or Java programming language then you must have seen that your program starts from main() function. Very similar way, Android system initiates its program with in an Activity starting with a call on onCreate() callback method.

7 Activities are a fundamental building block of Android applications and they can exist in a number of different states. The activity lifecycle begins with instantiation and ends with destruction, and includes many states in between. When an activity changes state, the appropriate lifecycle event method is called, notifying the activity of the impending state change and allowing it to execute code in order to adapt to that change.

8 Layouts in Android 1Linear Layout LinearLayout is a view group that aligns all children in a single direction, vertically or horizontally. 2Relative Layout RelativeLayout is a view group that displays child views in relative positions. 3Table Layout TableLayout is a view that groups views into rows and columns. 4Absolute Layout AbsoluteLayout enables you to specify the exact location of its children.

9 Layouts in Android[Continues…]
5Frame Layout The FrameLayout is a placeholder on screen that you can use to display a single view. 6List View ListView is a view group that displays a list of scrollable items. 7Grid View GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid

10 Activity States The Android OS arbitrates Activities based on their state. This helps Android identify activities that are no longer in use, allowing the OS to reclaim memory and resources. The following diagram illustrates the states an Activity can go through during its lifetime:

11 These states can be broken into 4 main groups as follows:
Active or Running - Activities are considered active or running if they are in the foreground, also known as the top of the activity stack. This is considered the highest priority activity in Android, and as such will only be killed by the OS in extreme situations, such as if the activity tries to use more memory than is available on the device as this could cause the UI to become unresponsive. Paused - When the device goes to sleep, or an activity is still visible but partially hidden by a new, non-full-sized or transparent activity, the activity is considered paused. Paused activities are still alive, that is, they maintain all state and member information, and remain attached to the window manager.  Stopped/Backgrounded - Activities that are completely obscured by another activity are considered stopped or in the background. Stopped activities still try to retain their state and member information for as long as possible, but stopped activities are considered to be the lowest priority of the three states and, as such, the OS will kill activities in this state first to satisfy the resource requirements of higher priority activities. Restarted – It is possible for an activity that is anywhere from paused to stopped in the lifecycle to be removed from memory by Android. If the user navigates back to the activity it must be restarted, restored to its previously saved state, and then displayed to the user.

12 Activity Life Cycle Methods

13 The Activity class defines the following callbacks i. e. events
The Activity class defines the following callbacks i.e. events. You don't need to implement all the callbacks methods. However, it's important that you understand each one and implement those that ensure your app behaves the way users expect. CallBack Description onCreate() This is the first callback and called when the activity is first created. onStart() This callback is called when the activity becomes visible to the user. onResume() This is called when the user starts interacting with the application onPause() The paused activity does not receive user input and cannot execute any code and called when the current activity is being paused and the previous activity is being resumed. onStop() This callback is called when the activity is no longer visible. onDestroy() This callback is called before the activity is destroyed by the system. onRestart() This callback is called when the activity restarts after stopping it.

14 Toast A toast provides simple feedback about an operation in a small popup. It only fills the amount of space required for the message and the current activity remains visible and interactive. For example, navigating away from an before you send it triggers a "Draft saved" toast to let you know that you can continue editing later. Toasts automatically disappear after a timeout.

15 import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity {   private Button button;   public void onCreate(Bundle savedInstanceState)   super.onCreate(savedInstanceState); setContentView(R.layout.main);   button = (Button) findViewById(R.id.buttonToast);   button.setOnClickListener(new OnClickListener() public void onClick(View arg0)   Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show();   } });

16 Example 1: Radio Buttons

17 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=" android:layout_width="fill_parent“ android:layout_height="fill_parent" android:orientation="vertical" >   <RadioGroup android:layout_width="wrap_content" android:layout_height="wrap_content" >   <RadioButton android:layout_width="wrap_content“ android:layout_height="wrap_content“ android:checked="true" />   <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" />   </RadioGroup>

18 <Button android:layout_width="wrap_content" android:layout_height="wrap_content“ />   </LinearLayout>

19 import android.app.Activity;
import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Toast;   public class MyAndroidAppActivity extends Activity {   private RadioGroup radioSexGroup; private RadioButton radioSexButton; private Button btnDisplay; public void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); setContentView(R.layout.main);   addListenerOnButton();   }

20 public void addListenerOnButton()
{   radioSexGroup = (RadioGroup) findViewById(R.id.radioSex); btnDisplay = (Button) findViewById(R.id.btnDisplay);   btnDisplay.setOnClickListener(new OnClickListener() public void onClick(View v)   // get selected radio button from radioGroup int selectedId = radioSexGroup.getCheckedRadioButtonId();   // find the radiobutton by returned id radioSexButton = (RadioButton) findViewById(selectedId);   Toast.makeText(MyAndroidAppActivity.this, radioSexButton.getText(), Toast.LENGTH_SHORT).show();   }   }); }

21 import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity ---End---   private Button button;   public void o----nCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState); setContentView(R.layout.main);   button = (Button) findViewById(R.id.buttonToast);   button.setOnClickListener(new OnClickListener() public void onClick(View arg0)   Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show();   } });

22 CheckBox

23 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" >   <CheckBox android:layout_width="wrap_content“ android:layout_height="wrap_content" android: />   <CheckBox android:layout_height="wrap_content“ android: android: checked="true" />   <CheckBox android: /> <Button android:layout_width="wrap_content" android: />   </LinearLayout>

24 package com.mkyong.android;
import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.Toast; public class MyAndroidAppActivity extends Activity { private CheckBox chkIos, chkAndroid, chkWindows; private Button btnDisplay; public void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); setContentView(R.layout.main);   addListenerOnChkIos(); addListenerOnButton(); }  

25 public void addListenerOnChkIos()
{   chkIos = (CheckBox) findViewById(R.id.chkIos);   chkIos.setOnClickListener(new OnClickListener() public void onClick(View v) { //is chkIos checked? if (((CheckBox) v).isChecked()) Toast.makeText(MyAndroidAppActivity.this, "Bro, try Android :)", Toast.LENGTH_LONG).show(); }   } });

26 public void addListenerOnButton()
{   chkIos = (CheckBox) findViewById(R.id.chkIos); chkAndroid = (CheckBox) findViewById(R.id.chkAndroid); chkWindows = (CheckBox) findViewById(R.id.chkWindows); btnDisplay = (Button) findViewById(R.id.btnDisplay);   btnDisplay.setOnClickListener(new OnClickListener()   //Run when button is clicked @Override public void onClick(View v)   StringBuffer result = new StringBuffer(); result.append("IPhone check : ").append(chkIos.isChecked()); result.append("\nAndroid check : ").append(chkAndroid.isChecked()); result.append("\nWindows Mobile check:").append(chkWindows.isChecked());   Toast.makeText(MyAndroidAppActivity.this, result.toString(), Toast.LENGTH_LONG).show();   } });

27 import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity ---End---   private Button button;   public void o----nCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState); setContentView(R.layout.main);   button = (Button) findViewById(R.id.buttonToast);   button.setOnClickListener(new OnClickListener() public void onClick(View arg0)   Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show();   } });

28 Toggle Buttons In Android, the android.widget.ToggleButton is a special class to render a button which has only two states, for example, “on and “off”. It’s best alternative to radio buttons to turn on or turn off a function.

29 Toggle Buttons In Android, the android.widget.ToggleButton is a special class to render a button which has only two states, for example, “on and “off”. It’s best alternative to radio buttons to turn on or turn off a function.

30 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android= android:layout_width="fill_parent“ android:layout_height="fill_parent“ android:orientation="vertical" >   <ToggleButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="ToggleButton" />   <ToggleButton android:checked="true" />   <Button android:layout_height="wrap_content“ />   </LinearLayout>

31 package com.mkyong.android;  
import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; import android.widget.ToggleButton;   public class MyAndroidAppActivity extends Activity {   private ToggleButton toggleButton1, toggleButton2; private Button btnDisplay;   @Override public void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); setContentView(R.layout.main);   addListenerOnButton(); }

32 public void addListenerOnButton()
{   toggleButton1 = (ToggleButton) findViewById(R.id.toggleButton1); toggleButton2 = (ToggleButton) findViewById(R.id.toggleButton2); btnDisplay = (Button) findViewById(R.id.btnDisplay);   btnDisplay.setOnClickListener(new OnClickListener() public void onClick(View v)   StringBuffer result = new StringBuffer(); result.append("toggleButton1 : ").append(toggleButton1.getText()); result.append("\ntoggleButton2 : ").append(toggleButton2.getText());   Toast.makeText(MyAndroidAppActivity.this, result.toString(), Toast.LENGTH_SHORT).show();   }   }); }

33 import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity ---End---   private Button button;   public void o----nCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState); setContentView(R.layout.main);   button = (Button) findViewById(R.id.buttonToast);   button.setOnClickListener(new OnClickListener() public void onClick(View arg0)   Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show();   } });

34 Image Button Add Image to Resources
Put your images into folder “res/drawable-ldpi“, “res/drawable-mdpi” or “res/drawable-hdpi“. See figure below, no matter which folder you put, Android will find your image automatically. In this case, both “android.png” and “android3d.png” images are used for demonstration.

35 2. Add ImageView Open “res/layout/main.xml” file, just add an ImageView and Button for demonstration. By default, imageView1 will display “android.png”. File : res/layout/main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:layout_width="fill_parent“ android:layout_height="fill_parent" android:orientation="vertical" >   <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" />   <Button android:text="Change Image" />   </LinearLayout>

36 ImageButton

37 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" >   <ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content" />   </LinearLayout>

38 import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity ---End---   private Button button;   public void o----nCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState); setContentView(R.layout.main);   button = (Button) findViewById(R.id.buttonToast);   button.setOnClickListener(new OnClickListener() public void onClick(View arg0)   Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show();   } });

39 Login Example

40 1]Activity_Main.xml <EditText android:id="@+id/editText2“
android:layout_width="wrap_content“ android:layout_height="wrap_content" android:inputType="textPassword" /> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:layout_height="wrap_content“ android:onClick="login“ />

41 1]MainActivity.java import android.app.Activity;
import android.graphics.Color; import android.os.Bundle; import android.view.Menu ; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { private EditText username=null; private EditText password=null; private TextView attempts; private Button login; int counter = 3; @Override protected void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); username = (EditText)findViewById(R.id.editText1); password = (EditText)findViewById(R.id.editText2); attempts = (TextView)findViewById(R.id.textView5); attempts.setText(Integer.toString(counter)); login = (Button)findViewById(R.id.button1); }

42 1]MainActivity.java public void login(View view) {
if(username.getText().toString().equals("admin") && password.getText().toString().equals("admin")) Toast.makeText(getApplicationContext(), "Redirecting...", Toast.LENGTH_SHORT).show(); } else Toast.makeText(getApplicationContext(), "Wrong Credentials", Toast.LENGTH_SHORT).show(); attempts.setBackgroundColor(Color.RED); counter--; attempts.setText(Integer.toString(counter)); if(counter==0) login.setEnabled(false);

43 import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity ---End---   private Button button;   public void o----nCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState); setContentView(R.layout.main);   button = (Button) findViewById(R.id.buttonToast);   button.setOnClickListener(new OnClickListener() public void onClick(View arg0)   Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show();   } });

44 Intent Example Intent Types
An Intent is a messaging object you can use to request an action from another app component. Intent Types There are two types of intents: Explicit intents specify the component to start by name (the fully-qualified class name). You'll typically use an explicit intent to start a component in your own app, because you know the class name of the activity or service you want to start. For example, start a new activity in response to a user action or start a service to download a file in the background. Implicit intents do not name a specific component, but instead declare a general action to perform, which allows a component from another app to handle it. For example, if you want to show the user a location on a map, you can use an implicit intent to request that another capable app show a specified location on a map.

45 Intent Example Screen1

46 Screen1 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="     android:layout_width="fill_parent"     android:layout_height="fill_parent"     android:orientation="vertical“>     <TextView         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:text="Enter your name"         android:textAppearance="?android:attr/textAppearanceLarge" />     <EditText         android:ems="10" >         <requestFocus />     </EditText>     <Button         android:text="Take me to next screen" /> </LinearLayout>

47 Screen2

48 Screen2 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="     android:layout_width="match_parent"     android:layout_height="match_parent"     android:orientation="vertical" >     <TextView         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:textAppearance="?android:attr/textAppearanceLarge"         android:text="TEXT"/> </LinearLayout> We have to create two java activity classes to handle two screens:  IntentExampleActivity.java GreetingActivity.java

49 IntentExampleActivity class
EditText nameEditCtrl; Button btnCtlr; String name; nameEditCtrl = (EditText) findViewById(R.id.editText1); btnCtlr = (Button) findViewById(R.id.button1); btnCtlr.setOnClickListener(new ButtonClickHandler()); public class ButtonClickHandler implements View.OnClickListener { //When button is clicked public void onClick(View view) { //If name field is not empty, name variable is assigned with entered name if (nameEditCtrl != null && nameEditCtrl.getText().length() != 0) { name = nameEditCtrl.getText().toString(); } //If name is not entered, String 'Guest' is assigned to name variable else{ name ="Guest";

50 IntentExampleActivity class
//Create Intent object which moves from IntentExampleActivity class //to GreetingActivity class Intent intObj = new Intent(IntentExampleActivity.this,GreetingActivity.class); //Set user entered name in value name which will be //used in GreetingActivity class intObj.putExtra("USERNAME", name); //Start GreetingActivity startActivity(intObj); }     

51 2. GreetingActivity.java
package com.prgguru.android; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.widget.TextView; public class GreetingActivity extends Activity {     TextView greetMsg;     /** Called when the activity is first created. */     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.greeting);         greetMsg = (TextView) findViewById(R.id.textView1);                 //Assign the intent that started this activity         Intent intename = getIntent();                 //Get the USERNAME passed from IntentExampleActivity         String uname = (String) intename.getSerializableExtra("USERNAME");                 //Set text for greetMsg TextView         greetMsg.setText("Welcome " + uname);     } } Add GreetingActivity in AndroidManifest.xml under application tag: <activity android:name=".GreetingActivity" > </activity>     

52 import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity ---End---   private Button button;   public void o----nCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState); setContentView(R.layout.main);   button = (Button) findViewById(R.id.buttonToast);   button.setOnClickListener(new OnClickListener() public void onClick(View arg0)   Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show();   } });

53 DatePicker Example

54 Activity_main.xml <RelativeLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button style="?android:attr/buttonStyleSmall" android:layout_centerHorizontal="true" android: text="Set Date" />     

55 Activity_main.xml <DatePicker android:id="@+id/datePicker1"
android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="34dp" /> </RelativeLayout>    

56 MainActivity.java import android.os.Bundle;
import android.app.Activity; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.Toast; public class MainActivity extends Activity { DatePicker dp; Button b1; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); dp=(DatePicker)findViewById(R.id.datePicker1); b1=(Button)findViewById(R.id.button1); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Toast.makeText(MainActivity.this,dp.getDayOfMonth()+":“ +(dp.getMonth()+1)+":"+dp.getYear(),Toast.LENGTH_LONG).show(); } });

57 import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity ---End---   private Button button;   public void o----nCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState); setContentView(R.layout.main);   button = (Button) findViewById(R.id.buttonToast);   button.setOnClickListener(new OnClickListener() public void onClick(View arg0)   Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show();   } });

58 TimePicker Example

59 Activity_main.xml <RelativeLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Set Hours and Minutes" /> <TimePicker android:layout_alignParentLeft="true" android:layout_marginTop="92dp" />

60 Activity_main.xml <Button android:id="@+id/button1"
style="?android:attr/buttonStyleSmall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="34dp" android:text="Set Time" /> </RelativeLayout>

61 MainActivity.java public class MainActivity extends Activity {
DatePicker dp; Button b1; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tp=(TimePicker)findViewById(R.id.timePicker1); btn=(Button)findViewById(R.id.button1); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub Toast.makeText(getApplicationContext(),(tp.getCurrentHour()%12==0?12:tp.getCurrentHour()%12 )+ ":"+tp.getCurrentMinute()+" "+((tp.getCurrentHour()>11 && tp.getCurrentHour()<24)?"PM":"AM"),Toast.LENGTH_LONG).show(); } });

62 import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity ---End---   private Button button;   public void o----nCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState); setContentView(R.layout.main);   button = (Button) findViewById(R.id.buttonToast);   button.setOnClickListener(new OnClickListener() public void onClick(View arg0)   Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show();   } });

63 RatingBar Example

64 Activity_main.xml <RelativeLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.ratingdemo.MainActivity" tools:ignore="MergeRootFrame" > <RatingBar android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_marginLeft="22dp" android:layout_marginTop="27dp" /> <TextView android:layout_alignParentTop="true" android:layout_marginTop="32dp" android:text="Rating Bar" android:textAppearance="?android:attr/textAppearanceLarge" tools:ignore="HardcodedText" />

65 Activity_main.xml <Button android:id="@+id/button1"
android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="50dp" android:text="Show Rating" /> </RelativeLayout>

66 1]MainActivity.java public class MainActivity extends ActionBarActivity { RatingBar rate; Button b1; rate=(RatingBar)findViewById(R.id.ratingBar1); b1=(Button)findViewById(R.id.button1); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Toast.makeText(getApplicationContext(), "Rating:"+String.valueOf(rate.getRating()),6000).show(); } });

67 import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity ---End---   private Button button;   public void o----nCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState); setContentView(R.layout.main);   button = (Button) findViewById(R.id.buttonToast);   button.setOnClickListener(new OnClickListener() public void onClick(View arg0)   Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show();   } });

68 AlertDialog Example

69 AlertDialog Example

70 1]Activity_main.xml <RelativeLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.alertdialog.MainActivity" tools:ignore="MergeRootFrame" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="26dp" android:text="Alert Dialog" android:textAppearance="?android:attr/textAppearanceMedium" tools:ignore="HardcodedText" /> <Button android:layout_marginTop="21dp" android:text="Show Alert" /> </RelativeLayout>

71 1]Mainactivity.java public class MainActivity extends ActionBarActivity { Button b1; b1=(Button)findViewById(R.id.button1); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { AlertDialog obj=new AlertDialog.Builder(MainActivity.this).create(); obj.setTitle("Caption"); obj.setMessage("hello"); obj.setIcon(R.drawable.ic_launcher); //Code to add ok button in alert /*obj.setButton("OK",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Toast.makeText(getApplicationContext(),"Hello alert", 6000).show(); } });*/ obj.show(); });

72 import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity ---End---   private Button button;   public void o----nCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState); setContentView(R.layout.main);   button = (Button) findViewById(R.id.buttonToast);   button.setOnClickListener(new OnClickListener() public void onClick(View arg0)   Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show();   } });

73 ProgressDialog Example

74 1]Activity_main.xml <RelativeLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.progressdialog.MainActivity" tools:ignore="MergeRootFrame" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="38dp" android:text="Progress Dialog Demo" android:textAppearance="?android:attr/textAppearanceLarge" tools:ignore="HardcodedText" /> <Button android:layout_marginTop="21dp" android:text="Show Progress" /> </RelativeLayout>

75 1]Mainactivity.java public class MainActivity extends ActionBarActivity { Button b1; ProgressDialog dlg; b1=(Button)findViewById(R.id.button1); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { dlg=new ProgressDialog(MainActivity.this); dlg.setMax(100); dlg.setMessage("Loading......"); dlg.setTitle("Progress.."); dlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); dlg.show();

76 1]Mainactivity.java new Thread(new Runnable() { @Override
public void run() { // TODO Auto-generated method stub while(dlg.getProgress()<=dlg.getMax()) try Thread.sleep(500); handle.sendMessage(handle.obtainMessage()); if(dlg.getProgress()==dlg.getMax()) dlg.dismiss(); } catch(Exception e) {} }).start(); Handler handle = new Handler() { public void handleMessage(Message msg) { super.handleMessage(msg); dlg.incrementProgressBy(2); }; });

77 import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity ---End---   private Button button;   public void o----nCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState); setContentView(R.layout.main);   button = (Button) findViewById(R.id.buttonToast);   button.setOnClickListener(new OnClickListener() public void onClick(View arg0)   Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show();   } });

78 AlertDialog with Yes and No Button Example

79 1]Activity_main.xml <RelativeLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.alertdialog.MainActivity" tools:ignore="MergeRootFrame" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="26dp" android:text="Alert Dialog" android:textAppearance="?android:attr/textAppearanceMedium" tools:ignore="HardcodedText" /> <Button android:layout_marginTop="21dp" android:text="Show Alert" /> </RelativeLayout>

80 1]Mainactivity.java public class MainActivity extends ActionBarActivity { Button b1; b1=(Button)findViewById(R.id.button1); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setMessage("This ends the activity"); builder.setCancelable(true); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub Toast.makeText(getApplicationContext(), "Yes button is Clicked",5000).show(); } });

81 1]Mainactivity.java builder.setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub Toast.makeText(getApplicationContext(), "No button is Clicked",5000).show(); } }); AlertDialog dialog = builder.create(); dialog.show();

82 import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity ---End---   private Button button;   public void o----nCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState); setContentView(R.layout.main);   button = (Button) findViewById(R.id.buttonToast);   button.setOnClickListener(new OnClickListener() public void onClick(View arg0)   Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show();   } });

83 Custom Dialog

84 Activity_Custom[Screen 2]

85 1]Activity_main.xml <RelativeLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.customdialog.MainActivity" tools:ignore="MergeRootFrame" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="28dp" android:text="Custom Dialog Control" android:textAppearance="?android:attr/textAppearanceLarge" tools:ignore="HardcodedText" /> <Button android:layout_marginTop="31dp" android:text="Show Custom Dialog" </RelativeLayout>

86 2]Activity_Custom.xml <RelativeLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.customdialog.CustomActivity" tools:ignore="MergeRootFrame" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:minHeight="100dp" android:minWidth="100dp" tools:ignore="HardcodedText" /> <Button android:layout_alignParentBottom="true" android:layout_marginBottom="42dp" android:text="OK" tools:ignore="HardcodedText" />

87 2]Activity_Custom.xml continues…
< <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:textAppearance="?android:attr/textAppearanceLarge" /> </RelativeLayout>

88 1]Mainactivity.java public class MainActivity extends ActionBarActivity { Button b1; final Context cnt=this; b1=(Button)findViewById(R.id.button1); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) final Dialog dlg=new Dialog(cnt); dlg.setContentView(R.layout.activity_custom); dlg.setTitle("My Dialog....."); TextView t1=(TextView)dlg.findViewById(R.id.cusText); t1.setText("Android Custom Dialog Control"); ImageView img=(ImageView)dlg.findViewById(R.id.imageView1); img.setImageResource(R.drawable.ic_launcher); Button b2=(Button)dlg.findViewById(R.id.button1);

89 1]Mainactivity.java continues..
b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dlg.dismiss(); } }); dlg.show();

90 import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity ---End---   private Button button;   public void o----nCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState); setContentView(R.layout.main);   button = (Button) findViewById(R.id.buttonToast);   button.setOnClickListener(new OnClickListener() public void onClick(View arg0)   Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show();   } });

91 Option Menu In Android Activity_mai.xml

92 Go to res/menus/main.xml
Option Menu In Android Go to res/menus/main.xml

93 1]Activity_main.xml <RelativeLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.menudemo.MainActivity" tools:ignore="MergeRootFrame" android:background="#CCEEFF" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="87dp" android:text="Example of Option Menus" android:textAppearance="?android:attr/textAppearanceLarge" tools:ignore="HardcodedText" /> android:layout_marginTop="22dp" android:text="Enter No" android:textAppearance="?android:attr/textAppearanceLarge" />

94 1]Activity_main.xml Continues..
<EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="19dp" android:ems="10" > <requestFocus /> </EditText> <TextView android:layout_centerVertical="true" android:layout_marginLeft="55dp" android:text="Yellow" android:background="#FFFF00" android:textAppearance="?android:attr/textAppearanceLarge" />

95 1]Activity_main.xml Continues..
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="25dp" android:background="#FF0000" android:text="Red" android:textAppearance="?android:attr/textAppearanceLarge" /> <Button android:text="Click" /> </RelativeLayout>

96 2]main.xml <menu xmlns:android=" xmlns:app=" xmlns:tools=" tools:context="com.example.menudemo.MainActivity" > <item android:title="Apple" tools:ignore="HardcodedText" /> <item android:title="Banana" tools:ignore="HardcodedText“/> </menu>

97 1]main_activity.java public class MainActivity extends ActionBarActivity { EditText t1; Button b1; TextView a1,a2; t1=(EditText)findViewById(R.id.editText1); b1=(Button)findViewById(R.id.button1); a1=(TextView)findViewById(R.id.textView3); a2=(TextView)findViewById(R.id.textView4); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub int no=Integer.parseInt(t1.getText().toString()); if(no==1) a1.setVisibility(View.VISIBLE); a2.setVisibility(View.INVISIBLE); } else a2.setVisibility(View.VISIBLE); a1.setVisibility(View.INVISIBLE); });}

98 1]main_activity.java continues..
public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. switch(item.getItemId()) { case R.id.A1: Toast.makeText(getApplicationContext(), "Apple Selected",5000).show(); return true; case R.id.A2: Toast.makeText(getApplicationContext(), "Banana Selected",5000).show(); default: return super.onOptionsItemSelected(item); }

99 import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity ---End---   private Button button;   public void o----nCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState); setContentView(R.layout.main);   button = (Button) findViewById(R.id.buttonToast);   button.setOnClickListener(new OnClickListener() public void onClick(View arg0)   Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show();   } });

100 Working with Preferences
Android provides many ways of storing data of an application. One of this way is called Shared Preferences. Shared Preferences allow you to save and retrieve data in the form of key,value pair. In order to use shared preferences , you have to call a method getSharedPreferences() that returns a SharedPreference instance poiting to the file that contains the values of preferences. SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); The first parameter is the key and the second parameter is the MODE. Apart from private there are other modes availaible that are listed below: 1]MODE_APPEND This will append the new preferences with the already exisiting preferences 2]MODE_PRIVATE By setting this mode , the file can only be accessed using calling application 3]MODE_WORLD_READABLE This mode allow other application to read the preferences 4]MODE_WORLD_WRITEABLE This mode allow other application to write the preferences

101 Steps To add Preference File
1] Create preference file Create an Android XML resource called mypreferences.xml of the PreferenceScreen type. In order to use shared preferences , you have to call a method getSharedPreferences() that returns a SharedPreference instance poiting to the file that contains the values of preferences.

102 Steps To add Preference File[Conitnue..]
After creation the correct Android editor should open the file. If not select the file, right-click on it and select Open with → Android XML Resource Editor.

103 Steps To add Preference File[Conitnue..]
You can save something in the sharedpreferences by using SharedPreferences.Editor class. You will call the edit method of SharedPreference instance and will recieve it in an editor object. Its syntax is: Editor editor = sharedpreferences.edit(); editor.putString("key", "value"); editor.commit(); Apart from the putString method , there are methods availaible in the editor class that allows manipulation of data inside shared preferences. They are listed as follows: 1]apply() It is an abstract method. It will commit your changes back from editor to the sharedPreference object you are calling. 2]clear() It will remove all values from the editor 3]remove(String key) It will remove the value whose key has been passed as a parameter

104 Steps To add Preference File[Conitnue..]
4]putLong(String key, long value) It will save a long value in a preference editor 5]putInt(String key, int value) It will save a integer value in a preference editor 6]putFloat(String key, float value) It will save a float value in a preference editor Example This example demonstrates the use of the Shared Preferences. It display a screen with some text fields , whose value are saved when the application is closed and brought back when it is opened again 

105 Steps: 1] You will use Eclipse IDE to create an Android application and name it as SharedPreferences under a package com.example.sharedpreferences. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs. 2]Modify src/MainActivity.java file to add progress code to display the spinning progress dialog 3]Modify res/layout/activity_main.xml file to add respective XML code. 4]Modify res/values/string.xml file to add a message as a string constant. 5]Run the application and choose a running android device and install the application on it and verify the results.

106 1]MainActivity.java package com.example.sharedpreferences;
import com.example.sharedpreferences.*; import android.os.Bundle; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.view.Menu; import android.view.View; import android.widget.TextView; public class MainActivity extends Activity { TextView name ; TextView phone; TextView ; TextView street; TextView place;

107 1]MainActivity.java[Continue..]
public static final String MyPREFERENCES = "MyPrefs" ; public static final String Name = "nameKey"; public static final String Phone = "phoneKey"; public static final String = " Key"; public static final String Street = "streetKey"; public static final String Place = "placeKey"; SharedPreferences sharedpreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); name = (TextView) findViewById(R.id.editTextName); phone = (TextView) findViewById(R.id.editTextPhone); = (TextView) findViewById(R.id.editTextStreet); street = (TextView) findViewById(R.id.editText ); place = (TextView) findViewById(R.id.editTextCity);

108 1]MainActivity.java[Continue..]
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); if (sharedpreferences.contains(Name)) { name.setText(sharedpreferences.getString(Name, "")); } if (sharedpreferences.contains(Phone)) phone.setText(sharedpreferences.getString(Phone, "")); if (sharedpreferences.contains( )) .setText(sharedpreferences.getString( , "")); if (sharedpreferences.contains(Street)) street.setText(sharedpreferences.getString(Street, "")); if (sharedpreferences.contains(Place)) place.setText(sharedpreferences.getString(Place,""));

109 1]MainActivity.java[Continue..]
public void run(View view) { String n = name.getText().toString(); String ph = phone.getText().toString(); String e = .getText().toString(); String s = street.getText().toString(); String p = place.getText().toString(); Editor editor = sharedpreferences.edit(); editor.putString(Name, n); editor.putString(Phone, ph); editor.putString( , e); editor.putString(Street, s); editor.putString(Place, p); editor.commit(); }

110 2]Activity_main.xml

111 2]Activity_main.xml <ScrollView
xmlns:android=" xmlns:tools=" android:layout_width="match_parent“ android:layout_height="wrap_content" tools:context=".DisplayContact" > <RelativeLayout android:layout_height="370dp" >

112 2]Activity_main.xml[Continue..]
<EditText android:layout_width="wrap_content“ android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_marginTop="5dp“ android:layout_marginLeft="82dp" android:ems="10" android:inputType="text" > </EditText> android:layout_width="wrap_content" android:layout_marginTop="22dp" android:ems="10" android:inputType="text Address" />

113 2]Activity_main.xml[Continue..]
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true“ android:textAppearance="?android:attr/textAppearanceMedium" /> <Button android:layout_alignParentBottom="true“ android:layout_marginBottom="28dp“ android:onClick="run" />

114 2]Activity_main.xml[Continue..]
<TextView android:layout_width="wrap_content“ android:layout_height="wrap_content“ android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" /> </RelativeLayout> </ScrollView>

115 3] res/values/strings.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">SharedPreferences</string> <string name="action_settings">Settings</string> <string name="hello_world">Hello world!</string> <string name="name">Name</string> <string name="phone">Phone</string> <string name=" "> </string> <string name="street">Street</string> <string name="country">City/State/Zip</string> <string name="save">Save Contact</string> </resources>

116 import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity ---End---   private Button button;   public void o----nCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState); setContentView(R.layout.main);   button = (Button) findViewById(R.id.buttonToast);   button.setOnClickListener(new OnClickListener() public void onClick(View arg0)   Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show();   } });

117 Open Browser URL via Intent
Activity_main.xml

118 Activity_main.xml <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" >   <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button - Go to mkyong.com" /> <EditText android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="42dp" android:ems="10" />   </LinearLayout>

119 Mainactivity.java public class MyAndroidAppActivity extends Activity {
  Button button; EditText e1; public void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); setContentView(R.layout.main);   addListenerOnButton();   }   public void addListenerOnButton()   button = (Button) findViewById(R.id.button1); e1=(EditText)findViewById(R.id.editText1);

120 String abc=e1.getText().toString();
Mainactivity.java   button.setOnClickListener(new OnClickListener() { public void onClick(View arg0) String abc=e1.getText().toString();   Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(abc)); startActivity(browserIntent);   }   });   }   }

121 import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity ---End---   private Button button;   public void o----nCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState); setContentView(R.layout.main);   button = (Button) findViewById(R.id.buttonToast);   button.setOnClickListener(new OnClickListener() public void onClick(View arg0)   Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show();   } });

122 How to make a phone call in Android
Activity_main.xml

123 How to make a phone call in Android
Activity_main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" >   <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="call " />   </LinearLayout>

124 How to make a phone call in Android
MainActivity.java public class MainActivity extends Activity {   private Button button;   public void onCreate(Bundle savedInstanceState)   super.onCreate(savedInstanceState); setContentView(R.layout.main);   button = (Button) findViewById(R.id.buttonCall);   // add button listener button.setOnClickListener(new OnClickListener() public void onClick(View arg0)   Intent callIntent = new Intent(Intent.ACTION_CALL); callIntent.setData(Uri.parse("tel: ")); startActivity(callIntent);   }   });   }   }

125 import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity ---End---   private Button button;   public void o----nCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState); setContentView(R.layout.main);   button = (Button) findViewById(R.id.buttonToast);   button.setOnClickListener(new OnClickListener() public void onClick(View arg0)   Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show();   } });

126 Send Sms using Android Activity_main.xml

127 Send Sms using Android Activity_main.xml
<RelativeLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.smsdemo.MainActivity" tools:ignore="MergeRootFrame" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginTop="29dp" android:text="Phone No" tools:ignore="HardcodedText" android:textAppearance="?android:attr/textAppearanceMedium" /> <EditText android:layout_alignParentRight="true" android:ems="10" />

128 Activity_main.xml[continues..]
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_marginTop="33dp" android:text="Write Msg" android:textAppearance="?android:attr/textAppearanceMedium" tools:ignore="HardcodedText" /> <EditText android:layout_alignParentRight="true" android:ems="10" /> <Button android:layout_marginTop="46dp" android:text="Send Msg" /> </RelativeLayout>

129 Send Sms using Android Mainactivity.java public class MainActivity extends ActionBarActivity { EditText e1,e2; Button b1; protected void onCreate(Bundle savedInstanceState) { e1=(EditText)findViewById(R.id.editText1); e2=(EditText)findViewById(R.id.editText2); b1=(Button)findViewById(R.id.button1);

130 Send Sms using Android Mainactivity.java b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { try { // TODO Auto-generated method stub SmsManager mgr=SmsManager.getDefault(); mgr.sendTextMessage(e1.getText().toString(),null,e2.getText().toString(),null,null); Toast.makeText(getApplicationContext(),"Msg Sent...",5000).show(); } catch(Exception ee) Toast.makeText(getApplicationContext(),"Msg not delivered",5000).show(); });

131 import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity ---End---   private Button button;   public void o----nCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState); setContentView(R.layout.main);   button = (Button) findViewById(R.id.buttonToast);   button.setOnClickListener(new OnClickListener() public void onClick(View arg0)   Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show();   } });

132 Context Menu using Android
Activity_main.xml

133 Context Menu using Android
Activity_main.xml <RelativeLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.cmenudemo.MainActivity" tools:ignore="MergeRootFrame" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="25dp" android:text="Welcome to Context Menu" tools:ignore="HardcodedText" android:textAppearance="?android:attr/textAppearanceLarge" />

134 Context Menu using Android
Activity_main.xml <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="14dp" android:text="Click Me" /> </RelativeLayout>

135 Context Menu using Android
Mainactivity.java public class MainActivity extends ActionBarActivity { EButton b1; protected void onCreate(Bundle savedInstanceState) { b1=(Button)findViewById(R.id.button1); registerForContextMenu(b1);

136 Context Menu using Android
Mainactivity.java public class MainActivity extends ActionBarActivity { EButton b1; protected void onCreate(Bundle savedInstanceState) { b1=(Button)findViewById(R.id.button1); registerForContextMenu(b1);

137 Context Menu using Android
Mainactivity.java public void onCreateContextMenu(ContextMenu menu,View v,ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.setHeaderTitle("My Context Menu"); menu.add(0, v.getId(),1, "Call"); menu.add(0, v.getId(),0, "Msg"); }

138 Context Menu using Android
Mainactivity.java public boolean onContextItemSelected(MenuItem item) { if(item.getGroupId()==0) if(item.getTitle()=="Call") Toast.makeText(getApplicationContext(),"Call Me",4000).show(); } else if(item.getTitle()=="Msg") Toast.makeText(getApplicationContext(),"Text Me",4000).show(); else return false; return true;

139 import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity ---End---   private Button button;   public void o----nCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState); setContentView(R.layout.main);   button = (Button) findViewById(R.id.buttonToast);   button.setOnClickListener(new OnClickListener() public void onClick(View arg0)   Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show();   } });

140 Mail Sending using Android
What is Intent? Android Intent, which is an object carrying an intent ie. message from one component to another component with-in the application or outside the application. As such you do not need to develop your client because they are already available like Gmail. But you will need to send from your Android application, where you will have to write an Activity that needs to launch an client and sends an using your Android device. For this purpose, your Activity will send an ACTION_SEND along with appropriate data load, to the Android Intent Resolver. The specified chooser gives the proper interface for the user to pick how to send your data.

141 Intent Object - Action to send Email
You will use ACTION_SEND action to launch an client installed on your Android device. Following is simple syntax to create an intent with ACTION_SEND action. Intent Intent = new Intent(Intent.ACTION_SEND); To send an you need to specify mailto: as URI using setData() method and data type will be to text/plain using setType() method as follows: Intent.setData(Uri.parse("mailto:")); Intent.setType("text/plain");

142 Intent Object - Extra to send Email
Android has built-in support to add TO, SUBJECT, CC, TEXT etc. fields which can be attached to the intent before sending the intent to a target client. You can use following extra fields in your EXTRA_BCC  A String[] holding addresses that should be blind carbon copied. 2EXTRA_CC  A String[] holding addresses that should be carbon copied. 3EXTRA_   A String[] holding addresses that should be delivered to. 4EXTRA_HTML_TEXT  A constant String that is associated with the Intent, used with ACTION_SEND to supply an alternative to EXTRA_TEXT as HTML formatted text. 5EXTRA_SUBJECT  A constant string holding the desired subject line of a message.

143 Intent Object - Extra to send Email
6EXTRA_TEXT  A constant CharSequence that is associated with the Intent, used with ACTION_SEND to supply the literal data to be sent. 7EXTRA_TITLE  A CharSequence dialog title to provide to the user when used with a ACTION_CHOOSER.

144 MainActivity.java public class MainActivity extends Activity {
@Override protected void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button startBtn = (Button) findViewById(R.id.send ); startBtn.setOnClickListener(new View.OnClickListener() public void onClick(View view) send (); } });

145 MainActivity.java protected void sendEmail() {
Log.i("Send ", ""); String[] TO = String[] CC = Intent Intent = new Intent(Intent.ACTION_SEND); Intent.setData(Uri.parse("mailto:")); Intent.setType("text/plain"); Intent.putExtra(Intent.EXTRA_ , TO); Intent.putExtra(Intent.EXTRA_CC, CC); Intent.putExtra(Intent.EXTRA_SUBJECT, "Your subject"); Intent.putExtra(Intent.EXTRA_TEXT, " message goes here");

146 MainActivity.java MainActivity.java try {
startActivity(Intent.createChooser( Intent, "Send mail...")); finish(); Log.i("Finished sending ...", ""); } catch (android.content.ActivityNotFoundException ex) Toast.makeText(MainActivity.this, "There is no client installed.", Toast.LENGTH_SHORT).show(); MainActivity.java

147 Activity_main.xml <LinearLayout
xmlns:android=" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:layout_height="wrap_content" </LinearLayout> Activity_main.xml

148 import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity ---End---   private Button button;   public void o----nCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState); setContentView(R.layout.main);   button = (Button) findViewById(R.id.buttonToast);   button.setOnClickListener(new OnClickListener() public void onClick(View arg0)   Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show();   } });

149 Introduction to SQLite
Screen1

150 Introduction to SQLite
Screen2

151 MainActivity.java MainActivity.java
public class MainActivity extends ActionBarActivity { EditText t1,t2,t3; Button b1,b2,b3,b4; SQLiteDatabase db; protected void onCreate(Bundle savedInstanceState) t1=(EditText)findViewById(R.id.editText1); t2=(EditText)findViewById(R.id.editText2); t3=(EditText)findViewById(R.id.editText3); b1=(Button)findViewById(R.id.button1); b2=(Button)findViewById(R.id.Button2); b3=(Button)findViewById(R.id.Button3); b4=(Button)findViewById(R.id.Button4); db=openOrCreateDatabase("StudentDB", Context.MODE_PRIVATE, null); db.execSQL("CREATE TABLE IF NOT EXISTS student(rollno VARCHAR,name VARCHAR,marks VARCHAR);"); MainActivity.java

152 MainActivity.java MainActivity.java
b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { if(t1.getText().toString().trim().length()==0|| t2.getText().toString().trim().length()==0|| t3.getText().toString().trim().length()==0) { //showMessage("Error", "Please enter all values"); return; } db.execSQL("INSERT INTO student VALUES(‘ "+t1.getText()+“ ','"+t2.getText()+ "','"+t3.getText()+"');"); showMessage("Success", "Record added"); clearText(); MainActivity.java

153 MainActivity.java b2.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View arg0) { Cursor c=db.rawQuery("SELECT * FROM student", null); if(c.getCount()==0) { showMessage("Error", "No records found"); return; } StringBuffer buffer=new StringBuffer(); while(c.moveToNext()) buffer.append("Rollno: "+c.getString(0)+"\n"); buffer.append("Name: "+c.getString(1)+"\n"); buffer.append("Marks: "+c.getString(2)+"\n\n"); showMessage("Student Details", buffer.toString()); }); MainActivity.java

154 MainActivity.java b4.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View arg0) { if(t1.getText().toString().trim().length()==0) showMessage("Error", "Please enter Rollno"); return; } Cursor c=db.rawQuery("SELECT * FROM student WHERE rollno='"+t1.getText()+"'", null); if(c.moveToFirst()) db.execSQL("UPDATE student SET name='"+t2.getText()+"',marks='"+t3.getText()+ "' WHERE rollno='"+t1.getText()+"'"); showMessage("Success", "Record Modified"); else showMessage("Error", "Invalid Rollno"); clearText(); });

155 MainActivity.java b3.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View arg0) { /*if(t1.getText().toString().trim().length()==0) { showMessage("Error", "Please enter Rollno"); return; }*/ Cursor c=db.rawQuery("SELECT * FROM student WHERE rollno='"+t1.getText()+"'", null); if(c.moveToFirst()) db.execSQL("DELETE FROM student WHERE rollno='"+t1.getText()+"'"); showMessage("Success", "Record Deleted"); } //else //{ //showMessage("Error", "Invalid Rollno"); //} clearText(); });

156 MainActivity.java public void clearText() { t1.setText("");
t1.requestFocus(); } public void showMessage(String title,String message) Builder builder=new Builder(this); builder.setCancelable(true); builder.setTitle(title); builder.setMessage(message); builder.show();

157 import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity ---End---   private Button button;   public void o----nCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState); setContentView(R.layout.main);   button = (Button) findViewById(R.id.buttonToast);   button.setOnClickListener(new OnClickListener() public void onClick(View arg0)   Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show();   } });


Download ppt "Android -By Yogita Nirmal."

Similar presentations


Ads by Google