Android -By Yogita Nirmal
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.
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.
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 10.5.8 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)
Versions of Android
Android Application Life Cycle An activity represents a single screen with a user interface. For example, an email application might have one activity that shows a list of new emails, another activity to compose an email, and another activity for reading emails. 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.
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.
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.
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
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:
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.
Activity Life Cycle Methods
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.
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 email 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.
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() @Override public void onClick(View arg0) Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show(); } });
Example 1: Radio Buttons
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent“ android:layout_height="fill_parent" android:orientation="vertical" > <RadioGroup android:id="@+id/radioSex" android:layout_width="wrap_content" android:layout_height="wrap_content" > <RadioButton android:id="@+id/radioMale" android:layout_width="wrap_content“ android:layout_height="wrap_content“ android:text="@string/radio_male" android:checked="true" /> <RadioButton android:id="@+id/radioFemale" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/radio_female" /> </RadioGroup>
<Button android:id="@+id/btnDisplay" android:layout_width="wrap_content" android:layout_height="wrap_content“ android:text="@string/btn_display" /> </LinearLayout>
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; @Override public void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); setContentView(R.layout.main); addListenerOnButton(); }
public void addListenerOnButton() { radioSexGroup = (RadioGroup) findViewById(R.id.radioSex); btnDisplay = (Button) findViewById(R.id.btnDisplay); btnDisplay.setOnClickListener(new OnClickListener() @Override 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(); } }); }
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() @Override public void onClick(View arg0) Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show(); } });
CheckBox
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <CheckBox android:id="@+id/chkIos" android:layout_width="wrap_content“ android:layout_height="wrap_content" android: text="@string/chk_ios" /> <CheckBox android:id="@+id/chkAndroid“ android:layout_height="wrap_content“ android: text="@string/chk_android" android: checked="true" /> <CheckBox android:id="@+id/chkWindows“ android: text="@string/chk_windows" /> <Button android:id="@+id/btnDisplay" android:layout_width="wrap_content" android: text="@string/btn_display" /> </LinearLayout>
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; @Override public void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); setContentView(R.layout.main); addListenerOnChkIos(); addListenerOnButton(); }
public void addListenerOnChkIos() { chkIos = (CheckBox) findViewById(R.id.chkIos); chkIos.setOnClickListener(new OnClickListener() @Override public void onClick(View v) { //is chkIos checked? if (((CheckBox) v).isChecked()) Toast.makeText(MyAndroidAppActivity.this, "Bro, try Android :)", Toast.LENGTH_LONG).show(); } } });
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(); } });
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() @Override public void onClick(View arg0) Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show(); } });
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.
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.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=http://schemas.android.com/apk/res/android android:layout_width="fill_parent“ android:layout_height="fill_parent“ android:orientation="vertical" > <ToggleButton android:id="@+id/toggleButton1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="ToggleButton" /> <ToggleButton android:id="@+id/toggleButton2" android:textOn="@string/toggle_turn_on" android:textOff="@string/toggle_turn_off" android:checked="true" /> <Button android:id="@+id/btnDisplay" android:layout_height="wrap_content“ android:text="@string/btn_display" /> </LinearLayout>
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(); }
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() @Override 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(); } }); }
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() @Override public void onClick(View arg0) Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show(); } });
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.
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="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent“ android:layout_height="fill_parent" android:orientation="vertical" > <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/android" /> <Button android:id="@+id/btnChangeImage" android:text="Change Image" /> </LinearLayout>
ImageButton
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <ImageButton android:id="@+id/imageButton1“ android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/android_button" /> </LinearLayout>
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() @Override public void onClick(View arg0) Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show(); } });
Login Example
1]Activity_Main.xml <EditText android:id="@+id/editText2“ android:layout_width="wrap_content“ android:layout_height="wrap_content" android:inputType="textPassword" /> <EditText android:id="@+id/editText1“ android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/button1" android:layout_height="wrap_content“ android:onClick="login“ android:text="@string/Login" />
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); }
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);
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() @Override public void onClick(View arg0) Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show(); } });
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.
Intent Example Screen1
Screen1 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical“> <TextView android:id="@+id/textView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Enter your name" android:textAppearance="?android:attr/textAppearanceLarge" /> <EditText android:id="@+id/editText1" android:ems="10" > <requestFocus /> </EditText> <Button android:id="@+id/button1" android:text="Take me to next screen" /> </LinearLayout>
Screen2
Screen2 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/textView1" android:layout_width="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
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";
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); }
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. */ @Override 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" android:label="@string/app_name" > </activity>
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() @Override public void onClick(View arg0) Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show(); } });
DatePicker Example
Activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> <Button android:id="@+id/button1" style="?android:attr/buttonStyleSmall" android:layout_below="@+id/textView1" android:layout_centerHorizontal="true" android: text="Set Date" />
Activity_main.xml <DatePicker android:id="@+id/datePicker1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView1" android:layout_below="@+id/button1" android:layout_marginTop="34dp" /> </RelativeLayout>
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(); } });
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() @Override public void onClick(View arg0) Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show(); } });
TimePicker Example
Activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Set Hours and Minutes" /> <TimePicker android:id="@+id/timePicker1" android:layout_alignParentLeft="true" android:layout_below="@+id/textView1" android:layout_marginTop="92dp" />
Activity_main.xml <Button android:id="@+id/button1" style="?android:attr/buttonStyleSmall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignRight="@+id/textView1" android:layout_below="@+id/timePicker1" android:layout_marginTop="34dp" android:text="Set Time" /> </RelativeLayout>
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(); } });
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() @Override public void onClick(View arg0) Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show(); } });
RatingBar Example
Activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.ratingdemo.MainActivity" tools:ignore="MergeRootFrame" > <RatingBar android:id="@+id/ratingBar1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/textView1" android:layout_marginLeft="22dp" android:layout_marginTop="27dp" /> <TextView android:id="@+id/textView1" android:layout_alignLeft="@+id/ratingBar1" android:layout_alignParentTop="true" android:layout_marginTop="32dp" android:text="Rating Bar" android:textAppearance="?android:attr/textAppearanceLarge" tools:ignore="HardcodedText" />
Activity_main.xml <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/ratingBar1" android:layout_below="@+id/ratingBar1" android:layout_marginLeft="50dp" android:text="Show Rating" /> </RelativeLayout>
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(); } });
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() @Override public void onClick(View arg0) Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show(); } });
AlertDialog Example
AlertDialog Example
1]Activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.alertdialog.MainActivity" tools:ignore="MergeRootFrame" > <TextView android:id="@+id/textView1" 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:id="@+id/button1" android:layout_below="@+id/textView1" android:layout_marginTop="21dp" android:text="Show Alert" /> </RelativeLayout>
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(); });
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() @Override public void onClick(View arg0) Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show(); } });
ProgressDialog Example
1]Activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.progressdialog.MainActivity" tools:ignore="MergeRootFrame" > <TextView android:id="@+id/textView1" 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:id="@+id/button1" android:layout_below="@+id/textView1" android:layout_marginTop="21dp" android:text="Show Progress" /> </RelativeLayout>
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();
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); }; });
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() @Override public void onClick(View arg0) Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show(); } });
AlertDialog with Yes and No Button Example
1]Activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.alertdialog.MainActivity" tools:ignore="MergeRootFrame" > <TextView android:id="@+id/textView1" 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:id="@+id/button1" android:layout_below="@+id/textView1" android:layout_marginTop="21dp" android:text="Show Alert" /> </RelativeLayout>
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(); } });
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();
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() @Override public void onClick(View arg0) Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show(); } });
Custom Dialog
Activity_Custom[Screen 2]
1]Activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.customdialog.MainActivity" tools:ignore="MergeRootFrame" > <TextView android:id="@+id/textView1" 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:id="@+id/button1" android:layout_below="@+id/textView1" android:layout_marginTop="31dp" android:text="Show Custom Dialog" </RelativeLayout>
2]Activity_Custom.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.customdialog.CustomActivity" tools:ignore="MergeRootFrame" > <ImageView android:id="@+id/imageView1" 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" android:src="@drawable/ic_launcher" /> <Button android:id="@+id/button1" android:layout_alignParentBottom="true" android:layout_marginBottom="42dp" android:text="OK" tools:ignore="HardcodedText" />
2]Activity_Custom.xml continues… < <TextView android:id="@+id/cusText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/imageView1" android:layout_centerHorizontal="true" android:textAppearance="?android:attr/textAppearanceLarge" /> </RelativeLayout>
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);
1]Mainactivity.java continues.. b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dlg.dismiss(); } }); dlg.show();
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() @Override public void onClick(View arg0) Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show(); } });
Option Menu In Android Activity_mai.xml
Go to res/menus/main.xml Option Menu In Android Go to res/menus/main.xml
1]Activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.menudemo.MainActivity" tools:ignore="MergeRootFrame" android:background="#CCEEFF" > <TextView android:id="@+id/textView1" 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:id="@+id/textView2" android:layout_alignLeft="@+id/textView1" android:layout_below="@+id/textView1" android:layout_marginTop="22dp" android:text="Enter No" android:textAppearance="?android:attr/textAppearanceLarge" />
1]Activity_main.xml Continues.. <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/textView2" android:layout_marginLeft="19dp" android:layout_toRightOf="@+id/textView2" android:ems="10" > <requestFocus /> </EditText> <TextView android:id="@+id/textView3" android:layout_alignLeft="@+id/textView2" android:layout_centerVertical="true" android:layout_marginLeft="55dp" android:text="Yellow" android:background="#FFFF00" android:textAppearance="?android:attr/textAppearanceLarge" />
1]Activity_main.xml Continues.. <TextView android:id="@+id/textView4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView3" android:layout_below="@+id/textView3" android:layout_marginTop="25dp" android:background="#FF0000" android:text="Red" android:textAppearance="?android:attr/textAppearanceLarge" /> <Button android:id="@+id/button1" android:layout_alignRight="@+id/textView1" android:text="Click" /> </RelativeLayout>
2]main.xml <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:context="com.example.menudemo.MainActivity" > <item android:id="@+id/A1" android:title="Apple" tools:ignore="HardcodedText" /> <item android:id="@+id/A2" android:title="Banana" tools:ignore="HardcodedText“/> </menu>
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); });}
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); }
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() @Override public void onClick(View arg0) Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show(); } });
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
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.
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.
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
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
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.
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 email; TextView street; TextView place;
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 Email = "emailKey"; 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); email = (TextView) findViewById(R.id.editTextStreet); street = (TextView) findViewById(R.id.editTextEmail); place = (TextView) findViewById(R.id.editTextCity);
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(Email)) email.setText(sharedpreferences.getString(Email, "")); if (sharedpreferences.contains(Street)) street.setText(sharedpreferences.getString(Street, "")); if (sharedpreferences.contains(Place)) place.setText(sharedpreferences.getString(Place,""));
1]MainActivity.java[Continue..] public void run(View view) { String n = name.getText().toString(); String ph = phone.getText().toString(); String e = email.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(Email, e); editor.putString(Street, s); editor.putString(Place, p); editor.commit(); }
2]Activity_main.xml
2]Activity_main.xml <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/scrollView1" android:layout_width="match_parent“ android:layout_height="wrap_content" tools:context=".DisplayContact" > <RelativeLayout android:layout_height="370dp" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" >
2]Activity_main.xml[Continue..] <EditText android:id="@+id/editTextName" 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:id="@+id/editTextEmail“ android:layout_width="wrap_content" android:layout_alignLeft="@+id/editTextStreet“ android:layout_below="@+id/editTextStreet" android:layout_marginTop="22dp" android:ems="10" android:inputType="textEmailAddress" />
2]Activity_main.xml[Continue..] <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/editTextName" android:layout_alignParentLeft="true“ android:text="@string/name" android:textAppearance="?android:attr/textAppearanceMedium" /> <Button android:id="@+id/button1" android:layout_alignLeft="@+id/editTextCity“ android:layout_alignParentBottom="true“ android:layout_marginBottom="28dp“ android:onClick="run" android:text="@string/save" />
2]Activity_main.xml[Continue..] <TextView android:id="@+id/textView2" android:layout_width="wrap_content“ android:layout_height="wrap_content“ android:layout_alignBottom="@+id/editTextEmail“ android:layout_alignLeft="@+id/textView1“ android:text="@string/email" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:id="@+id/textView5“ android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/editTextPhone“ android:text="@string/phone" android:textAppearance="?android:attr/textAppearanceMedium" /> </RelativeLayout> </ScrollView>
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="email">Email</string> <string name="street">Street</string> <string name="country">City/State/Zip</string> <string name="save">Save Contact</string> </resources>
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() @Override public void onClick(View arg0) Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show(); } });
Open Browser URL via Intent Activity_main.xml
Activity_main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button - Go to mkyong.com" /> <EditText android:id="@+id/editText1" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="42dp" android:ems="10" /> </LinearLayout>
Mainactivity.java public class MyAndroidAppActivity extends Activity { Button button; EditText e1; @Override 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);
String abc=e1.getText().toString(); Mainactivity.java button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) String abc=e1.getText().toString(); Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(abc)); startActivity(browserIntent); } }); } }
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() @Override public void onClick(View arg0) Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show(); } });
How to make a phone call in Android Activity_main.xml
How to make a phone call in Android Activity_main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/buttonCall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="call 0377778888" /> </LinearLayout>
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() @Override public void onClick(View arg0) Intent callIntent = new Intent(Intent.ACTION_CALL); callIntent.setData(Uri.parse("tel:0377778888")); startActivity(callIntent); } }); } }
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() @Override public void onClick(View arg0) Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show(); } });
Send Sms using Android Activity_main.xml
Send Sms using Android Activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.smsdemo.MainActivity" tools:ignore="MergeRootFrame" > <TextView android:id="@+id/textView1" 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:id="@+id/editText1" android:layout_alignBottom="@+id/textView1" android:layout_alignParentRight="true" android:ems="10" />
Activity_main.xml[continues..] <TextView android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/textView1" android:layout_marginTop="33dp" android:text="Write Msg" android:textAppearance="?android:attr/textAppearanceMedium" tools:ignore="HardcodedText" /> <EditText android:id="@+id/editText2" android:layout_alignParentRight="true" android:layout_alignTop="@+id/TextView01" android:ems="10" /> <Button android:id="@+id/button1" android:layout_below="@+id/editText2" android:layout_marginTop="46dp" android:layout_toLeftOf="@+id/editText2" android:text="Send Msg" /> </RelativeLayout>
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);
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(); });
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() @Override public void onClick(View arg0) Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show(); } });
Context Menu using Android Activity_main.xml
Context Menu using Android Activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.cmenudemo.MainActivity" tools:ignore="MergeRootFrame" > <TextView android:id="@+id/textView1" 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" />
Context Menu using Android Activity_main.xml <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textView1" android:layout_centerHorizontal="true" android:layout_marginTop="14dp" android:text="Click Me" /> </RelativeLayout>
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);
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);
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"); }
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;
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() @Override public void onClick(View arg0) Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show(); } });
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 email client because they are already available like Gmail. But you will need to send email from your Android application, where you will have to write an Activity that needs to launch an email client and sends an email 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 email data.
Intent Object - Action to send Email You will use ACTION_SEND action to launch an email client installed on your Android device. Following is simple syntax to create an intent with ACTION_SEND action. Intent emailIntent = new Intent(Intent.ACTION_SEND); To send an email you need to specify mailto: as URI using setData() method and data type will be to text/plain using setType() method as follows: emailIntent.setData(Uri.parse("mailto:")); emailIntent.setType("text/plain");
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 email client. You can use following extra fields in your email: EXTRA_BCC A String[] holding e-mail addresses that should be blind carbon copied. 2EXTRA_CC A String[] holding e-mail addresses that should be carbon copied. 3EXTRA_EMAIL A String[] holding e-mail 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.
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.
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.sendEmail); startBtn.setOnClickListener(new View.OnClickListener() public void onClick(View view) sendEmail(); } });
MainActivity.java protected void sendEmail() { Log.i("Send email", ""); String[] TO = {"amrood.admin@gmail.com"}; String[] CC = {"mcmohd@gmail.com"}; Intent emailIntent = new Intent(Intent.ACTION_SEND); emailIntent.setData(Uri.parse("mailto:")); emailIntent.setType("text/plain"); emailIntent.putExtra(Intent.EXTRA_EMAIL, TO); emailIntent.putExtra(Intent.EXTRA_CC, CC); emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Your subject"); emailIntent.putExtra(Intent.EXTRA_TEXT, "Email message goes here");
MainActivity.java MainActivity.java try { startActivity(Intent.createChooser(emailIntent, "Send mail...")); finish(); Log.i("Finished sending email...", ""); } catch (android.content.ActivityNotFoundException ex) Toast.makeText(MainActivity.this, "There is no email client installed.", Toast.LENGTH_SHORT).show(); MainActivity.java
Activity_main.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/sendEmail" android:layout_height="wrap_content" android:text="@string/compose_email"/> </LinearLayout> Activity_main.xml
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() @Override public void onClick(View arg0) Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show(); } });
Introduction to SQLite Screen1
Introduction to SQLite Screen2
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
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
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
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(); });
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(); });
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();
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() @Override public void onClick(View arg0) Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show(); } });