0% found this document useful (0 votes)
6 views459 pages

Android Important

The document provides a tutorial on creating and using Alert Dialogs in Android applications, detailing how to build dialogs using AlertDialog.Builder and customize them with various methods. It also introduces Dialog Fragments and different types of dialogs, such as list and single-choice dialogs, with example code for implementation. Additionally, it briefly discusses tween animations in Android, explaining how to apply animations to views using the Animation class and XML files.

Uploaded by

Bhumika Kachhava
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views459 pages

Android Important

The document provides a tutorial on creating and using Alert Dialogs in Android applications, detailing how to build dialogs using AlertDialog.Builder and customize them with various methods. It also introduces Dialog Fragments and different types of dialogs, such as list and single-choice dialogs, with example code for implementation. Additionally, it briefly discusses tween animations in Android, explaining how to apply animations to views using the Animation class and XML files.

Uploaded by

Bhumika Kachhava
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Android - Alert Dialog Tutorial

A Dialog is small window that prompts the user to a decision or enter additional information.

Some times in your application, if you wanted to ask the user about taking a decision between yes
or no in response of any particular action taken by the user, by remaining in the same activity and
without changing the screen, you can use Alert Dialog.

In order to make an alert dialog, you need to make an object of AlertDialogBuilder which an inner
class of AlertDialog. Its syntax is given below

[Link] alertDialogBuilder = new [Link](this);

Now you have to set the positive (yes) or negative (no) button using the object of the
AlertDialogBuilder class. Its syntax is

[Link](CharSequence text,
[Link] listener)

[Link](CharSequence text,
[Link] listener)

Apart from this , you can use other functions provided by the builder class to customize the alert
dialog. These are listed below

[Link] Method type & description

1 setIcon(Drawable icon)

This method set the icon of the alert dialog box.

2 setCancelable(boolean cancel able)

This method sets the property that the dialog can be cancelled or not

3 setMessage(CharSequence message)

This method sets the message to be displayed in the alert dialog


4 setMultiChoiceItems(CharSequence[] items, boolean[] checkedItems,
[Link] listener)

This method sets list of items to be displayed in the dialog as the content. The
selected option will be notified by the listener

5 setOnCancelListener([Link] onCancelListener)

This method Sets the callback that will be called if the dialog is cancelled.

6 setTitle(CharSequence title)

This method set the title to be appear in the dialog

After creating and setting the dialog builder , you will create an alert dialog by calling the create()
method of the builder class. Its syntax is

AlertDialog alertDialog = [Link]();

[Link]();

This will create the alert dialog and will show it on the screen.

Dialog fragment
Before enter into an example we should need to know dialog [Link] fragment is a
fragment which can show fragment in dialog box

public class DialogFragment extends DialogFragment {

@Override

public Dialog onCreateDialog(Bundle savedInstanceState) {

// Use the Builder class for convenient dialog construction

[Link] builder = new [Link](getActivity());

[Link]([Link], new [Link]() {

public void onClick(DialogInterface dialog, int id) {

[Link](this,"enter a text here",Toast.LENTH_SHORT).show();

})

.setNegativeButton([Link], new [Link]() {


public void onClick(DialogInterface dialog, int id) {

finish();

});

// Create the AlertDialog object and return it

return [Link]();

List dialog
It has used to show list of items in a dialog [Link] suppose, user need to select a list of items or
else need to click a item from multiple list of [Link] this situation we can use list dialog.

public Dialog onCreateDialog(Bundle savedInstanceState) {

[Link] builder = new [Link](getActivity());

[Link](Pick a Color)

.setItems([Link].colors_array, new [Link]() {

public void onClick(DialogInterface dialog, int which) {

// The 'which' argument contains the index position

// of the selected item

});

return [Link]();

Single-choice list dialog


It has used to add single choice list to Dialog [Link] can check or uncheck as per user choice.

public Dialog onCreateDialog(Bundle savedInstanceState) {

mSelectedItems = new ArrayList();

[Link] builder = new [Link](getActivity());

[Link]("This is list choice dialog box");


.setMultiChoiceItems([Link], null,new
[Link]() {

@Override

public void onClick(DialogInterface dialog, int which, boolean isChecked) {

if (isChecked) {

// If the user checked the item, add it to the selected items

[Link](which);

else if ([Link](which)) {

// Else, if the item is already in the array, remove it

[Link]([Link](which));

})

// Set the action buttons

.setPositiveButton([Link], new [Link]() {

@Override

public void onClick(DialogInterface dialog, int id) {

// User clicked OK, so save the mSelectedItems results somewhere

// or return them to the component that opened the dialog

...

})

.setNegativeButton([Link], new [Link]() {

@Override

public void onClick(DialogInterface dialog, int id) {

...

});
return [Link]();

Example
The following example demonstrates the use of AlertDialog in android.

To experiment with this example , you need to run this on an emulator or an actual device.

Step Description
s

1 You will use Android studio to create an Android application and name it as My
Application under a package package [Link];
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/[Link] file to add alert dialog code to launch the dialog.

3 Modify layout XML file res/layout/activity_main.xml add any GUI component if


required.

4 No need to change default string constants. Android studio takes care of default
strings at values/[Link]

9 Run the application and choose a running android device and install the application
on it and verify the results.

Here is the modified code of src/[Link]

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends ActionBarActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);

public void open(View view){

[Link] alertDialogBuilder = new [Link](this);

[Link]("Are you sure,You wanted to make decision");

[Link]("yes", new
[Link]() {

@Override

public void onClick(DialogInterface arg0, int arg1) {

[Link]([Link],"You clicked yes


button",Toast.LENGTH_LONG).show();

});

[Link]("No",new [Link]()
{

@Override

public void onClick(DialogInterface dialog, int which) {

finish();

});
AlertDialog alertDialog = [Link]();

[Link]();

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link].menu_main, menu);

return true;

@Override

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 [Link].

int id = [Link]();

//noinspection SimplifiableIfStatement

if (id == [Link].action_settings) {

return true;

return [Link](item);

Here is the modified code of res/layout/activity_main.xml

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"

tools:context=".MainActivity">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Alert Dialog"

android:id="@+id/textView"

android:textSize="35dp"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorialspoint"

android:id="@+id/textView2"

android:textColor="#ff3eff0f"

android:textSize="35dp"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true" />

<ImageView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/imageView"

android:src="@drawable/logo"

android:layout_below="@+id/textView2"

android:layout_alignRight="@+id/textView2"

android:layout_alignEnd="@+id/textView2"

android:layout_alignLeft="@+id/textView"
android:layout_alignStart="@+id/textView" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Alert dialog"

android:id="@+id/button"

android:layout_below="@+id/imageView"

android:layout_alignRight="@+id/textView2"

android:layout_alignEnd="@+id/textView2"

android:layout_marginTop="42dp"

android:onClick="open"

android:layout_alignLeft="@+id/imageView"

android:layout_alignStart="@+id/imageView" />

</RelativeLayout>

Here is [Link]

<resources>

<string name="app_name">My Application</string>

<string name="hello_world">Hello world!</string>

<string name="action_settings">Settings</string>

</resources>

Here is the default code of [Link]

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

<manifest xmlns:android="[Link]

package="[Link]"

android:versionCode="1"

android:versionName="1.0" >

<application

android:allowBackup="true"

android:icon="@drawable/ic_launcher"
android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name="[Link]"

android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>

</manifest>

Android - Animations Tutorial


Animation is the process of creating motion and shape change

Animation in android is possible from many ways. In this chapter we will discuss one easy and
widely used way of making animation called tweened animation.

Tween Animation
Tween Animation takes some parameters such as start value, end value, size, time duration,
rotation angle e.t.c and performs the required animation on that object. It can be applied to any type
of object. So in order to use this, android has provided us a class called Animation.

In order to perform animation in android, we are going to call a static function loadAnimation() of the
class AnimationUtils. We are going to receive the result in an instance of Animation Object. Its
syntax is as follows −

Animation animation = [Link](getApplicationContext(),


[Link]);
Note the second parameter. It is the name of the our animation xml file. You have to create a new
folder called anim under res directory and make an xml file under anim folder.

This animation class has many useful functions which are listed below:

[Link] Method & Description

1 start()

This method starts the animation.

2 setDuration(long duration)

This method sets the duration of an animation.

3 getDuration()

This method gets the duration which is set by above method

4 end()

This method ends the animation.

5 cancel()

This method cancels the animation.

In order to apply this animation to an object , we will just call the startAnimation() method of the
object. Its syntax is −

ImageView image1 = (ImageView)findViewById([Link].imageView1);

[Link](animation);

Example
The following example demonstrates the use of Animation in android. You would be able to choose
different type of animation from the menu and the selected animation will be applied on an
imageView on the screen.
To experiment with this example , you need to run this on an emulator or an actual device.

Step Description
s

1 You will use Android studio IDE to create an Android application and name it as My
Application under a package [Link]. 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/[Link] file to add animation code

3 Modify layout XML file res/layout/activity_main.xml add any GUI component if


required.

4 Create a new folder under res directory and call it anim. Confim it by visiting res/anim

5 Right click on anim and click on new and select Android XML file You have to create
different files that are listed below.

6 Create files [Link],[Link],[Link],[Link],[Link],[Link] and


add the XML code.

7 No need to change default string constants. Android studio takes care of default
constants at values/[Link].

8 Run the application and choose a running android device and install the application
on it and verify the results.

Here is the modified code of [Link].

package [Link];

import [Link];

import [Link];
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends Activity {

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);

public void clockwise(View view){

ImageView image = (ImageView)findViewById([Link]);

Animation animation = [Link](getApplicationContext(),


[Link]);

[Link](animation);

public void zoom(View view){

ImageView image = (ImageView)findViewById([Link]);

Animation animation1 = [Link](getApplicationContext(),


[Link]);

[Link](animation1);

public void fade(View view){

ImageView image = (ImageView)findViewById([Link]);

Animation animation1 = [Link](getApplicationContext(),


[Link]);

[Link](animation1);
}

public void blink(View view){

ImageView image = (ImageView)findViewById([Link]);

Animation animation1 = [Link](getApplicationContext(),


[Link]);

[Link](animation1);

public void move(View view){

ImageView image = (ImageView)findViewById([Link]);

Animation animation1 = [Link](getApplicationContext(),


[Link]);

[Link](animation1);

public void slide(View view){

ImageView image = (ImageView)findViewById([Link]);

Animation animation1 = [Link](getApplicationContext(),


[Link]);

[Link](animation1);

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link].menu_main, menu);

return true;

@Override

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 [Link].

int id = [Link]();

//noinspection SimplifiableIfStatement

if (id == [Link].action_settings) {

return true;

return [Link](item);

Here is the modified code of res/layout/activity_main.xml.

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Alert Dialog"

android:id="@+id/textView"

android:textSize="35dp"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true" />

<TextView

android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:text="Tutorialspoint"

android:id="@+id/textView2"

android:textColor="#ff3eff0f"

android:textSize="35dp"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true" />

<ImageView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/imageView"

android:src="@drawable/logo"

android:layout_below="@+id/textView2"

android:layout_alignRight="@+id/textView2"

android:layout_alignEnd="@+id/textView2"

android:layout_alignLeft="@+id/textView"

android:layout_alignStart="@+id/textView"/>

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="zoom"

android:id="@+id/button"

android:layout_below="@+id/imageView"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:layout_marginTop="40dp"

android:onClick="clockwise"/>

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"
android:text="clockwise"

android:id="@+id/button2"

android:layout_alignTop="@+id/button"

android:layout_centerHorizontal="true"

android:onClick="zoom"/>

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="fade"

android:id="@+id/button3"

android:layout_alignTop="@+id/button2"

android:layout_alignParentRight="true"

android:layout_alignParentEnd="true"

android:onClick="fade"/>

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="blink"

android:onClick="blink"

android:id="@+id/button4"

android:layout_below="@+id/button"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="move"

android:onClick="move"

android:id="@+id/button5"

android:layout_below="@+id/button2"
android:layout_alignRight="@+id/button2"

android:layout_alignEnd="@+id/button2"

android:layout_alignLeft="@+id/button2"

android:layout_alignStart="@+id/button2" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="slide"

android:onClick="slide"

android:id="@+id/button6"

android:layout_below="@+id/button3"

android:layout_toRightOf="@+id/textView"

android:layout_toEndOf="@+id/textView" />

</RelativeLayout>

Here is the code of res/anim/[Link].

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

<set xmlns:android="[Link]

<scale xmlns:android="[Link]

android:fromXScale="0.5"

android:toXScale="3.0"

android:fromYScale="0.5"

android:toYScale="3.0"

android:duration="5000"

android:pivotX="50%"

android:pivotY="50%" >

</scale>

<scale xmlns:android="[Link]

android:startOffset="5000"
android:fromXScale="3.0"

android:toXScale="0.5"

android:fromYScale="3.0"

android:toYScale="0.5"

android:duration="5000"

android:pivotX="50%"

android:pivotY="50%" >

</scale>

</set>

Here is the code of res/anim/[Link].

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

<set xmlns:android="[Link]

<rotate xmlns:android="[Link]

android:fromDegrees="0"

android:toDegrees="360"

android:pivotX="50%"

android:pivotY="50%"

android:duration="5000" >

</rotate>

<rotate xmlns:android="[Link]

android:startOffset="5000"

android:fromDegrees="360"

android:toDegrees="0"

android:pivotX="50%"

android:pivotY="50%"

android:duration="5000" >

</rotate>

</set>
Here is the code of res/anim/[Link].

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

<set xmlns:android="[Link]

android:interpolator="@android:anim/accelerate_interpolator" >

<alpha

android:fromAlpha="0"

android:toAlpha="1"

android:duration="2000" >

</alpha>

<alpha

android:startOffset="2000"

android:fromAlpha="1"

android:toAlpha="0"

android:duration="2000" >

</alpha>

</set>

Here is the code of res/anim/[Link].

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

<set xmlns:android="[Link]

<alpha android:fromAlpha="0.0"

android:toAlpha="1.0"

android:interpolator="@android:anim/accelerate_interpolator"

android:duration="600"

android:repeatMode="reverse"

android:repeatCount="infinite"/>

</set>

Here is the code of res/anim/[Link].


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

<set

xmlns:android="[Link]

android:interpolator="@android:anim/linear_interpolator"

android:fillAfter="true">

<translate

android:fromXDelta="0%p"

android:toXDelta="75%p"

android:duration="800" />

</set>

Here is the code of res/anim/[Link]

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

<set xmlns:android="[Link]

android:fillAfter="true" >

<scale

android:duration="500"

android:fromXScale="1.0"

android:fromYScale="1.0"

android:interpolator="@android:anim/linear_interpolator"

android:toXScale="1.0"

android:toYScale="0.0" />

</set>

Here is the modified code of res/values/[Link].

<resources>

<string name="app_name">My Application</string>

<string name="hello_world">Hello world!</string>

<string name="action_settings">Settings</string>

</resources>
Here is the default code of [Link].

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

<manifest xmlns:android="[Link]

package="[Link]"

android:versionCode="1"

android:versionName="1.0" >

<application

android:allowBackup="true"

android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name="[Link]"

android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>

</manifest>

Android - Audio Capture Tutorial


Android has a built in microphone through which you can capture audio and store it , or play it in
your phone. There are many ways to do that but the most common way is through MediaRecorder
class.
Android provides MediaRecorder class to record audio or video. In order to use MediaRecorder
class ,you will first create an instance of MediaRecorder class. Its syntax is given below.

MediaRecorder myAudioRecorder = new MediaRecorder();

Now you will set the source , output and encoding format and output file. Their syntax is given
below.

[Link]([Link]);

[Link]([Link].THREE_GPP);

[Link]([Link].AMR_NB);

[Link](outputFile);

After specifying the audio source and format and its output file, we can then call the two basic
methods prepare and start to start recording the audio.

[Link]();

[Link]();

Apart from these methods , there are other methods listed in the MediaRecorder class that allows
you more control over audio and video recording.

[Link] Method & description

1 setAudioSource()

This method specifies the source of audio to be recorded

2 setVideoSource()

This method specifies the source of video to be recorded

3 setOutputFormat()

This method specifies the audio format in which audio to be stored

4 setAudioEncoder()
This method specifies the audio encoder to be used

5 setOutputFile()

This method configures the path to the file into which the recorded audio is to be
stored

6 stop()

This method stops the recording process.

7 release()

This method should be called when the recorder instance is needed.

Example
This example provides demonstration of MediaRecorder class to capture audio and then
MediaPlayer class to play that recorded audio.

To experiment with this example , you need to run this on an actual device.

Step Description
s

1 You will use Android studio IDE to create an Android application and name it as
AudioCapture under a package [Link];. 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/[Link] file to add AudioCapture code

3 Modify layout XML file res/layout/activity_main.xml add any GUI component if


required.

4 Modify [Link] to add necessary permissions.


5 Run the application and choose a running android device and install the application
on it and verify the results.

Here is the content of src/[Link]

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends Activity {

Button play,stop,record;

private MediaRecorder myAudioRecorder;

private String outputFile = null;

@Override

protected void onCreate(Bundle savedInstanceState) {


[Link](savedInstanceState);

setContentView([Link].activity_main);

play=(Button)findViewById([Link].button3);

stop=(Button)findViewById([Link].button2);

record=(Button)findViewById([Link]);

[Link](false);

[Link](false);

outputFile = [Link]().getAbsolutePath() +
"/recording.3gp";;

myAudioRecorder=new MediaRecorder();

[Link]([Link]);

[Link]([Link].THREE_GPP);

[Link]([Link].AMR_NB);

[Link](outputFile);

[Link](new [Link]() {

@Override

public void onClick(View v) {

try {

[Link]();

[Link]();

catch (IllegalStateException e) {

// TODO Auto-generated catch block

[Link]();

catch (IOException e) {

// TODO Auto-generated catch block


[Link]();

[Link](false);

[Link](true);

[Link](getApplicationContext(), "Recording started",


Toast.LENGTH_LONG).show();

});

[Link](new [Link]() {

@Override

public void onClick(View v) {

[Link]();

[Link]();

myAudioRecorder = null;

[Link](false);

[Link](true);

[Link](getApplicationContext(), "Audio recorded


successfully",Toast.LENGTH_LONG).show();

});

[Link](new [Link]() {

@Override

public void onClick(View v) throws


IllegalArgumentException,SecurityException,IllegalStateException {

MediaPlayer m = new MediaPlayer();

try {

[Link](outputFile);
}

catch (IOException e) {

[Link]();

try {

[Link]();

catch (IOException e) {

[Link]();

[Link]();

[Link](getApplicationContext(), "Playing audio",


Toast.LENGTH_LONG).show();

});

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link].menu_main, menu);

return true;

@Override

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 [Link].


int id = [Link]();

//noinspection SimplifiableIfStatement

if (id == [Link].action_settings) {

return true;

return [Link](item);

Here is the content of activity_main.xml

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link]

android:layout_width="match_parent"

android:layout_height="match_parent"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"

tools:context=".MainActivity">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Android Audio Recording"

android:id="@+id/textView"

android:textSize="30dp"

android:layout_alignParentTop="true"

android:layout_alignParentRight="true"

android:layout_alignParentEnd="true" />

<TextView
android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorialspoint"

android:id="@+id/textView2"

android:textColor="#ff3eff0f"

android:textSize="35dp"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true" />

<ImageView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/imageView"

android:src="@drawable/logo"

android:layout_below="@+id/textView2"

android:layout_alignLeft="@+id/textView2"

android:layout_alignStart="@+id/textView2"

android:layout_alignRight="@+id/textView2"

android:layout_alignEnd="@+id/textView2" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Record"

android:id="@+id/button"

android:layout_below="@+id/imageView"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:layout_marginTop="59dp" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"
android:text="Stop"

android:id="@+id/button2"

android:layout_alignTop="@+id/button"

android:layout_centerHorizontal="true" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="play"

android:id="@+id/button3"

android:layout_alignTop="@+id/button2"

android:layout_alignRight="@+id/textView"

android:layout_alignEnd="@+id/textView" />

</RelativeLayout>

Here is the content of [Link]

<resources>

<string name="app_name">My Application</string>

<string name="hello_world">Hello world!</string>

<string name="action_settings">Settings</string>

</resources>

Here is the content of [Link]

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

<manifest xmlns:android="[Link]

package="[Link]"

android:versionCode="1"

android:versionName="1.0" >

<uses-permission android:name="[Link].WRITE_EXTERNAL_STORAGE"/>

<uses-permission android:name="[Link].RECORD_AUDIO" />


<application

android:allowBackup="true"

android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name="[Link]"

android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>

</manifest>

Android - Audio Manager Tutorial


You can easily control your ringer volume and ringer profile i-e:(silent,vibrate,loud e.t.c) in android.
Android provides AudioManager class that provides access to these controls.

In order to use AndroidManager class, you have to first create an object of AudioManager class by
calling the getSystemService() method. Its syntax is given below.

private AudioManager myAudioManager;

myAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);

Once you instantiate the object of AudioManager class, you can use setRingerModemethod to set
the audio or ringer profile of your device. Its syntax is given below.
[Link](AudioManager.RINGER_MODE_VIBRATE);

The method setRingerMode takes an integer number as a parameter. For each mode , an integer
number is assigned that will differentiate between different modes. The possible modes are.

[Link] Mode & Description

1 RINGER_MODE_VIBRATE

This Mode sets the device at vibrate mode.

2 RINGER_MODE_NORMAL

This Mode sets the device at normal(loud) mode.

3 RINGER_MODE_SILENT

This Mode sets the device at silent mode.

Once you have set the mode , you can call the getRingerMode() method to get the set state of the
system. Its syntax is given below.

int mod = [Link]();

Apart from the getRingerMode method, there are other methods available in the AudioManager
class to control the volume and other modes. They are listed below.

[Link] Method & description

1 adjustVolume(int direction, int flags)

This method adjusts the volume of the most relevant stream

2 getMode()

This method returns the current audio mode

3 getStreamMaxVolume(int streamType)
This method returns the maximum volume index for a particular stream

4 getStreamVolume(int streamType)

This method returns the current volume index for a particular stream

5 isMusicActive()

This method checks whether any music is active.

6 startBluetoothSco()

This method Start bluetooth SCO audio connection

7 stopBluetoothSco()

This method stop bluetooth SCO audio connection.

Example
The below example demonstrates the use of AudioManager class. It crates a application that allows
you to set different ringer modes for your device.

To experiment with this example , you need to run this on an actual device.

Step Description
s

1 You will use Android studio IDE to create an Android application under a package
[Link]; 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/[Link] file to add AudioManager code

3 Modify layout XML file res/layout/activity_main.xml add any GUI component if


required.

4 Modify res/values/[Link] file and add necessary string components.

5 Modify [Link] to add necessary permissions.

6 Run the application and choose a running android device and install the application
on it and verify the results.

Here is the content of src/[Link]

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];
public class MainActivity extends Activity {

Button mode,ring,vibrate,silent;

private AudioManager myAudioManager;

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);

vibrate=(Button)findViewById([Link].button3);

ring=(Button)findViewById([Link].button2);

mode=(Button)findViewById([Link]);

silent=(Button)findViewById([Link].button4);

myAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);

[Link](new [Link]() {

@Override

public void onClick(View v) {

[Link](AudioManager.RINGER_MODE_VIBRATE);

[Link]([Link],"Now in Vibrate
Mode",Toast.LENGTH_LONG).show();

});

[Link](new [Link]() {

@Override

public void onClick(View v) {

[Link](AudioManager.RINGER_MODE_NORMAL);

[Link]([Link],"Now in Ringing
Mode",Toast.LENGTH_LONG).show();

}
});

[Link](new [Link]() {

@Override

public void onClick(View v) {

[Link](AudioManager.RINGER_MODE_SILENT);

[Link]([Link],"Now in silent
Mode",Toast.LENGTH_LONG).show();

});

[Link](new [Link]() {

@Override

public void onClick(View v) {

int mod=[Link]();

if(mod==AudioManager.RINGER_MODE_VIBRATE){

[Link]([Link],"Now in Vibrate
Mode",Toast.LENGTH_LONG).show();

else if(mod==AudioManager.RINGER_MODE_NORMAL){

[Link]([Link],"Now in Ringing
Mode",Toast.LENGTH_LONG).show();

else

[Link]([Link],"Now in Vibrate
Mode",Toast.LENGTH_LONG).show();

});

}
@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link].menu_main, menu);

return true;

@Override

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 [Link].

int id = [Link]();

//noinspection SimplifiableIfStatement

if (id == [Link].action_settings) {

return true;

return [Link](item);

Here is the content of activity_main.xml

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Android Audio Recording"

android:id="@+id/textView"

android:textSize="30dp"

android:layout_alignParentTop="true"

android:layout_alignParentRight="true"

android:layout_alignParentEnd="true" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorialspoint"

android:id="@+id/textView2"

android:textColor="#ff3eff0f"

android:textSize="35dp"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true" />

<ImageView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/imageView"

android:src="@drawable/logo"

android:layout_below="@+id/textView2"

android:layout_alignLeft="@+id/textView2"

android:layout_alignStart="@+id/textView2"

android:layout_alignRight="@+id/textView2"

android:layout_alignEnd="@+id/textView2" />

<Button
android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Mode"

android:id="@+id/button"

android:layout_below="@+id/imageView"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:layout_marginTop="59dp" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Ring"

android:id="@+id/button2"

android:layout_alignTop="@+id/button"

android:layout_centerHorizontal="true" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="vibrate"

android:id="@+id/button3"

android:layout_alignTop="@+id/button2"

android:layout_alignRight="@+id/textView"

android:layout_alignEnd="@+id/textView" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Silent"

android:id="@+id/button4"

android:layout_below="@+id/button2"

android:layout_alignLeft="@+id/button2"
android:layout_alignStart="@+id/button2" />

</RelativeLayout>

Here is the content of [Link]

<resources>

<string name="app_name">My Application</string>

<string name="hello_world">Hello world!</string>

<string name="action_settings">Settings</string>

</resources>

Here is the content of [Link]

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

<manifest xmlns:android="[Link]

package="[Link]"

android:versionCode="1"

android:versionName="1.0" >

<application

android:allowBackup="true"

android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name="[Link]"

android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>
</activity>

</application>

</manifest>

Android - Auto Complete Tutorial

If you want to get suggestions, when you type in an editable text field, you can do this via
AutoCompleteTextView. It provides suggestions automatically when the user is typing. The list of
suggestions is displayed in a drop down menu from which the user can choose an item to replace
the content of the edit box with.

In order to use AutoCompleteTextView you have to first create an AutoCompletTextView Field in


the xml. Its syntax is given below.

<AutoCompleteTextView

android:id="@+id/autoCompleteTextView1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true"

android:layout_marginTop="65dp"

android:ems="10" >

After that, you have to get a reference of this textview in java. Its syntax is given below.

private AutoCompleteTextView actv;

actv = (AutoCompleteTextView) findViewById([Link].autoCompleteTextView1);

The the next thing you need to do is to specify the list of suggestions items to be displayed. You
can specify the list items as a string array in java or in [Link]. Its syntax is given below.

String[] countries = getResources().getStringArray([Link].list_of_countries);

ArrayAdapter<String> adapter = new


ArrayAdapter<String>(this,[Link].simple_list_item_1,countries);
[Link](adapter);

The array adapter class is responsible for displaying the data as list in the suggestion box of the
text field. The setAdapter method is used to set the adapter of the autoCompleteTextView. Apart
from these methods, the other methods of Auto Complete are listed below.

[Link] Method & description

1 getAdapter()

This method returns a filterable list adapter used for auto completion

2 getCompletionHint()

This method returns optional hint text displayed at the bottom of the the matching list

3 getDropDownAnchor()

This method returns returns the id for the view that the auto-complete drop down list
is anchored to.

4 getListSelection()

This method returns the position of the dropdown view selection, if there is one

5 isPopupShowing()

This method indicates whether the popup menu is showing

6 setText(CharSequence text, boolean filter)

This method sets text except that it can disable filtering

7 showDropDown()

This method displays the drop down on screen.


Example
The below example demonstrates the use of AutoCompleteTextView class. It crates a basic
application that allows you to type in and it displays suggestions on your device.

To experiment with this example , you need to run this on an actual device or in an emulator.

Step Description
s

1 You will use Android Studio to create an Android application under a package
package [Link]. 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/[Link] file to add AutoCompleteTextView code

3 Modify layout XML file res/layout/activity_main.xml add any GUI component if


required.

4 Run the application and choose a running android device and install the application
on it and verify the results.

Here is the content of src/[Link]

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends Activity {

AutoCompleteTextView text;

MultiAutoCompleteTextView text1;

String[] languages={"Android ","java","IOS","SQL","JDBC","Web services"};

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);

text=(AutoCompleteTextView)findViewById([Link].autoCompleteTextView1);

text1=(MultiAutoCompleteTextView)findViewById([Link].multiAutoCompleteTextView1);

ArrayAdapter adapter = new


ArrayAdapter(this,[Link].simple_list_item_1,languages);
[Link](adapter);

[Link](1);

[Link](adapter);

[Link](new [Link]());

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link].menu_main, menu);

return true;

@Override

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 [Link].

int id = [Link]();

//noinspection SimplifiableIfStatement

if (id == [Link].action_settings) {

return true;

return [Link](item);

Here is the content of activity_main.xml

<RelativeLayout xmlns:android="[Link]
xmlns:tools=[Link]
android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Android Auto Complete"

android:id="@+id/textView"

android:textSize="30dp"

android:layout_alignParentTop="true"

android:layout_alignParentRight="true"

android:layout_alignParentEnd="true" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorialspoint"

android:id="@+id/textView2"

android:textColor="#ff3eff0f"

android:textSize="35dp"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true" />

<ImageView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/imageView"

android:src="@drawable/logo"

android:layout_below="@+id/textView2"
android:layout_alignLeft="@+id/textView2"

android:layout_alignStart="@+id/textView2"

android:layout_alignRight="@+id/textView2"

android:layout_alignEnd="@+id/textView2" />

<AutoCompleteTextView

android:id="@+id/autoCompleteTextView1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:ems="10"

android:layout_below="@+id/imageView"

android:layout_alignLeft="@+id/imageView"

android:layout_alignStart="@+id/imageView"

android:layout_marginTop="72dp"

android:hint="AutoComplete TextView">

<requestFocus />

</AutoCompleteTextView>

<MultiAutoCompleteTextView

android:id="@+id/multiAutoCompleteTextView1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:ems="10"

android:layout_below="@+id/autoCompleteTextView1"

android:layout_alignLeft="@+id/autoCompleteTextView1"

android:layout_alignStart="@+id/autoCompleteTextView1"

android:hint="Multi Auto Complete " />

</RelativeLayout>

Here is the content of [Link]

<resources>

<string name="app_name">My Application</string>


<string name="hello_world">Hello world!</string>

<string name="action_settings">Settings</string>

</resources>

Here is the content of [Link]

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

<manifest xmlns:android="[Link]

package="[Link]"

android:versionCode="1"

android:versionName="1.0" >

<application

android:allowBackup="true"

android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name="[Link]"

android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>

</manifest>
Android - Best Practices Tutorial
There are some practices that you can follow while developing android application. These are
suggested by the android itself and they keep on improving with respect to time.

These best practices include interaction design features, performance, security and privacy,
compatibility, testing, distributing and monetizing tips. They are narrowed down and are listed as
below.

Best Practices - User input


Every text field is intended for a different job. For example, some text fields are for text and some
are for numbers. If it is for numbers then it is better to display the numeric keypad when that
textfield is focused. Its syntax is.

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/editText"

android:layout_alignParentRight="true"

android:layout_alignParentEnd="true"

android:hint="User Name"

android:layout_below="@+id/imageView"

android:layout_alignLeft="@+id/imageView"

android:layout_alignStart="@+id/imageView"

android:numeric="integer" />

Other then that if your field is for password, and then it must show a password hint, so that the user
can easily remember the password. It can be achieved as.

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/editText2"

android:layout_alignLeft="@+id/editText"

android:layout_alignStart="@+id/editText"

android:hint="Pass Word"
android:layout_below="@+id/editText"

android:layout_alignRight="@+id/editText"

android:layout_alignEnd="@+id/editText"

android:password="true" />

Best Practices - Background jobs


There are certain jobs in an application that are running in an application background. Their job
might be to fetch some thing from the internet , playing music e.t.c. It is recommended that the long
awaiting tasks should not be done in the UI thread and rather in the background by services or
AsyncTask.

AsyncTask Vs Services.
Both are used for doing background tasks , but the service is not affected by most user interface life
cycle events, so it continues to run in circumstances that would shut down an AsyncTask.

Best Practices - Performance


Your application performance should be up-to the mark. But it should perform differently not on the
front end, but on the back end when it the device is connected to a power source or charging.
Charging could be of from USB and from wire cable.

When your device is charging itself, it is recommended to update your application settings if any,
such as maximizing your refresh rate whenever the device is connected. It can be done as this.

IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);

Intent batteryStatus = [Link](null, ifilter);

// Are we charging / charged? Full or charging.

int status = [Link](BatteryManager.EXTRA_STATUS, -1);

// How are we charging? From AC or USB.

int chargePlug = [Link](BatteryManager.EXTRA_PLUGGED, -1);


Best Practices - Security and privacy
It is very important that your application should be secure and not only the application, but the user
data and the application data should also be secured. The security can be increased by the
following factors.

 Use internal storage rather then external for storing applications files
 Use content providers wherever possible
 Use SSl when connecting to the web
 Use appropriate permissions for accessing different functionalities of device

Example
The below example demonstrates some of the best practices you should follow when developing
android application. It crates a basic application that allows you to specify how to use text fields and
how to increase performance by checking the charging status of the phone.

To experiment with this example , you need to run this on an actual device.

Step Description
s

1 You will use Android studio IDE to create an Android application under a package
[Link];. 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/[Link] file to add the code

3 Modify layout XML file res/layout/activity_main.xml add any GUI component if


required.

4 Run the application and choose a running android device and install the application
on it and verify the results.

Here is the content of src/[Link]

package [Link];
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends ActionBarActivity {

EditText ed1,ed2;

Button b1;

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);
setContentView([Link].activity_main);

ed1=(EditText)findViewById([Link]);

ed2=(EditText)findViewById([Link].editText2);

b1=(Button)findViewById([Link]);

[Link](new [Link]() {

@Override

public void onClick(View v) {

IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);

Intent batteryStatus = registerReceiver(null, ifilter);

int status = [Link](BatteryManager.EXTRA_STATUS, -1);

boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||

status == BatteryManager.BATTERY_STATUS_FULL;

int chargePlug = [Link](BatteryManager.EXTRA_PLUGGED,-


1);

boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;

boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;

if(usbCharge){

[Link](getApplicationContext(),"Mobile is charging on
USB",Toast.LENGTH_LONG).show();

else

[Link](getApplicationContext(),"Mobile is charging on
AC",Toast.LENGTH_LONG).show();

});

}
@Override

protected void onDestroy() {

[Link]();

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link].menu_main, menu);

return true;

@Override

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 [Link].

int id = [Link]();

//noinspection SimplifiableIfStatement

if (id == [Link].action_settings) {

return true;

return [Link](item);

Here is the content of activity_main.xml

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView android:text="Bluetooth Example" android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/textview"

android:textSize="35dp"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials point"

android:id="@+id/textView"

android:layout_below="@+id/textview"

android:layout_centerHorizontal="true"

android:textColor="#ff7aff24"

android:textSize="35dp" />

<ImageView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/imageView"

android:src="@drawable/abc"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true" />

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"
android:id="@+id/editText"

android:layout_alignParentRight="true"

android:layout_alignParentEnd="true"

android:hint="User Name"

android:layout_below="@+id/imageView"

android:layout_alignLeft="@+id/imageView"

android:layout_alignStart="@+id/imageView"

android:numeric="integer" />

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/editText2"

android:layout_alignLeft="@+id/editText"

android:layout_alignStart="@+id/editText"

android:hint="Pass Word"

android:layout_below="@+id/editText"

android:layout_alignRight="@+id/editText"

android:layout_alignEnd="@+id/editText"

android:password="true" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Check"

android:id="@+id/button"

android:layout_below="@+id/editText2"

android:layout_centerHorizontal="true" />

</RelativeLayout>

Here is the content of [Link]

<resources>
<string name="app_name">My Application</string>

<string name="hello_world">Hello world!</string>

<string name="action_settings">Settings</string>

</resources>

Here is the content of [Link]

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

<manifest xmlns:android="[Link]

package="[Link]"

android:versionCode="1"

android:versionName="1.0" >

<application

android:allowBackup="true"

android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name="[Link]"

android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>

</manifest>
Android - Bluetooth Tutorial
Among many ways, Bluetooth is a way to send or receive data between two different devices.
Android platform includes support for the Bluetooth framework that allows a device to wirelessly
exchange data with other Bluetooth devices.

Android provides Bluetooth API to perform these different operations.

 Scan for other Bluetooth devices


 Get a list of paired devices
 Connect to other devices through service discovery

Android provides BluetoothAdapter class to communicate with Bluetooth. Create an object of this
calling by calling the static method getDefaultAdapter(). Its syntax is given below.

private BluetoothAdapter BA;

BA = [Link]();

In order to enable the Bluetooth of your device, call the intent with the following Bluetooth constant
ACTION_REQUEST_ENABLE. Its syntax is.

Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

startActivityForResult(turnOn, 0);

Apart from this constant, there are other constants provided the API , that supports different tasks.
They are listed below.

[Link] Constant & description

1 ACTION_REQUEST_DISCOVERABLE

This constant is used for turn on discovering of bluetooth

2 ACTION_STATE_CHANGED

This constant will notify that Bluetooth state has been changed

3 ACTION_FOUND
This constant is used for receiving information about each device that is discovered

Once you enable the Bluetooth , you can get a list of paired devices by calling getBondedDevices()
method. It returns a set of bluetooth devices. Its syntax is.

private Set<BluetoothDevice>pairedDevices;

pairedDevices = [Link]();

Apart form the parried Devices , there are other methods in the API that gives more control over
Blueetooth. They are listed below.

[Link] Method & description

1 enable()

This method enables the adapter if not enabled

2 isEnabled()

This method returns true if adapter is enabled

3 disable()

This method disables the adapter

4 getName()

This method returns the name of the Bluetooth adapter

5 setName(String name)

This method changes the Bluetooth name

6 getState()

This method returns the current state of the Bluetooth Adapter.


7 startDiscovery()

This method starts the discovery process of the Bluetooth for 120 seconds.

Example
This example provides demonstration of BluetoothAdapter class to manipulate Bluetooth and show
list of paired devices by the Bluetooth.

To experiment with this example , you need to run this on an actual device.

Step Description
s

1 You will use Android studio to create an Android application a package


[Link];. 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/[Link] file to add the code

3 Modify layout XML file res/layout/activity_main.xml add any GUI component if


required.

4 Modify [Link] to add necessary permissions.

5 Run the application and choose a running android device and install the application
on it and verify the results.

Here is the content of src/[Link]

package [Link];

import [Link];

import [Link];

import [Link];
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends Activity {

Button b1,b2,b3,b4;

private BluetoothAdapter BA;

private Set<BluetoothDevice>pairedDevices;

ListView lv;

@Override
protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);

b1 = (Button) findViewById([Link]);

b2=(Button)findViewById([Link].button2);

b3=(Button)findViewById([Link].button3);

b4=(Button)findViewById([Link].button4);

BA = [Link]();

lv = (ListView)findViewById([Link]);

public void on(View v){

if (![Link]()) {

Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

startActivityForResult(turnOn, 0);

[Link](getApplicationContext(),"Turned on",Toast.LENGTH_LONG).show();

else

[Link](getApplicationContext(),"Already on",
Toast.LENGTH_LONG).show();

public void off(View v){

[Link]();

[Link](getApplicationContext(),"Turned off" ,Toast.LENGTH_LONG).show();

public void visible(View v){

Intent getVisible = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);


startActivityForResult(getVisible, 0);

public void list(View v){

pairedDevices = [Link]();

ArrayList list = new ArrayList();

for(BluetoothDevice bt : pairedDevices)

[Link]([Link]());

[Link](getApplicationContext(),"Showing Paired
Devices",Toast.LENGTH_SHORT).show();

final ArrayAdapter adapter = new


ArrayAdapter(this,[Link].simple_list_item_1, list);

[Link](adapter);

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link].menu_main, menu);

return true;

Here is the content of activity_main.xml

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity"

android:transitionGroup="true">

<TextView android:text="Bluetooth Example" android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/textview"

android:textSize="35dp"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials point"

android:id="@+id/textView"

android:layout_below="@+id/textview"

android:layout_centerHorizontal="true"

android:textColor="#ff7aff24"

android:textSize="35dp" />

<ImageView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/imageView"

android:src="@drawable/abc"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true"

android:theme="@style/[Link]" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Turn On"
android:id="@+id/button"

android:layout_below="@+id/imageView"

android:layout_toStartOf="@+id/imageView"

android:layout_toLeftOf="@+id/imageView"

android:clickable="true"

android:onClick="on" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Get visible"

android:onClick="visible"

android:id="@+id/button2"

android:layout_alignBottom="@+id/button"

android:layout_centerHorizontal="true" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="List devices"

android:onClick="list"

android:id="@+id/button3"

android:layout_below="@+id/imageView"

android:layout_toRightOf="@+id/imageView"

android:layout_toEndOf="@+id/imageView" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="turn off"

android:onClick="off"

android:id="@+id/button4"

android:layout_below="@+id/button"
android:layout_alignParentLeft="true"

android:layout_alignParentStart="true" />

<ListView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/listView"

android:layout_alignParentBottom="true"

android:layout_alignLeft="@+id/button"

android:layout_alignStart="@+id/button"

android:layout_below="@+id/textView2" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Paired devices:"

android:id="@+id/textView2"

android:textColor="#ff34ff06"

android:textSize="25dp"

android:layout_below="@+id/button4"

android:layout_alignLeft="@+id/listView"

android:layout_alignStart="@+id/listView" />

</RelativeLayout>

Here is the content of [Link]

<resources>

<string name="app_name">My Application</string>

<string name="hello_world">Hello world!</string>

<string name="action_settings">Settings</string>

</resources>

Here is the content of [Link]


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

<manifest xmlns:android="[Link]

package="[Link]" >

<uses-permission android:name="[Link]"/>

<uses-permission android:name="[Link].BLUETOOTH_ADMIN"/>

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name=".MainActivity"

android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>

</manifest>

Let's try to run your application. I assume you have connected your actual Android Mobile device
with your computer. To run the app from Android studio, open one of your project's activity files and
click Run icon from the tool bar. Before starting your application, Android studio will display
following window to select an option where you want to run your Android application.
Now select Turn On to turn on the bluetooth. But as you select it , your Bluetooth will not be turned
on. In fact , it will ask your permission to enable the Bluetooth.

Android - Camera Tutorial


These are the following two ways, in which you can use camera in your application

 Using existing android camera application in our application


 Directly using Camera API provided by android in our application

Using existing android camera application in our


application
You will use MediaStore.ACTION_IMAGE_CAPTURE to launch an existing camera application
installed on your phone. Its syntax is given below
Intent intent = new Intent([Link].ACTION_IMAGE_CAPTURE);

Apart from the above, there are other available Intents provided by MediaStore. They are listed as
follows

[Link] Intent type and description

1 ACTION_IMAGE_CAPTURE_SECURE

It returns the image captured from the camera , when the device is secured

2 ACTION_VIDEO_CAPTURE

It calls the existing video application in android to capture video

3 EXTRA_SCREEN_ORIENTATION

It is used to set the orientation of the screen to vertical or landscape

4 EXTRA_FULL_SCREEN

It is used to control the user interface of the ViewImage

5 INTENT_ACTION_VIDEO_CAMERA

This intent is used to launch the camera in the video mode

6 EXTRA_SIZE_LIMIT

It is used to specify the size limit of video or image capture size

Now you will use the function startActivityForResult() to launch this activity and wait for its result. Its
syntax is given below

startActivityForResult(intent,0)

This method has been defined in the activity class. We are calling it from main activity. There are
methods defined in the activity class that does the same job , but used when you are not calling
from the activity but from somewhere else. They are listed below
[Link] Activity function description

1 startActivityForResult(Intent intent, int requestCode, Bundle options)

It starts an activity , but can take extra bundle of options with it

2 startActivityFromChild(Activity child, Intent intent, int requestCode)

It launch the activity when your activity is child of any other activity

3 startActivityFromChild(Activity child, Intent intent, int requestCode, Bundle


options)

It work same as above , but it can take extra values in the shape of bundle with it

4 startActivityFromFragment(Fragment fragment, Intent intent, int requestCode)

It launches activity from the fragment you are currently inside

5 startActivityFromFragment(Fragment fragment, Intent intent, int requestCode,


Bundle options)

It not only launches the activity from the fragment , but can take extra values with it

No matter which function you used to launch the activity , they all return the result. The result can
be obtained by overriding the function onActivityResult.

Example
Here is an example that shows how to launch the existing camera application to capture an image
and display the result in the form of bitmap

To experiment with this example , you need to run this on an actual device on which camera is
supported.

Step Description
s

1 You will use Android studio IDE to create an Android application and name it as
Camera under a [Link]. 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/[Link] file to add intent code to launch the activity and result
method to recieve the output.

3 Modify layout XML file res/layout/activity_main.xml add any GUI component if


required. Here we add only imageView and a textView.

4 Run the application and choose a running android device and install the application
on it and verify the results.

Following is the content of the modified main activity file src/[Link].

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends ActionBarActivity {

Button b1,b2;

ImageView iv;

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);

b1=(Button)findViewById([Link]);

iv=(ImageView)findViewById([Link]);

[Link](new [Link]() {

@Override

public void onClick(View v) {

Intent intent = new


Intent([Link].ACTION_IMAGE_CAPTURE);

startActivityForResult(intent, 0);

});

}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

// TODO Auto-generated method stub

[Link](requestCode, resultCode, data);

Bitmap bp = (Bitmap) [Link]().get("data");

[Link](bp);

@Override

protected void onDestroy() {

[Link]();

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link].menu_main, menu);

return true;

@Override

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 [Link].

int id = [Link]();

//noinspection SimplifiableIfStatement

if (id == [Link].action_settings) {

return true;

}
return [Link](item);

Following will be the content of res/layout/activity_main.xml file−

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView android:text="Camera Example" android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/textview"

android:textSize="35dp"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials point"

android:id="@+id/textView"

android:layout_below="@+id/textview"

android:layout_centerHorizontal="true"

android:textColor="#ff7aff24"

android:textSize="35dp" />

<ImageView

android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:id="@+id/imageView"

android:src="@drawable/abc"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="camera"

android:id="@+id/button"

android:layout_below="@+id/imageView"

android:layout_centerHorizontal="true"

android:layout_marginTop="86dp" />

</RelativeLayout>

Following will be the content of res/values/[Link] to define one new constants

<resources>

<string name="app_name">My Application</string>

<string name="hello_world">Hello world!</string>

<string name="action_settings">Settings</string>

</resources>

Following is the default content of [Link] −

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

<manifest xmlns:android="[Link]

package="[Link]"

android:versionCode="1"

android:versionName="1.0" >

<application

android:allowBackup="true"
android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name="[Link]"

android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>

</manifest>

Let's try to run your application. I assume you have connected your actual Android Mobile device
with your computer. To run the app from android studio, open one of your project's activity files and
click Run icon from the tool bar. Before starting your application, Android studio will display
following window to select an option where you want to run your Android application.
Select your mobile device as an option and then check your mobile device which will display
following screen −
Now just tap on the button on and the camera will be opened. Just capture a picture. After capturing
it , two buttons will appear asking you to discard it or keep it
Just press the tic button and you will be brought back to your application with the captured image in
place of android icon
Directly using Camera API provided by android in our
application
We will be using the camera API to integrate the camera in our application

First you will need to initialize the camera object using the static method provide by the api
called [Link]. Its syntax is

Camera object = null;

object = [Link]();

Apart from the above function , there are other functions provided by the Camera class that which
are listed below

[Link] Method & Description

1 getCameraInfo(int cameraId, [Link] cameraInfo)

It returns the information about a particular camera

2 getNumberOfCameras()

It returns an integer number defining of cameras available on device

3 lock()

It is used to lock the camera , so no other application can access it

4 release()

It is used to release the lock on camera , so other applications can access it

5 open(int cameraId)

It is used to open particular camera when multiple cameras are supported

6 enableShutterSound(boolean enabled)
It is used to enable/disable default shutter sound of image capture

Now you need make an separate class and extend it with SurfaceView and implements
SurfaceHolder interface.

The two classes that have been used have the following purpose

Class Description

Camera It is used to control the camera and take images or capture video from the
camera

SurfaceVie This class is used to present a live camera preview to the user.
w

You have to call the preview method of the camera class to start the preview of the camera to the
user

public class ShowCamera extends SurfaceView implements [Link] {

private Camera theCamera;

public void surfaceCreated(SurfaceHolder holder) {

[Link](holder);

[Link]();

public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3){

public void surfaceDestroyed(SurfaceHolder arg0) {

Apart from the preview there are other options of the camera that can be set using the other
functions provided by the Camera API
[Link] Method & Description

1 startFaceDetection()

This function starts the face detection in the camera

2 stopFaceDetection()

It is used to stop the face detection which is enabled by the above function

3 startSmoothZoom(int value)

It takes an integer value and zoom the camera very smoothly to that value

4 stopSmoothZoom()

It is used to stop the zoom of the camera

5 stopPreview()

It is used to stop the preview of the camera to the user

6 takePicture([Link] shutter, [Link] raw,


[Link] jpeg)

It is used to enable/disable default shutter sound of image capture

Example
Following example demonstrates the usage of the camera API in the application

To experiment with this example, you will need actual Mobile device equipped with latest Android
OS, because camera is not supported by the emulator

Step Description
s

1 You will use Android studio IDE to create an Android application and name it as
Camera under a package [Link];. 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/[Link] file to add the respective code of camera.

3 Modify layout XML file res/layout/activity_main.xml add any GUI component if


required. Here we add only FrameView and a button and a ImageView.

4 Modify [Link] as shown below to add the necessary permissions for


camera

5 Run the application and choose a running android device and install the application
on it and verify the results.

Following is the content of the modified main activity file src/[Link].

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends Activity implements [Link] {

Camera camera;

SurfaceView surfaceView;

SurfaceHolder surfaceHolder;

[Link] rawCallback;

[Link] shutterCallback;

[Link] jpegCallback;
@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);

surfaceView = (SurfaceView) findViewById([Link]);

surfaceHolder = [Link]();

[Link](this);

[Link](SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

jpegCallback = new PictureCallback() {

@Override

public void onPictureTaken(byte[] data, Camera camera) {

FileOutputStream outStream = null;

try {

outStream = new FileOutputStream([Link]("/sdcard/%[Link]",


[Link]()));

[Link](data);

[Link]();

catch (FileNotFoundException e) {

[Link]();

catch (IOException e) {

[Link]();

finally {
}

[Link](getApplicationContext(), "Picture Saved",


Toast.LENGTH_LONG).show();

refreshCamera();

};

public void captureImage(View v) throws IOException {

[Link](null, null, jpegCallback);

public void refreshCamera() {

if ([Link]() == null) {

return;

try {

[Link]();

catch (Exception e) {

try {

[Link](surfaceHolder);

[Link]();

catch (Exception e) {

}
@Override

protected void onDestroy() {

[Link]();

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link].menu_main, menu);

return true;

@Override

public boolean onOptionsItemSelected(MenuItem item) {

// Handle action bar item clicks here. The action bar

// automatically handle clicks on the Home/Up button, so long

// as you specify a parent activity in [Link].

int id = [Link]();

//noinspection SimplifiableIfStatement

if (id == [Link].action_settings) {

return true;

return [Link](item);

@Override

public void surfaceCreated(SurfaceHolder holder) {

try {

camera = [Link]();

}
catch (RuntimeException e) {

[Link](e);

return;

[Link] param;

param = [Link]();

[Link](352, 288);

[Link](param);

try {

[Link](surfaceHolder);

[Link]();

catch (Exception e) {

[Link](e);

return;

@Override

public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
{

refreshCamera();

@Override

public void surfaceDestroyed(SurfaceHolder holder) {

[Link]();

[Link]();

camera = null;

}
}

Modify the content of the res/layout/activity_main.xml

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView android:text="Camera Example" android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/textview"

android:textSize="35dp"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials point"

android:id="@+id/textView"

android:layout_below="@+id/textview"

android:layout_centerHorizontal="true"

android:textColor="#ff7aff24"

android:textSize="35dp" />

<SurfaceView

android:id="@+id/surfaceView"

android:layout_width="match_parent"

android:layout_height="0dp"
android:layout_weight="1"/>

</RelativeLayout>

Modify the content of the res/values/[Link]

<resources>

<string name="app_name">My Application</string>

<string name="hello_world">Hello world!</string>

<string name="action_settings">Settings</string>

</resources>

Modify the content of the [Link] and add the necessary permissions as shown
below.

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

<manifest xmlns:android="[Link]

package="[Link].camera1"

android:versionCode="1"

android:versionName="1.0" >

<uses-permission android:name="[Link]" />

<uses-permission android:name="[Link].WRITE_EXTERNAL_STORAGE" />

<uses-feature android:name="[Link]" />

<uses-feature android:name="[Link]" />

<application

android:allowBackup="true"

android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name="[Link]"

android:label="@string/app_name" >
<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>

</manifest>

Let's try to run your application. I assume you have connected your actual Android Mobile device
with your computer. To run the app from Android studio, open one of your project's activity files and
click Run icon from the toolbar. Before starting your application, Android studio will display
following window to select an option where you want to run your Android application.
Select your mobile device as an option and then check your mobile device which will display
following screen:

Android - Clipboard Tutorial


Android provides the clipboard framework for copying and pasting different types of data. The data
could be text, images, binary stream data or other complex data types.

Android provides the library of ClipboardManager and ClipData and [Link] to use the
copying and pasting [Link] order to use clipboard framework, you need to put data into clip
object, and then put that object into system wide clipboard.

In order to use clipboard , you need to instantiate an object of ClipboardManager by calling


the getSystemService() method. Its syntax is given below −

ClipboardManager myClipboard;

myClipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);

Copying data
The next thing you need to do is to instantiate the ClipData object by calling the respective type of
data method of the ClipData class. In case of text data , thenewPlainText method will be called.
After that you have to set that data as the clip of the Clipbaoard Manager [Link] syntax is given
below −

ClipData myClip;

String text = "hello world";

myClip = [Link]("text", text);

[Link](myClip);

The ClipData object can take these three form and following functions are used to create those
forms.

[Link] ClipData Form & Method

1 Text

newPlainText(label, text)
Returns a ClipData object whose single [Link] object contains a text string.

2 URI

newUri(resolver, label, URI)

Returns a ClipData object whose single [Link] object contains a URI.

3 Intent

newIntent(label, intent)

Returns a ClipData object whose single [Link] object contains an Intent.

Pasting data
In order to paste the data, we will first get the clip by calling the getPrimaryClip()method. And from
that click we will get the item in [Link] object. And from the object we will get the data. Its
syntax is given below −

ClipData abc = [Link]();

[Link] item = [Link](0);

String text = [Link]().toString();

Apart from the these methods , there are other methods provided by the ClipboardManager class
for managing clipboard framework. These methods are listed below −

[Link] Method & description

1 getPrimaryClip()

This method just returns the current primary clip on the clipboard

2 getPrimaryClipDescription()

This method returns a description of the current primary clip on the clipboard but not
a copy of its data.
3 hasPrimaryClip()

This method returns true if there is currently a primary clip on the clipboard

4 setPrimaryClip(ClipData clip)

This method sets the current primary clip on the clipboard

5 setText(CharSequence text)

This method can be directly used to copy text into the clipboard

6 getText()

This method can be directly used to get the copied text from the clipboard

Example
Here is an example demonstrating the use of ClipboardManager class. It creates a basic copy
paste application that allows you to copy the text and then paste it via clipboard.

To experiment with this example , you can run this on an actual device or in an emulator.

Step Description
s

1 You will use Android studio IDE to create an Android application and under a package
[Link]. 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/[Link] file to add necessary code.

3 Modify the res/layout/activity_main to add respective XML components

4 Run the application and choose a running android device and install the application
on it and verify the results
Following is the content of the modified main activity file src/[Link].

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends ActionBarActivity {


EditText ed1,ed2;

Button b1,b2;

private ClipboardManager myClipboard;

private ClipData myClip;.

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);

ed1=(EditText)findViewById([Link]);

ed2=(EditText)findViewById([Link].editText2);

b1=(Button)findViewById([Link]);

b2=(Button)findViewById([Link].button2);

myClipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);

[Link](new [Link]() {

@Override

public void onClick(View v) {

String text;

text = [Link]().toString();

myClip = [Link]("text", text);

[Link](myClip);

[Link](getApplicationContext(), "Text
Copied",Toast.LENGTH_SHORT).show();

});
[Link](new [Link]() {

@Override

public void onClick(View v) {

ClipData abc = [Link]();

[Link] item = [Link](0);

String text = [Link]().toString();

[Link](text);

[Link](getApplicationContext(), "Text
Pasted",Toast.LENGTH_SHORT).show();

});

@Override

protected void onDestroy() {

[Link]();

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link].menu_main, menu);

return true;

@Override

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 [Link].


int id = [Link]();

//noinspection SimplifiableIfStatement

if (id == [Link].action_settings) {

return true;

return [Link](item);

Following is the modified content of the xml res/layout/activity_main.xml.

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"

tools:context=".MainActivity">

<TextView android:text="Example" android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/textview"

android:textSize="35dp"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials point"

android:id="@+id/textView"

android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"

android:textColor="#ff7aff24"

android:textSize="35dp" />

<ImageView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/imageView"

android:src="@drawable/abc"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true" />

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/editText"

android:layout_alignParentRight="true"

android:layout_alignParentEnd="true"

android:hint="Copy text"

android:layout_below="@+id/imageView"

android:layout_alignLeft="@+id/imageView"

android:layout_alignStart="@+id/imageView" />

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/editText2"

android:layout_alignLeft="@+id/editText"

android:layout_alignStart="@+id/editText"

android:hint="paste text"

android:layout_below="@+id/editText"

android:layout_alignRight="@+id/editText"

android:layout_alignEnd="@+id/editText" />
<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Copy text"

android:id="@+id/button"

android:layout_below="@+id/editText2"

android:layout_alignLeft="@+id/editText2"

android:layout_alignStart="@+id/editText2" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Paste text"

android:id="@+id/button2"

android:layout_below="@+id/editText2"

android:layout_alignRight="@+id/editText2"

android:layout_alignEnd="@+id/editText2" />

</RelativeLayout>

Following is the content of the res/values/[Link].

<resources>

<string name="app_name">My Application</string>

<string name="hello_world">Hello world!</string>

<string name="action_settings">Settings</string>

</resources>

Following is the content of [Link] file.

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

<manifest xmlns:android="[Link]

package="[Link]"

android:versionCode="1"
android:versionName="1.0" >

<application

android:allowBackup="true"

android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name="[Link]"

android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>

</manifest>

Android - Custom Fonts Tutorial


In android, you can define your own custom fonts for the strings in your application. You just need
to download the required font from the internet, and then place it in assets/fonts folder.

After putting fonts in the assets folder under fonts folder, you can access it in your java code
through Typeface class. First , get the reference of the text view in the code. Its syntax is given
below −

TextView tx = (TextView)findViewById([Link].textview1);
The next thing you need to do is to call static method of Typeface classcreateFromAsset() to get
your custom font from assets. Its syntax is given below −

Typeface custom_font = [Link](getAssets(), "fonts/font [Link]");

The last thing you need to do is to set this custom font object to your TextView Typeface property.
You need to call setTypeface() method to do that. Its syntax is given below −

[Link](custom_font);

Apart from these Methods, there are other methods defined in the Typeface class , that you can
use to handle Fonts more effectively.

[Link] Method & description

1 create(String familyName, int style)

Create a Typeface object given a family name, and option style information

2 create(Typeface family, int style)

Create a Typeface object that best matches the specified existing Typeface and the
specified Style

3 createFromFile(String path)

Create a new Typeface from the specified font file

4 defaultFromStyle(int style)

Returns one of the default Typeface objects, based on the specified style

5 getStyle()

Returns the Typeface's intrinsic style attributes


Example
Here is an example demonstrating the use of Typeface to handle CustomFont. It creates a basic
application that displays a custom font that you specified in the fonts file.

To experiment with this example, you can run this on an actual device or in an emulator.

Step Description
s

1 You will use Android studio IDE to create an Android application under a package
[Link]. 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 Download a font from internet and put it under assets/fonts folder.

3 Modify src/[Link] file to add necessary code.

4 Modify the res/layout/activity_main to add respective XML components

5 Run the application and choose a running android device and install the application
on it and verify the results

Following is the content of the modified main activity file [Link].

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends ActionBarActivity {

TextView tv1,tv2;

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);

tv1=(TextView)findViewById([Link].textView3);

tv2=(TextView)findViewById([Link].textView4);

Typeface face= [Link](getAssets(), "font/[Link]");

[Link](face);

Typeface face1= [Link](getAssets(), "font/[Link]");

[Link](face1);

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link].menu_main, menu);

return true;

}
@Override

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 [Link].

int id = [Link]();

//noinspection SimplifiableIfStatement

if (id == [Link].action_settings) {

return true;

return [Link](item);

Following is the modified content of the xml activity_main.xml.

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Typeface"

android:id="@+id/textView"

android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"

android:textSize="30dp" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials Point"

android:id="@+id/textView2"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true"

android:textSize="35dp"

android:textColor="#ff16ff01" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials Point"

android:id="@+id/textView3"

android:layout_centerVertical="true"

android:textSize="45dp"

android:layout_alignParentRight="true"

android:layout_alignParentEnd="true"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials Point"

android:id="@+id/textView4"

android:layout_below="@+id/textView3"

android:layout_alignLeft="@+id/textView3"

android:layout_alignStart="@+id/textView3"
android:layout_marginTop="73dp"

android:textSize="45dp" />

</RelativeLayout>

Following is the content of the res/values/[Link].

<resources>

<string name="app_name">My Application</string>

<string name="hello_world">Hello world!</string>

<string name="action_settings">Settings</string>

</resources>

Following is the content of [Link] file.

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

<manifest xmlns:android="[Link]

package="[Link]" >

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name=".MainActivity"

android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>
</application>

</manifest>

Android - Data Backup Tutorial


Android allows you to backup your application data to remote "cloud" storage, in order to provide a
restore point for the application data and settings. You can only backup your application data. In
order to access the other applications data, you need to root your phone.

In order to make a data backup application, you need to register your application with google
backup service. This has been explained in the example. After registering , you have to specify its
key in the [Link]

<application

android:allowBackup="true"

android:backupAgent="MyBackupPlace">

<meta-data

android:name="[Link].api_key"

android:value="AEdPqrEAAAAIErlxFByGgNz2ywBeQb6TsmLpp5Ksh1PW-ZSexg" />

</application>

Android provides BackUpAgentHelper class to handle all the operations of data backup. In order
to use this class , you have to extend your class with it. Its syntax is given below:

public class MyBackUpPlace extends BackupAgentHelper {

The persistent data that you want to backup is in either of the two forms. Either it could be
SharedPrefrences or it could be File. Android supports both types of backup in the respective
classes of SharedPreferencesBackupHelper and FileBackupHelper.

In order to use SharedPerefernceBackupHelper, you need to instantiate its object with the name
of your sharedPerefernces File. Its syntax is given below −
static final String File_Name_Of_Prefrences = "myPrefrences";

SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this,


File_Name_Of_Prefrences);

The last thing you need to do is to call addHelper method by specifying the backup key string , and
the helper object. Its syntax is given below −

addHelper(PREFS_BACKUP_KEY, helper);

The addHelper method will automatically add a helper to a given data subset to the agent's
configuration.

Apart from these methods, there are other methods defined in the BackupAgentHelper class. They
are defined below −

[Link] Method & description

1 onBackup(ParcelFileDescriptor oldState, BackupDataOutput data,


ParcelFileDescriptor newState)

Run the backup process on each of the configured handlers

2 onRestore(BackupDataInput data, int appVersionCode, ParcelFileDescriptor


newState)

Run the restore process on each of the configured handlers

The methods of the SharedPreferencesBackUpHelper class are listed below.

[Link] Method & description

1 performBackup(ParcelFileDescriptor oldState, BackupDataOutput data,


ParcelFileDescriptor newState)

Backs up the configured SharedPreferences groups

2 restoreEntity(BackupDataInputStream data)
Restores one entity from the restore data stream to its proper shared preferences file
store

Example
The following example demonstrates the use of BackupAgentHelper class to create backup of your
application data.

To experiment with this example, you need to run this on an actual device or in an emulator.

Step Description
s

1 You will use Android studio to create an Android application and name it as Backup
under a package [Link]. 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 Register your application with Google backup service.

3 Modify the AndroidManifest to add respective necessary key and other components

4 Create backup agent class with the name you specify at [Link]

5 Run the application and verify the results

Register you android application with google backup service. In order to do that , visit this link.
You must agree to the terms of service, and then enter the application package name. It is shown
below −
Then click on Register with android backup service. It would give you your key, along with your
AndroidManifest code to copy. Just copy the key. It is shown below −

Once you copy the key , you need to write it in your [Link] file. Its code is given
below −

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

<manifest xmlns:android="[Link]

package="[Link]"

android:versionCode="1"

android:versionName="1.0" >

<uses-sdk

android:minSdkVersion="8"

android:targetSdkVersion="17" />

<application

android:allowBackup="true"

android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

android:backupAgent="MyBackUpPlace"

android:theme="@style/AppTheme" >

<activity
android:name="[Link]"

android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

<meta-data

android:name="[Link].api_key"

android:value="AEdPqrEAAAAIErlxFByGgNz2ywBeQb6TsmLpp5Ksh1PW-ZSexg" />

</application>

</manifest>

Here is the code of BackUpAgentHelper class. The name of the class should be the same as you
specified in the backupAgent tag under application in [Link]

package [Link];

import [Link];

import [Link];

public class MyBackUpPlace extends BackupAgentHelper {

static final String File_Name_Of_Prefrences = "myPrefrences";

static final String PREFS_BACKUP_KEY = "backup";

@Override

public void onCreate() {

SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this,

File_Name_Of_Prefrences);

addHelper(PREFS_BACKUP_KEY, helper);
}

Test your BackupAgent


Once you've implemented your backup agent, you can test the backup and restore functionality
with the following procedure, using bmgr.

Install your application on a suitable Android system image.


If using the emulator, create and use an AVD with Android 2.2 (API Level 8).

If using a device, the device must be running Android 2.2 or greater and have Google Play built in.

Ensure data backup is enabled


If using the emulator, you can enable backup with the following command from your SDK tools/
path −

adb shell bmgr enable true

If using a device, open the system Settings, select Privacy, then enable Back up my data and
Automatic restore.

Performing backup
For testing purposes, you can also make a request with the following bmgr command −

adb shell bmgr backup [Link]

Initiate a backup operation by typing the following command.

adb shell bmgr run

This forces the Backup Manager to perform all backup requests that are in its queue.

Uninstall and reinstall your application


Uninstall the application with the following command −

adb uninstall [Link]

Then reinstall the application and verify the results.


Android - Developer Tools Tutorial
The android developer tools let you create interactive and powerful application for android platform.
The tools can be generally categorized into two types.

 SDK tools
 Platform tools

SDK tools
SDK tools are generally platform independent and are required no matter which android platform
you are working on. When you install the Android SDK into your system, these tools get
automatically installed. The list of SDK tools has been given below −

[Link] Tool & description

1 android

This tool lets you manage AVDs, projects, and the installed components of the SDK

2 ddms

This tool lets you debug Android applications

3 Draw 9-Patch

This tool allows you to easily create a NinePatch graphic using a WYSIWYG editor

4 emulator

This tools let you test your applications without using a physical device

5 mksdcard

Helps you create a disk image (external sdcard storage) that you can use with the
emulator

6 proguard
Shrinks, optimizes, and obfuscates your code by removing unused code

7 sqlite3

Lets you access the SQLite data files created and used by Android applications

8 traceview

Provides a graphical viewer for execution logs saved by your application

9 Adb

Android Debug Bridge (adb) is a versatile command line tool that lets you
communicate with an emulator instance or connected Android-powered device.

We will discuss three important tools here that are android,ddms and sqlite3.

Android
Android is a development tool that lets you perform these tasks:

 Manage Android Virtual Devices (AVD)


 Create and update Android projects
 Update your sdk with new platform add-ons and documentation

android [global options] action [action options]

DDMS
DDMS stands for Dalvik debug monitor server, that provides many services on the device. The
service could include message formation, call spoofing, capturing screenshot, exploring internal
threads and file systems e.t.c

Running DDMS
From Android studio click on Tools>Android>Android device Monitor.

How it works
In android, each application runs in its own process and each process run in the virtual machine.
Each VM exposes a unique port, that a debugger can attach to.
When DDMS starts, it connects to adb. When a device is connected, a VM monitoring service is
created between adb and DDMS, which notifies DDMS when a VM on the device is started or
terminated.

Making SMS
Making sms to [Link] need to call telnet client and server as shown below

Now click on send button, and you will see an sms notification in the emulator window. It is shown
below
Making Call
In the DDMS, select the Emulator Control tab. In the emulator control tab , click on voice and then
start typing the incoming number. It is shown in the picture below −
Now click on the call button to make a call to your emulator. It is shown below −
Now click on hangup in the Android studio window to terminate the call.

The fake sms and call can be viewed from the notification by just dragging the notification window
to the center using mouse. It is shown below −
Capturing ScreenShot
You can also capture screenshot of your emulator. For this look for the camera icon on the right
side under Devices tab. Just point your mouse over it and select it.
As soon as you select it , it will start the screen capturing process and will capture whatever screen
of the emulator currently active. It is shown below −

The eclipse orientation can be changed using Ctrl + F11 key. Now you can save the image or rotate
it and then select done to exit the screen capture dialog.

Sqlite3
Sqlite3 is a command line program which is used to manage the SQLite databases created by
Android applications. The tool also allow us to execute the SQL statements on the fly.

There are two way through which you can use SQlite , either from remote shell or you can use
locally.

Use Sqlite3 from a remote shell.


Enter a remote shell by entering the following command −

adb [-d|-e|-s {<serialNumber>}] shell

From a remote shell, start the sqlite3 tool by entering the following command:

sqlite3
Once you invoke sqlite3, you can issue sqlite3 commands in the shell. To exit and return to the adb
remote shell, enter exit or press CTRL+D.

Using Sqlite3 directly


Copy a database file from your device to your host machine.

adb pull <database-file-on-device>

Start the sqlite3 tool from the /tools directory, specifying the database file −

sqlite3 <database-file-on-host>

Platform tools
The platform tools are customized to support the features of the latest android platform.

The platform tools are typically updated every time you install a new SDK platform. Each update of
the platform tools is backward compatible with older platforms.

Some of the platform tools are listd below −

 Android Debug bridge (ADB)


 Android Interface definition language (AIDL)
 aapt, dexdump , and dex e.t.c

Android - Emulator Tutorial


The Android SDK includes a virtual mobile device emulator that runs on your computer. The
emulator lets you prototype, develop and test Android applications without using a physical device.

In this chapter we are going to explore different functionalities in the emulator that are present in the
real android device.

Creating AVD
If you want to emulate a real device, first crate an AVD with the same device configurations as real
device, then launch this AVD from AVD manager.
Creating Snapshots in Eclipse
Creating snapshots mean saving an emulator state to a file that enables the emulator to be started
quickly the next time you try to launch it. The one of the biggest advantage of creating snapshots is
that it saves the boot up time.

In order to create snapshot, check mark the option of snapshot while creating your AVD. It is shown
below −

The first time you launch the emulator , it will take the usual time of loading. But when you close it
and start it again, you will see a considerable amount of time reduction in appearing of emulator.

Changing Orientation
Usually by default when you launch the emulator, its orientation is vertical, but you can change it
orientation by pressing Ctrl+F11 key from keyboard.

First launch the emulator. It is shown in the picture below −


Once it is launched, press Ctrl+F11 key to change its orientation. It is shown below:
Emulator Commands.
Apart from just orientation commands, there are other very useful commands of emulator that you
should keep in mind while using emulator. They are listed below −

[Link] Command & description

1 Home

Shifts to main screen

2 F2

Toggles context sensitive menu

3 F3

Bring out call log

4 F4
End call

5 F5

Search

6 F6

Toggle trackball mode

7 F7

Power button

8 F8

Toggle data network

9 Ctrl+F5

Ring Volume up

10 Ctrl+F6

Ring Volume down

Emulator - Sending SMS


You can emulate sending SMS to your emulator. There are two ways to do that. You can do that
from DDMS which can be found in Android studio, or from Telnet.(Network utility found in windows).
Sending SMS through Telnet.

Telnet is not enabled by default in windows. You have to enable it to use it. Once enabled you can
go to command prompt and start telnet by typing telnet.

In order to send SMS , note down the AVD number which can be found on the title bar of the
emulator. It could be like this 5554 e.t.c. Once noted , type this command in command prompt.

telnet localhost 5554

Press enter when you type the command. It is shown below in the figure.

You will see that you are now connected to your emulator. Now type this command to send
message.

sms send 1234 "hello"


Once you type this command , hit enter. Now look at the AVD. You will receive a notification
displaying that you got a new text message. It is shown below −
Emulator - Making Call
You can easily make phone calls to your emulator using telent client. You need to connect to your
emulator from telnet. It is discussed in the sending sms topic above.

After that you will type this command in the telent window to make a call. Its syntax is given below −

gsm call 1234

Once you type this command , hit enter. Now look at the AVD. You will receive a call from the
number your put in the command. It is shown below −
Emulator - Transferring files
You can easily transfer files into the emulator and vice versa. In order to do that, you need to select
the DDMS utility in Android studio. After that select the file explorer tab. It is shown below −

Browse through the explorer and make new folder , view existing contents e.t.c.

Android - Gestures Tutorial


Android provides special types of touch screen events such as pinch , double tap, scrolls , long
presses and flinch. These are all known as gestures.

Android provides GestureDetector class to receive motion events and tell us that these events
correspond to gestures or not. To use it , you need to create an object of GestureDetector and then
extend another class [Link] to act as a listener and
override some methods. Its syntax is given below −

GestureDetector myG;

myG = new GestureDetector(this,new Gesture());

class Gesture extends [Link]{


public boolean onSingleTapUp(MotionEvent ev) {

public void onLongPress(MotionEvent ev) {

public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,

float distanceY) {

public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,

float velocityY) {

Handling Pinch Gesture


Android provides ScaleGestureDetector class to handle gestures like pinch e.t.c. In order to use it,
you need to instantiate an object of this class. Its syntax is as follow −

ScaleGestureDetector SGD;

SGD = new ScaleGestureDetector(this,new ScaleListener());

The first parameter is the context and the second parameter is the event listener. We have to define
the event listener and override a function OnTouchEvent to make it working. Its syntax is given
below −

public boolean onTouchEvent(MotionEvent ev) {

[Link](ev);

return true;

private class ScaleListener extends [Link]


{

@Override
public boolean onScale(ScaleGestureDetector detector) {

float scale = [Link]();

return true;

Apart from the pinch gestures , there are other methods available that notify more about touch
events. They are listed below −

[Link] Method & description

1 getEventTime()

This method get the event time of the current event being processed..

2 getFocusX()

This method get the X coordinate of the current gesture's focal point.

3 getFocusY()

This method get the Y coordinate of the current gesture's focal point.

4 getTimeDelta()

This method return the time difference in milliseconds between the previous
accepted scaling event and the current scaling event.

5 isInProgress()

This method returns true if a scale gesture is in progress..

6 onTouchEvent(MotionEvent event)

This method accepts MotionEvents and dispatches events when appropriate.


Example
Here is an example demonstrating the use of ScaleGestureDetector class. It creates a basic
application that allows you to zoom in and out through pinch.

To experiment with this example , you can run this on an actual device or in an emulator with touch
screen enabled.

Step Description
s

1 You will use Android studio to create an Android application under a package
[Link];. 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/[Link] file to add necessary code.

3 Modify the res/layout/activity_main to add respective XML components

4 Run the application and choose a running android device and install the application
on it and verify the results

Following is the content of the modified main activity file src/[Link].

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends Activity {

private ImageView iv;

private Matrix matrix = new Matrix();

private float scale = 1f;

private ScaleGestureDetector SGD;

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);

iv=(ImageView)findViewById([Link]);

SGD = new ScaleGestureDetector(this,new ScaleListener());

public boolean onTouchEvent(MotionEvent ev) {


[Link](ev);

return true;

private class ScaleListener extends ScaleGestureDetector.

SimpleOnScaleGestureListener {

@Override

public boolean onScale(ScaleGestureDetector detector) {

scale *= [Link]();

scale = [Link](0.1f, [Link](scale, 5.0f));

[Link](scale, scale);

[Link](matrix);

return true;

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link].menu_main, menu);

return true;

@Override

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 [Link].

int id = [Link]();
//noinspection SimplifiableIfStatement

if (id == [Link].action_settings) {

return true;

return [Link](item);

Following is the modified content of the xml res/layout/activity_main.xml.

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView android:text="Gestures Example" android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/textview"

android:textSize="35dp"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials point"

android:id="@+id/textView"

android:layout_below="@+id/textview"

android:layout_centerHorizontal="true"

android:textColor="#ff7aff24"
android:textSize="35dp" />

<ImageView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/imageView"

android:src="@drawable/abc"

android:scaleType="matrix"

android:layout_below="@+id/textView"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:layout_alignParentBottom="true"

android:layout_alignParentRight="true"

android:layout_alignParentEnd="true" />

</RelativeLayout>

Following is the content of the res/values/[Link].

<resources>

<string name="app_name>My Application</string>

<string name="hello_world">Hello world!</string>

<string name="action_settings">Settings</string>

</resources>

Following is the content of [Link] file.

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

<manifest xmlns:android="[Link]

package="[Link]"

android:versionCode="1"

android:versionName="1.0" >

<application

android:allowBackup="true"
android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name="[Link]"

android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>

</manifest>

Android - Image Effects Tutorial


Android allows you to manipulate images by adding different kinds of effects on the images. You
can easily apply image processing techniques to add certain kinds of effects on images. The effects
could be brightness,darkness, grayscale conversion e.t.c.

Android provides Bitmap class to handle images. This can be found under [Link].
There are many ways through which you can instantiate bitmap. We are creating a bitmap of image
from the imageView.

private Bitmap bmp;

private ImageView img;

img = (ImageView)findViewById([Link].imageView1);

BitmapDrawable abmp = (BitmapDrawable)[Link]();


Now we will create bitmap by calling getBitmap() function of BitmapDrawable class. Its syntax is
given below −

bmp = [Link]();

An image is nothing but a two dimensional matrix. Same way you will handle a bitmap. An image
consist of pixels. So you will get pixels from this bitmap and apply processing to it. Its syntax is as
follows −

for(int i=0; i<[Link](); i++){

for(int j=0; j<[Link](); j++){

int p = [Link](i, j);

The getWidth() and getHeight() functions returns the height and width of the matrix. The getPixel()
method returns the pixel at the specified index. Once you got the pixel, you can easily manipulate it
according to your needs.

Apart from these methods, there are other methods that helps us manipulate images more better.

[Link] Method & description

1 copy([Link] config, boolean isMutable)

This method copy this bitmap's pixels into the new bitmap

2 createBitmap(DisplayMetrics display, int width, int height, [Link] config)

Returns a mutable bitmap with the specified width and height

3 createBitmap(int width, int height, [Link] config)

Returns a mutable bitmap with the specified width and height

4 createBitmap(Bitmap src)
Returns an immutable bitmap from the source bitmap

5 extractAlpha()

Returns a new bitmap that captures the alpha values of the original

6 getConfig()

This mehtod eturn that config, otherwise return null

7 getDensity()

Returns the density for this bitmap

8 getRowBytes()

Return the number of bytes between rows in the bitmap's pixels

9 setPixel(int x, int y, int color)

Write the specified Color into the bitmap (assuming it is mutable) at the x,y
coordinate

10 setDensity(int density)

This method specifies the density for this bitmap

Example
The below example demonstrates some of the image effects on the bitmap. It crates a basic
application that allows you to convert the picture into grayscale and much more.

To experiment with this example , you need to run this on an actual device.

Step Description
s

1 You will use Android studio to create an Android application under a package
[Link]. 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/[Link] file to add necessary code.

3 Modify the res/layout/activity_main to add respective XML components

4 Run the application and choose a running android device and install the application
on it and verify the results

Following is the content of the modified [Link].

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends ActionBarActivity {

Button b1, b2, b3;

ImageView im;

private Bitmap bmp;

private Bitmap operation;

@Override

protected void onCreate(Bundle savedInstanceState) {


[Link](savedInstanceState);

setContentView([Link].activity_main);

b1 = (Button) findViewById([Link]);

b2 = (Button) findViewById([Link].button2);

b3 = (Button) findViewById([Link].button3);

im = (ImageView) findViewById([Link]);

BitmapDrawable abmp = (BitmapDrawable) [Link]();

bmp = [Link]();

public void gray(View view) {

operation = [Link]([Link](),[Link](),
[Link]());

double red = 0.33;

double green = 0.59;

double blue = 0.11;

for (int i = 0; i < [Link](); i++) {

for (int j = 0; j < [Link](); j++) {

int p = [Link](i, j);

int r = [Link](p);

int g = [Link](p);

int b = [Link](p);

r = (int) red * r;

g = (int) green * g;

b = (int) blue * b;

[Link](i, j, [Link]([Link](p), r, g, b));

[Link](operation);
}

public void bright(View view){

operation= [Link]([Link](), [Link](),[Link]());

for(int i=0; i<[Link](); i++){

for(int j=0; j<[Link](); j++){

int p = [Link](i, j);

int r = [Link](p);

int g = [Link](p);

int b = [Link](p);

int alpha = [Link](p);

r = 100 + r;

g = 100 + g;

b = 100 + b;

alpha = 100 + alpha;

[Link](i, j, [Link](alpha, r, g, b));

[Link](operation);

public void dark(View view){

operation= [Link]([Link](),[Link](),[Link]());

for(int i=0; i<[Link](); i++){

for(int j=0; j<[Link](); j++){

int p = [Link](i, j);

int r = [Link](p);

int g = [Link](p);

int b = [Link](p);

int alpha = [Link](p);


r = r - 50;

g = g - 50;

b = b - 50;

alpha = alpha -50;

[Link](i, j, [Link]([Link](p), r, g, b));

[Link](operation);

public void gama(View view) {

operation = [Link]([Link](),[Link](),[Link]());

for(int i=0; i<[Link](); i++){

for(int j=0; j<[Link](); j++){

int p = [Link](i, j);

int r = [Link](p);

int g = [Link](p);

int b = [Link](p);

int alpha = [Link](p);

r = r + 150;

g = 0;

b = 0;

alpha = 0;

[Link](i, j, [Link]([Link](p), r, g, b));

[Link](operation);

public void green(View view){


operation = [Link]([Link](),[Link](),
[Link]());

for(int i=0; <[Link](); i++){

for(int j=0; j<[Link](); j++){

int p = [Link](i, j);

int r = [Link](p);

int g = [Link](p);

int b = [Link](p);

int alpha = [Link](p);

r = 0;

g = g+150;

b = 0;

alpha = 0;

[Link](i, j, [Link]([Link](p), r, g, b));

[Link](operation);

public void blue(View view){

operation = [Link]([Link](),[Link](),
[Link]());

for(int i=0; i<[Link](); i++){

for(int j=0; j<[Link](); j++){

int p = [Link](i, j);

int r = [Link](p);

int g = [Link](p);

int b = [Link](p);

int alpha = [Link](p);


r = 0;

g = 0;

b = b+150;

alpha = 0;

[Link](i, j, [Link]([Link](p), r, g, b));

[Link](operation);

Following is the modified content of the xml res/layout/activity_main.xml.

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/textView"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true"

android:textSize="30dp"

android:text="Image Effects" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"
android:text="Tutorials Point"

android:id="@+id/textView2"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true"

android:textSize="35dp"

android:textColor="#ff16ff01" />

<ImageView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/imageView"

android:layout_below="@+id/textView2"

android:layout_centerHorizontal="true"

android:src="@drawable/logo"/>

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Gray"

android:onClick="gray"

android:id="@+id/button"

android:layout_alignParentBottom="true"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:layout_marginBottom="97dp" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="dark"

android:onClick="dark"

android:id="@+id/button2"

android:layout_alignBottom="@+id/button"
android:layout_alignParentRight="true"

android:layout_alignParentEnd="true" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Bright"

android:onClick="bright"

android:id="@+id/button3"

android:layout_alignTop="@+id/button2"

android:layout_centerHorizontal="true" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Red"

android:onClick="gama"

android:id="@+id/button4"

android:layout_below="@+id/button3"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Green"

android:onClick="green"

android:id="@+id/button5"

android:layout_alignTop="@+id/button4"

android:layout_alignLeft="@+id/button3"

android:layout_alignStart="@+id/button3" />

<Button
android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="blue"

android:onClick="blue"

android:id="@+id/button6"

android:layout_below="@+id/button2"

android:layout_toRightOf="@+id/textView"

android:layout_toEndOf="@+id/textView" />

</RelativeLayout>

Following is the content of [Link] file.

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

<manifest xmlns:android="[Link]

package="[Link]" >

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name=".MainActivity"

android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>
</manifest>

Android - Image Switcher Tutorial


Sometimes you don't want an image to appear abruptly on the screen, rather you want to apply
some kind of animation to the image when it transitions from one image to another. This is
supported by android in the form of ImageSwitcher.

An image switcher allows you to add some transitions on the images through the way they appear
on screen. In order to use image Switcher, you need to define its XML component first. Its syntax is
given below −

<ImageSwitcher

android:id="@+id/imageSwitcher1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerHorizontal="true"

android:layout_centerVertical="true" >

</ImageSwitcher>

Now we create an intance of ImageSwithcer in java file and get a reference of this XML component.
Its syntax is given below −

private ImageSwitcher imageSwitcher;


imageSwitcher = (ImageSwitcher)findViewById([Link].imageSwitcher1);

The next thing we need to do implement the ViewFactory interface and implement unimplemented
method that returns an imageView. Its syntax is below −

[Link]([Link].ic_launcher);

[Link](new ViewFactory() {

public View makeView() {

ImageView myView = new ImageView(getApplicationContext());

return myView;

}
The last thing you need to do is to add Animation to the ImageSwitcher. You need to define an
object of Animation class through AnimationUtilities class by calling a static method loadAnimation.
Its syntax is given below −

Animation in = [Link](this,[Link].slide_in_left);

[Link](in);

[Link](out);

The method setInAnimaton sets the animation of the appearance of the object on the screen
whereas setOutAnimation does the opposite. The method loadAnimation() creates an animation
object.

Apart from these methods, there are other methods defined in the ImageSwitcher class. They are
defined below −

[Link] Method & description

1 setImageDrawable(Drawable drawable)

Sets an image with image switcher. The image is passed in the form of bitmap

2 setImageResource(int resid)

Sets an image with image switcher. The image is passed in the form of integer id

3 setImageURI(Uri uri)

Sets an image with image switcher. THe image is passed in the form of URI

4 ImageSwitcher(Context context, AttributeSet attrs)

Returns an image switcher object with already setting some attributes passed in the
method

5 onInitializeAccessibilityEvent (AccessibilityEvent event)

Initializes an AccessibilityEvent with information about this View which is the event
source

6 onInitializeAccessibilityNodeInfo (AccessibilityNodeInfo info)

Initializes an AccessibilityNodeInfo with information about this view

Example
The below example demonstrates some of the image switcher effects on the bitmap. It crates a
basic application that allows you to view the animation effects on the images.

To experiment with this example , you need to run this on an actual device.

Step Description
s

1 You will use Android studio IDE to create an Android application under a package
[Link]. 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/[Link] file to add necessary code.

3 Modify the res/layout/activity_main to add respective XML components

4 Run the application and choose a running android device and install the application
on it and verify the results

Following is the content of the modified main activity file src/[Link].

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends Activity {

private ImageSwitcher sw;

private Button b1,b2;

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);

b1 = (Button) findViewById([Link]);

b2 = (Button) findViewById([Link].button2);

sw = (ImageSwitcher) findViewById([Link]);

[Link](new ViewFactory() {

@Override

public View makeView() {

ImageView myView = new ImageView(getApplicationContext());

[Link]([Link].FIT_CENTER);

[Link](new
[Link](LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));

return myView;

}
});

[Link](new [Link]() {

@Override

public void onClick(View v) {

[Link](getApplicationContext(), "previous
Image",Toast.LENGTH_LONG).show();

[Link]([Link]);

});

[Link](new [Link]() {

@Override

public void onClick(View v) {

[Link](getApplicationContext(), "Next
Image",Toast.LENGTH_LONG).show();

[Link]([Link]);

});

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link].menu_main, menu);

return true;

@Override

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 [Link].


int id = [Link]();

//noinspection SimplifiableIfStatement

if (id == [Link].action_settings) {

return true;

return [Link](item);

Following is the modified content of the xml res/layout/activity_main.xml.

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView android:text="Gestures Example" android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/textview"

android:textSize="35dp"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials point"

android:id="@+id/textView"
android:layout_below="@+id/textview"

android:layout_centerHorizontal="true"

android:textColor="#ff7aff24"

android:textSize="35dp" />

<ImageSwitcher

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/imageSwitcher"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true"

android:layout_marginTop="168dp" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="<"

android:id="@+id/button"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text=">"

android:id="@+id/button2"

android:layout_alignParentBottom="true"

android:layout_alignLeft="@+id/button"

android:layout_alignStart="@+id/button" />

</RelativeLayout>

Following is the content of [Link] file.


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

<manifest xmlns:android="[Link]

package="[Link]"

android:versionCode="1"

android:versionName="1.0" >

<application

android:allowBackup="true"

android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name="[Link]"

android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>

</manifest>

Android - Internal Storage Tutorial


Android provides many kinds of storage for applications to store their data. These storage places
are shared preferences, internal and external storage, SQLite storage, and storage via network
connection.
In this chapter we are going to look at the internal storage. Internal storage is the storage of the
private data on the device memory.

By default these files are private and are accessed by only your application and get deleted , when
user delete your application.

Writing file
In order to use internal storage to write some data in the file, call the openFileOutput() method with
the name of the file and the mode. The mode could be private , public e.t.c. Its syntax is given
below −

FileOutputStream fOut = openFileOutput("file name here",MODE_WORLD_READABLE);

The method openFileOutput() returns an instance of FileOutputStream. So you receive it in the


object of FileInputStream. After that you can call write method to write data on the file. Its syntax is
given below −

String str = "data";

[Link]([Link]());

[Link]();

Reading file
In order to read from the file you just created , call the openFileInput() method with the name of the
file. It returns an instance of FileInputStream. Its syntax is given below −

FileInputStream fin = openFileInput(file);

After that, you can call read method to read one character at a time from the file and then you can
print it. Its syntax is given below −

int c;

String temp="";

while( (c = [Link]()) != -1){

temp = temp + [Link]((char)c);

//string temp contains all the data of the file.


[Link]();

Apart from the the methods of write and close, there are other methods provided by
theFileOutputStream class for better writing files. These methods are listed below −

[Link] Method & description

1 FileOutputStream(File file, boolean append)

This method constructs a new FileOutputStream that writes to file.

2 getChannel()

This method returns a write-only FileChannel that shares its position with this stream

3 getFD()

This method returns the underlying file descriptor

4 write(byte[] buffer, int byteOffset, int byteCount)

This method Writes count bytes from the byte array buffer starting at position offset
to this stream

Apart from the the methods of read and close, there are other methods provided by
theFileInputStream class for better reading files. These methods are listed below −

[Link] Method & description

1 available()

This method returns an estimated number of bytes that can be read or skipped
without blocking for more input

2 getChannel()

This method returns a read-only FileChannel that shares its position with this stream
3 getFD()

This method returns the underlying file descriptor

4 read(byte[] buffer, int byteOffset, int byteCount)

This method reads at most length bytes from this stream and stores them in the byte
array b starting at offset

Example
Here is an example demonstrating the use of internal storage to store and read files. It creates a
basic storage application that allows you to read and write from internal storage.

To experiment with this example, you can run this on an actual device or in an emulator.

Step Description
s

1 You will use Android Studio IDE to create an Android application under a package
[Link]. 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/[Link] file to add necessary code.

3 Modify the res/layout/activity_main to add respective XML components

4 Run the application and choose a running android device and install the application
on it and verify the results

Following is the content of the modified main activity file src/[Link].

package [Link];

import [Link];

import [Link];
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends Activity {

Button b1,b2;

TextView tv;

EditText ed1;

String data;

private String file = "mydata";

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);

b1=(Button)findViewById([Link]);

b2=(Button)findViewById([Link].button2);

ed1=(EditText)findViewById([Link]);

tv=(TextView)findViewById([Link].textView2);

[Link](new [Link]() {

@Override

public void onClick(View v) {

data=[Link]().toString();
try {

FileOutputStream fOut = openFileOutput(file,MODE_WORLD_READABLE);

[Link]([Link]());

[Link]();

[Link](getBaseContext(),"file
saved",Toast.LENGTH_SHORT).show();

catch (Exception e) {

// TODO Auto-generated catch block

[Link]();

});

[Link](new [Link]() {

@Override

public void onClick(View v) {

try{

FileInputStream fin = openFileInput(file);

int c;

String temp="";

while( (c = [Link]()) != -1){

temp = temp + [Link]((char)c);

[Link](temp);

[Link](getBaseContext(),"file read",Toast.LENGTH_SHORT).show();

catch(Exception e){

});
}

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link].menu_main, menu);

return true;

@Override

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 [Link].

int id = [Link]();

//noinspection SimplifiableIfStatement

if (id == [Link].action_settings) {

return true;

return [Link](item);

Following is the modified content of the xml res/layout/activity_main.xml.

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView android:text="Internal storage" android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/textview"

android:textSize="35dp"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials point"

android:id="@+id/textView"

android:layout_below="@+id/textview"

android:layout_centerHorizontal="true"

android:textColor="#ff7aff24"

android:textSize="35dp" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Save"

android:id="@+id/button"

android:layout_alignParentBottom="true"

android:layout_alignLeft="@+id/textView"

android:layout_alignStart="@+id/textView" />

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/editText"
android:hint="Enter Text"

android:focusable="true"

android:textColorHighlight="#ff7eff15"

android:textColorHint="#ffff25e6"

android:layout_below="@+id/imageView"

android:layout_alignRight="@+id/textView"

android:layout_alignEnd="@+id/textView"

android:layout_marginTop="42dp"

android:layout_alignLeft="@+id/imageView"

android:layout_alignStart="@+id/imageView" />

<ImageView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/imageView"

android:src="@drawable/abc"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="load"

android:id="@+id/button2"

android:layout_alignTop="@+id/button"

android:layout_alignRight="@+id/editText"

android:layout_alignEnd="@+id/editText" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Read"

android:id="@+id/textView2"
android:layout_below="@+id/editText"

android:layout_toLeftOf="@+id/button2"

android:layout_toStartOf="@+id/button2"

android:textColor="#ff5bff1f"

android:textSize="25dp" />

</RelativeLayout>

Following is the content of the res/values/[Link].

<resources>

<string name="app_name">My Application</string>

<string name="hello_world">Hello world!</string>

<string name="action_settings">Settings</string>

</resources>

Following is the content of [Link] file.

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

<manifest xmlns:android="[Link]

package="[Link]" >

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name=".MainActivity"

android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>
</activity>

</application>

</manifest>

Let's try to run our Storage application we just modified. I assume you had created your AVD while
doing environment setup. To run the app from Android studio, open one of your project's activity
files and click Run icon from the tool bar. Android studio installs the app on your AVD and starts
it and if everything is fine with your set-up and application, it will display following Emulator window

Now what you need to do is to enter any text in the field. For example , i have entered some text.
Press the save button. The following notification would appear in you AVD −
Now when you press the load button, the application will read the file , and display the data. In case
of our, following data would be returned −
Note you can actually view this file by switching to DDMS tab. In DDMS , select file explorer and
navigate this path.

tools>android>android device Monitor

This has also been shown in the image below.


Android - JetPlayer Tutorial
The Android platform includes a JET engine that lets you add interactive playback of JET audio
content in your applications. Android provides JetPlayer class to handle this stuff.

In order to Jet Content , you need to use the JetCreator tool that comes with AndroidSDK. The
usage of jetCreator has been discussed in the example. In order to play the content created by
JetCreator, you need JetPlayer class supported by android.

In order to use JetPlayer , you need to instantiate an object of JetPlayer class. Its syntax is given
below −

JetPlayer jetPlayer = [Link]();


The next thing you need to do is to call loadJetFile method and pass in the path of your Jet file.
After that you have to add this into the Queue of JetPlayer. Its syntax is given below −

[Link]("/sdcard/[Link]");

byte segmentId = 0;

// queue segment 5, repeat once, use General MIDI, transpose by -1 octave

[Link](5, -1, 1, -1, 0, segmentId++);

The method queueJetSegment Queues the specified segment in the JET Queue. The last thing you
need to is to call the play method to start playing the music. Its syntax is given below −

[Link]();

Apart from these methods, there are other methods defined in the JetPlayer class. They are defined
below −

[Link] Method & description

1 clearQueue()

Empties the segment queue, and clears all clips that are scheduled for playback

2 closeJetFile()

Closes the resource containing the JET content

3 getJetPlayer()

Factory method for the JetPlayer class

4 loadJetFile(String path)

Loads a .jet file from a given path

5 pause()
Pauses the playback of the JET segment queue

6 release()

Stops the current JET playback, and releases all associated native resources

Example
The following example demonstrates the use of JetCreator tool to create Jet content. Once that
content is created, you can play it through JetPlayer.

To experiment with this example , you need to run this on an actual device or in an emulator.

Step Description
s

1 You will use Android studio IDE to create an Android application and name it as
JetPlayer under a package [Link]. 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 Install Python and WxPython on your computer from internet.

3 Run the jet creator from command prompt

4 Create Jet content and then save it

5 Run the application and verify the results

Using JetCreator
Installing python
The first step that you need while using JetCreator is to install the python. The python can be
installed from its official website here or from any where else on the internet.
Please keep in mind the version number of the python should either be 2.6 or 2.7 because this
example follows that.

Once you download python install it. After installing you have to set path to the python. Open your
command prompt and type the following [Link] is shown in the image below:

Once path is set , you can verify it by typing python and hit enter. It is shown below:

Installing WxPython
The next thing you need to do is to install the wxPython. It can be downloaded here. Once
downloaded , you will install it. It will be automatically installed in the python directory.

Ruuning JetCreator
The next thing you need to is to move to the path where JetCreator is present. It is in the tools,SDK
folder of the android. It is shown below −

Once in the folder type this command and hit enter.

python [Link]

It is shown in the figure below:


As soon as you hit enter, Jet Creator window will open. It would be something like this.

Creating JetContent
In the above Jet Window, click on the import button. And select JetCreator_demo_1 or 2 from the
JetFolder from the demo content folder in the Jet folder. It is shown in the image below:
Once you import the content , you will see the content in the JetCreator window. It is shown below:

Now you can explore different options of JetCreator by visiting the JetCreator linkhere. Finally in
order to create .jet file , you need to save the content from the file menu.

Verifying Results
Once you got the jet file, you can play it using jet player. The main code of playing it has been given
below −
JetPlayer jetPlayer = [Link]();

[Link]("/sdcard/[Link]");

byte segmentId = 0;

// queue segment 5, repeat once, use General MIDI, transpose by -1 octave

[Link](5, -1, 1, -1, 0, segmentId++);

[Link]();

Android - JSON Parser Tutorial


JSON stands for JavaScript Object [Link] is an independent data exchange format and is the
best alternative for XML. This chapter explains how to parse the JSON file and extract necessary
information from it.

Android provides four different classes to manipulate JSON data. These classes
areJSONArray,JSONObject,JSONStringer and JSONTokenizer.

The first step is to identify the fields in the JSON data in which you are interested in. For example.
In the JSON given below we interested in getting temperature only.

"sys":

"country":"GB",

"sunrise":1381107633,

"sunset":1381149604

},

"weather":[

"id":711,

"main":"Smoke",

"description":"smoke",

"icon":"50n"

}
],

"main":

"temp":304.15,

"pressure":1009,

JSON - Elements
An JSON file consist of many components. Here is the table defining the components of an JSON
file and their description −

[Link] Component & description

1 Array([)

In a JSON file , square bracket ([) represents a JSON array

2 Objects({)

In a JSON file, curly bracket ({) represents a JSON object

3 Key

A JSON object contains a key that is just a string. Pairs of key/value make up a
JSON object

4 Value

Each key has a value that could be string , integer or double e.t.c

JSON - Parsing
For parsing a JSON object, we will create an object of class JSONObject and specify a string
containing JSON data to it. Its syntax is:

String in;
JSONObject reader = new JSONObject(in);

The last step is to parse the JSON. An JSON file consist of different object with different key/value
pair e.t.c. So JSONObject has a separate function for parsing each of the component of JSON file.
Its syntax is given below:

JSONObject sys = [Link]("sys");

country = [Link]("country");

JSONObject main = [Link]("main");

temperature = [Link]("temp");

The method getJSONObject returns the JSON object. The method getString returns the string
value of the specified key.

Apart from the these methods , there are other methods provided by this class for better parsing
JSON files. These methods are listed below −

[Link] Method & description

1 get(String name)

This method just Returns the value but in the form of Object type

2 getBoolean(String name)

This method returns the boolean value specified by the key

3 getDouble(String name)

This method returns the double value specified by the key

4 getInt(String name)

This method returns the integer value specified by the key

5 getLong(String name)
This method returns the long value specified by the key

6 length()

This method returns the number of name/value mappings in this object..

7 names()

This method returns an array containing the string names in this object.

Example
To experiment with this example , you can run this on an actual device or in an emulator.

Step Description
s

1 You will use Android studio to create an Android application. 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/[Link] file to add necessary code.

3 Modify the res/layout/activity_main to add respective XML components

4 Modify the res/values/[Link] to add necessary string components

5 Run the application and choose a running android device and install the application
on it and verify the results

Following is the content of the modified main activity file src/[Link].

package [Link];

import [Link];
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends Activity {

public void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);

TextView output = (TextView) findViewById([Link].textView1);


String strJson="

\"Employee\" :[

\"id\":\"01\",

\"name\":\"Gopal Varma\",

\"salary\":\"500000\"

},

\"id\":\"02\",

\"name\":\"Sairamkrishna\",

\"salary\":\"500000\"

},

\"id\":\"03\",

\"name\":\"Sathish kallakuri\",

\"salary\":\"600000\"

}";

String data = "";

try {

JSONObject jsonRootObject = new JSONObject(strJson);

//Get the instance of JSONArray that contains JSONObjects

JSONArray jsonArray = [Link]("Employee");

//Iterate the jsonArray and print the info of JSONObjects

for(int i=0; i < [Link](); i++){

JSONObject jsonObject = [Link](i);

int id = [Link]([Link]("id").toString());

String name = [Link]("name").toString();


float salary =
[Link]([Link]("salary").toString());

data += "Node"+i+" : \n id= "+ id +" \n Name= "+ name +" \n Salary= "+
salary +" \n ";

[Link](data);

} catch (JSONException e) {[Link]();}

Following is the modified content of the xml res/layout/activity_main.xml.

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="JSON example"

android:id="@+id/textView"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true"

android:textSize="30dp" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials Point"
android:id="@+id/textView2"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true"

android:textSize="35dp"

android:textColor="#ff16ff01" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="New Text"

android:id="@+id/textView1"

android:layout_below="@+id/textView2"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:layout_alignParentRight="true"

android:layout_alignParentEnd="true" />

</RelativeLayout>

Following is the content of [Link] file.

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

<manifest xmlns:android="[Link]

package="[Link]" >

<uses-permission android:name="[Link]"/>

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name=".MainActivity"
android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>

</manifest>

Android - LinkedIn Integration Tutorial


Android allows your application to connect to Linkedin and share data or any kind of updates on
Linkedin. This chapter is about integrating Linkedin into your application.

There are two ways through which you can integrate Linkedin and share something from your
application. These ways are listed below.

 Linkedin SDK (Scribe)


 Intent Share

Integrating Linkedin SDK


This is the first way of connecting with Linkedin. You have to register your application and then
receive some Application Id , and then you have to download the Linkedin SDK and add it to your
project. The steps are listed below.

Registering your application


Create a new Linkedin application at [Link] Click on add
new application. It is shown below:
Now fill in your application name , description and your website url. It is shown below −

If everything works fine, you will receive an API key with the secret. Just copy the API key and save
it somewhere. It is shown in the image below −

Downloading SDK and integrating it


Download Linkedin sdk here. Copy the [Link] jar into your project libs folder.

Posting updates on Linkedin application


Once everything is complete, you can run the Linkedin samples which can be foundhere.
Intent share
Intent share is used to share data between applications. In this strategy, we will not handle the SDK
stuff, but let the Linkedin application handles it. We will simply call the Linkedin application and
pass the data to share. This way, we can share something on Linkedin.

Android provides intent library to share data between activities and applications. In order to use it
as share intent, we have to specify the type of the share intent toACTION_SEND. Its syntax is
given below −

Intent shareIntent = new Intent();

[Link](Intent.ACTION_SEND);

Next thing you need to is to define the type of data to pass , and then pass the data. Its syntax is
given below −

[Link]("text/plain");

[Link](Intent.EXTRA_TEXT, "Hello, from tutorialspoint");

startActivity([Link](shareIntent, "Share your thoughts"));

Apart from the these methods , there are other methods available that allows intent handling. They
are listed below −

[Link] Method & description

1 addCategory(String category)

This method add a new category to the intent.

2 createChooser(Intent target, CharSequence title)

Convenience function for creating a ACTION_CHOOSER Intent

3 getAction()

This method retrieve the general action to be performed, such as ACTION_VIEW

4 getCategories()
This method return the set of all categories in the [Link] and the current scaling
event

5 putExtra(String name, int value)

This method add extended data to the intent.

6 toString()

This method returns a string containing a concise, human-readable description of this


object

Example
Here is an example demonstrating the use of IntentShare to share data on Linkedin. It creates a
basic application that allows you to share some text on Linkedin.

To experiment with this example, you can run this on an actual device or in an emulator.

Step Description
s

1 You will use Android studio to create an Android application under a package
[Link]. 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/[Link] file to add necessary code.

3 Modify the res/layout/activity_main to add respective XML components

4 Run the application and choose a running android device and install the application
on it and verify the results

Following is the content of the modified main activity file [Link].

package [Link];
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import static [Link];

public class MainActivity extends ActionBarActivity {

private ImageView img;

protected void onCreate(Bundle savedInstanceState) {


[Link](savedInstanceState);

setContentView([Link].activity_main);

img=(ImageView)findViewById([Link]);

Button b1=(Button)findViewById([Link]);

[Link](new [Link]() {

@Override

public void onClick(View v) {

Intent sharingIntent = new Intent(Intent.ACTION_SEND);

Uri screenshotUri =
[Link]("[Link]://[Link]/*");

try {

InputStream stream =
getContentResolver().openInputStream(screenshotUri);

catch (FileNotFoundException e) {

// TODO Auto-generated catch block

[Link]();

[Link]("image/jpeg");

[Link](Intent.EXTRA_STREAM, screenshotUri);

startActivity([Link](sharingIntent, "Share image using"));

});

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate([Link].menu_main, menu);

return true;

@Override

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 [Link].

int id = [Link]();

//noinspection SimplifiableIfStatement

if (id == [Link].action_settings) {

return true;

return [Link](item);

Following is the modified content of the xml res/layout/activity_main.xml.

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"
android:id="@+id/textView"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true"

android:textSize="30dp"

android:text="Linkedin Share" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials Point"

android:id="@+id/textView2"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true"

android:textSize="35dp"

android:textColor="#ff16ff01" />

<ImageView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/imageView"

android:layout_below="@+id/textView2"

android:layout_centerHorizontal="true"

android:src="@drawable/logo"/>

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Share"

android:id="@+id/button"

android:layout_marginTop="61dp"

android:layout_below="@+id/imageView"

android:layout_centerHorizontal="true" />
</RelativeLayout>

Following is the content of [Link] file.

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

<manifest xmlns:android="[Link]

package="[Link]" >

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name=".MainActivity"

android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>

</manifest>

Android - Loading Spinner Tutorial


You can show progress of a task in android through loading progress bar. The progress bar comes
in two shapes. Loading bar and Loading Spinner. In this chapter we will discuss spinner.

Spinner is used to display progress of those tasks whose total time of completion is unknown. In
order to use that, you just need to define it in the xml like this.
<ProgressBar

android:id="@+id/progressBar1"

style="?android:attr/progressBarStyleLarge"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerHorizontal="true" />

After defining it in xml, you have to get its reference in java file through ProgressBar class. Its
syntax is given below −

private ProgressBar spinner;

spinner = (ProgressBar)findViewById([Link].progressBar1);

After that you can make its disappear , and bring it back when needed through setVisibility Method.
Its syntax is given below −

[Link]([Link]);

[Link]([Link]);

Apart from these Methods, there are other methods defined in the ProgressBar class , that you can
use to handle spinner more effectively.

[Link] Method & description

1 isIndeterminate()

Indicate whether this progress bar is in indeterminate mode

2 postInvalidate()

Cause an invalidate to happen on a subsequent cycle through the event loop

3 setIndeterminate(boolean indeterminate)

Change the indeterminate mode for this progress bar

4 invalidateDrawable(Drawable dr)
Invalidates the specified Drawable

5 incrementSecondaryProgressBy(int diff)

Increase the progress bar's secondary progress by the specified amount

6 getProgressDrawable()

Get the drawable used to draw the progress bar in progress mode

Example
Here is an example demonstrating the use of ProgressBar to handle spinner. It creates a basic
application that allows you to turn on the spinner on clicking the button.

To experiment with this example , you can run this on an actual device or in an emulator.

Step Description
s

1 You will use Android studio to create an Android application under a package
[Link];. 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/[Link] file to add necessary code.

3 Modify the res/layout/activity_main to add respective XML components

4 Need to create a xml file in drawable [Link] contains shape and rotate information
about the progress bar

5 Run the application and choose a running android device and install the application
on it and verify the results

Following is the content of the modified main activity file src/[Link].


package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends Activity {

Button b1;

private ProgressBar spinner;

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);

b1=(Button)findViewById([Link]);

spinner=(ProgressBar)findViewById([Link]);

[Link]([Link]);

[Link](new [Link]() {

@Override

public void onClick(View v) {

[Link]([Link]);

});

}
@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link].menu_main, menu);

return true;

@Override

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 [Link].

int id = [Link]();

//noinspection SimplifiableIfStatement

if (id == [Link].action_settings) {

return true;

return [Link](item);

Following is the modified content of the xml res/layout/activity_main.xml.

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView android:text="Progress Dialog" android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/textview"

android:textSize="35dp"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials point"

android:id="@+id/textView"

android:layout_below="@+id/textview"

android:layout_centerHorizontal="true"

android:textColor="#ff7aff24"

android:textSize="35dp" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="download"

android:id="@+id/button"

android:layout_below="@+id/imageView"

android:layout_centerHorizontal="true" />

<ImageView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/imageView"

android:src="@drawable/abc"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true" />
<ProgressBar

style="?android:attr/progressBarStyleLarge"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/progressBar"

android:progressDrawable="@drawable/circular_progress_bar"

android:layout_below="@+id/button"

android:layout_alignRight="@+id/textView"

android:layout_alignEnd="@+id/textView"

android:layout_alignLeft="@+id/textview"

android:layout_alignStart="@+id/textview"

android:layout_alignParentBottom="true" />

</RelativeLayout>

Following is the content of the res/drawable/circular_progress_bar.xml.

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

<rotate

xmlns:android="[Link]

android:fromDegrees="90"

android:pivotX="50%"

android:pivotY="50%"

android:toDegrees="360">

<shape

android:innerRadiusRatio="3"

android:shape="ring"

android:thicknessRatio="7.0">

<gradient

android:centerColor="#007DD6"

android:endColor="#007DD6"
android:startColor="#007DD6"

android:angle="0"

android:type="sweep"

android:useLevel="false" />

</shape>

</rotate>

Following is the content of [Link] file.

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

<manifest xmlns:android="[Link]

package="[Link]"

android:versionCode="1"

android:versionName="1.0" >

<application

android:allowBackup="true"

android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name="[Link]"

android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>
</manifest>

Android - Localization Tutorial


An android application can run on many devices in many different regions. In order to make your
application more interactive, your application should handle text,numbers,files e.t.c in ways
appropriate to the locales where your application will be used.

The way of changing string into different languages is called as localization

In this chapter we will explain , how you can localize your application according to different regions
e.t.c. We will localize the strings used in the application, and in the same way other things can be
localized.

Localizing Strings
In order to localize the strings used in your application , make a new folder under reswith name
of values-local where local would be the replaced with the region.

For example, in the case of italy, the values-it folder would be made under res. It is shown in the
image below −
Once that folder is made, copy the [Link] default folder to the folder you have created.
And change its contents. For example, i have changed the value of hello_world string.

Italy, res/values-it/[Link]
<;?xml version="1.0" encoding="utf-8"?>

<resources>

<string name="hello_world">Ciao mondo!</string>

</resources>

Spanish, res/values-it/[Link]
<;?xml version="1.0" encoding="utf-8"?>

<resources>

<string name="hello_world">Hola Mundo!</string>

</resources>

French, res/values-it/[Link]
<;?xml version="1.0" encoding="utf-8"?>

<resources>

<string name="hello_world">Bonjour le monde !</string>

</resources>

Apart from these languages, the region code of other languages have been given in the table below

[Link] Language & code

1 Afrikanns

Code: af. Folder name: values-af

2 Arabic

Code: ar. Folder name: values-ar

3 Bengali
Code: bn. Folder name: values-bn

4 Czech

Code: cs. Folder name: values-cs

5 Chinese

Code: zh. Folder name: values-zh

6 German

Code: de. Folder name: values-de

7 French

Code: fr. Folder name: values-fr

8 Japanese

Code: ja. Folder name: values-ja

Example
To experiment with this example , you can run this on an actual device or in an emulator.

Step Description
s

1 You will use Android studio to create an Android application under a package
[Link]. 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 the res/layout/activity_main to add respective XML components

3 Modify the res/values/[Link] to add necessary string components


4 Run the application and choose a running android device and install the application
on it and verify the results

Following is the modified content of the xml res/layout/activity_main.xml.

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView android:text="Wifi" android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/textview"

android:textSize="35dp"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials point"

android:id="@+id/textView"

android:layout_below="@+id/textview"

android:layout_centerHorizontal="true"

android:textColor="#ff7aff24"

android:textSize="35dp" />

<TextView
android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/hindi"

android:id="@+id/textView2"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true"

android:layout_marginTop="50dp"

android:textColor="#ff59ff1a"

android:textSize="30dp" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/marathi"

android:id="@+id/textView3"

android:textSize="30dp"

android:textColor="#ff67ff1e"

android:layout_centerVertical="true"

android:layout_centerHorizontal="true" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/arabic"

android:id="@+id/textView4"

android:layout_below="@+id/textView3"

android:layout_centerHorizontal="true"

android:layout_marginTop="42dp"

android:textColor="#ff40ff08"

android:textSize="30dp" />

<TextView

android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:text="@string/chinese"

android:id="@+id/textView5"

android:layout_below="@+id/textView4"

android:layout_alignLeft="@+id/textView3"

android:layout_alignStart="@+id/textView3"

android:layout_marginTop="42dp"

android:textSize="30dp"

android:textColor="#ff56ff12"

android:layout_alignRight="@+id/textView3"

android:layout_alignEnd="@+id/textView3" />

</RelativeLayout>

Following is the content of the res/values/[Link].

<resources>

<string name="app_name">My Application</string>

<string name="hello_world">Hello world!</string>

<string name="action_settings">Settings</strin>

<string name="hindi">ట్యుటోరియల్స్ పాయింట్</string>

<string name="marathi">शिकवण्या बिंदू</string>

<string name="arabic">7‫<نقطة الدروس‬/string>

<string name="chinese">教程点</string>

</resources>

Android - Login Screen Tutorial


A login application is the screen asking your credentials to login to some particular application. You
might have seen it when logging into facebook,twitter e.t.c

This chapter explains, how to create a login screen and how to manage security when false
attempts are made.
First you have to define two TextView asking username and password of the user. The password
TextView must have inputType set to password. Its syntax is given below −

<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"

/>

Define a button with login text and set its onClick Property. After that define the function mentioned
in the onClick property in the java file.

<Button

android:id="@+id/button1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:onClick="login"

android:text="@string/Login"

/>

In the java file, inside the method of onClick get the username and passwords text
usinggetText() and toString() method and match it with the text using equals() function.

EditText username = (EditText)findViewById([Link].editText1);

EditText password = (EditText)findViewById([Link].editText2);

public void login(View view){

if([Link]().toString().equals("admin") &&
[Link]().toString().equals("admin")){

//correcct password
}else{

//wrong password

The last thing you need to do is to provide a security mechanism, so that unwanted attempts should
be avoided. For this initialize a variable and on each false attempt, decrement it. And when it
reaches to 0, disable the login button.

int counter = 3;

counter--;

if(counter==0){

//disble the button, close the application e.t.c

Example
Here is an example demonstrating a login application. It creates a basic application that gives you
only three attempts to login to an application.

To experiment with this example , you can run this on an actual device or in an emulator.

Step Description
s

1 You will use Android studio to create an Android application under a package
[Link]. 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.

3 Modify src/[Link] file to add necessary code.

4 Modify the res/layout/activity_main to add respective XML components

5 Run the application and choose a running android device and install the application
on it and verify the results

Following is the content of the modified main activity file src/[Link].


package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends Activity {

Button b1,b2;

EditText ed1,ed2;

TextView tx1;

int counter = 3;

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);
b1=(Button)findViewById([Link]);

ed1=(EditText)findViewById([Link]);

ed2=(EditText)findViewById([Link].editText2);

b2=(Button)findViewById([Link].button2);

tx1=(TextView)findViewById([Link].textView3);

[Link]([Link]);

[Link](new [Link]() {

@Override

public void onClick(View v) {

if([Link]().toString().equals("admin") &&

[Link]().toString().equals("admin")) {

[Link](getApplicationContext(),
"Redirecting...",Toast.LENGTH_SHORT).show();

else{

[Link](getApplicationContext(), "Wrong
Credentials",Toast.LENGTH_SHORT).show();

[Link]([Link]);

[Link]([Link]);

counter--;

[Link]([Link](counter));

if (counter == 0) {

[Link](false);

});
[Link](new [Link]() {

@Override

public void onClick(View v) {

finish();

});

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link].menu_main, menu);

return true;

@Override

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 [Link].

int id = [Link]();

//noinspection SimplifiableIfStatement

if (id == [Link].action_settings) {

return true;

return [Link](item);

Following is the modified content of the xml res/layout/activity_main.xml.

<RelativeLayout xmlns:android="[Link]
xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView android:text="Login" android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/textview"

android:textSize="35dp"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials point"

android:id="@+id/textView"

android:layout_below="@+id/textview"

android:layout_centerHorizontal="true"

android:textColor="#ff7aff24"

android:textSize="35dp" />

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/editText"

android:hint="Enter Name"

android:focusable="true"

android:textColorHighlight="#ff7eff15"

android:textColorHint="#ffff25e6"
android:layout_marginTop="46dp"

android:layout_below="@+id/imageView"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:layout_alignParentRight="true"

android:layout_alignParentEnd="true" />

<ImageView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/imageView"

android:src="@drawable/abc"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true" />

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:inputType="textPassword"

android:ems="10"

android:id="@+id/editText2"

android:layout_below="@+id/editText"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:layout_alignRight="@+id/editText"

android:layout_alignEnd="@+id/editText"

android:textColorHint="#ffff299f"

android:hint="Password" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Attempts Left:"
android:id="@+id/textView2"

android:layout_below="@+id/editText2"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:textSize="25dp" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="New Text"

android:id="@+id/textView3"

android:layout_alignTop="@+id/textView2"

android:layout_alignParentRight="true"

android:layout_alignParentEnd="true"

android:layout_alignBottom="@+id/textView2"

android:layout_toEndOf="@+id/textview"

android:textSize="25dp"

android:layout_toRightOf="@+id/textview" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="login"

android:id="@+id/button"

android:layout_alignParentBottom="true"

android:layout_toLeftOf="@+id/textview"

android:layout_toStartOf="@+id/textview" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Cancel"

android:id="@+id/button2"
android:layout_alignParentBottom="true"

android:layout_toRightOf="@+id/textview"

android:layout_toEndOf="@+id/textview" />

</RelativeLayout>

Following is the content of the res/values/[Link].

<resources>

<string name="app_name">My Application</string>

<string name="hello_world">Hello world!</string>

<string name="action_settings">Settings</string>

</resources>

Following is the content of [Link] file.

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

<manifest xmlns:android="[Link]

package="[Link]" >

<uses-permission android:name="[Link]" />

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name=".MainActivity"

android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />


</intent-filter>

</activity>

</application>

</manifest>

Android - MediaPlayer Tutorial


Android provides many ways to control playback of audio/video files and streams. One of this way
is through a class called MediaPlayer.

Android is providing MediaPlayer class to access built-in mediaplayer services like playing
audio,video e.t.c. In order to use MediaPlayer , we have to call a static Methodcreate() of this class.
This method returns an instance of MediaPlayer class. Its syntax is as follows −

MediaPlayer mediaPlayer = [Link](this, [Link]);

The second parameter is the name of the song that you want to play. You have to make a new
folder under your project with name raw and place the music file into it.

Once you have created the Mediaplayer object you can call some methods to start or stop the
music. These methods are listed below.

[Link]();

[Link]();

On call to start() method, the music will start playing from the beginning. If this method is called
again after the pause() method , the music would start playing from where it is left and not from the
beginning.

In order to start music from the beginning , you have to call reset() method. Its syntax is given
below.

[Link]();

Apart from the start and pause method, there are other methods provided by this class for better
dealing with audio/video files. These methods are listed below −
[Link] Method & description

1 isPlaying()

This method just returns true/false indicating the song is playing or not

2 seekTo(position)

This method takes an integer, and move song to that particular second

3 getCurrentDuration()

This method returns the current position of song in milliseconds

4 getDuration()

This method returns the total time duration of song in milliseconds

5 reset()

This method resets the media player

6 release()

This method releases any resource attached with MediaPlayer object

7 setVolume(float leftVolume, float rightVolume)

This method sets the up down volume for this player

8 setDataSource(FileDescriptor fd)

This method sets the data source of audio/video file

9 selectTrack(int index)

This method takes an integer, and select the track from the list on that particular
index

10 getTrackInfo()

This method returns an array of track information

Example
Here is an example demonstrating the use of MediaPlayer class. It creates a basic media player
that allows you to forward, backward , play and pause a song.

To experiment with this example, you need to run this on an actual device to hear the audio sound.

Step Description
s

1 You will use Android studio IDE to create an Android application under a package
[Link];. 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/[Link] file to add MediaPlayer code.

3 Modify the res/layout/activity_main to add respective XML components

4 Create a new folder under MediaPlayer with name as raw and place an mp3 music
file in it with name as song.mp3

5 Run the application and choose a running android device and install the application
on it and verify the results

Following is the content of the modified main activity file src/[Link].

package [Link];

import [Link];
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends Activity {

private Button b1,b2,b3,b4;

private ImageView iv;

private MediaPlayer mediaPlayer;

private double startTime = 0;

private double finalTime = 0;

private Handler myHandler = new Handler();;

private int forwardTime = 5000;

private int backwardTime = 5000;

private SeekBar seekbar;

private TextView tx1,tx2,tx3;


public static int oneTimeOnly = 0;

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);

b1 = (Button) findViewById([Link]);

b2 = (Button) findViewById([Link].button2);

b3=(Button)findViewById([Link].button3);

b4=(Button)findViewById([Link].button4);

iv=(ImageView)findViewById([Link]);

tx1=(TextView)findViewById([Link].textView2);

tx2=(TextView)findViewById([Link].textView3);

tx3=(TextView)findViewById([Link].textView4);

[Link]("Song.mp3");

mediaPlayer = [Link](this, [Link]);

seekbar=(SeekBar)findViewById([Link]);

[Link](false);

[Link](false);

[Link](new [Link]() {

@Override

public void onClick(View v) {

[Link](getApplicationContext(), "Playing
sound",Toast.LENGTH_SHORT).show();

[Link]();

finalTime = [Link]();

startTime = [Link]();
if (oneTimeOnly == 0) {

[Link]((int) finalTime);

oneTimeOnly = 1;

[Link]([Link]("%d min, %d sec",

[Link]((long) finalTime),

[Link]((long) finalTime) -

[Link]([Link]((long)
finalTime)))

);

[Link]([Link]("%d min, %d sec",

[Link]((long) startTime),

[Link]((long) startTime) -

[Link]([Link]((long)
startTime)))

);

[Link]((int)startTime);

[Link](UpdateSongTime,100);

[Link](true);

[Link](false);

});

[Link](new [Link]() {

@Override

public void onClick(View v) {

[Link](getApplicationContext(), "Pausing
sound",Toast.LENGTH_SHORT).show();

[Link]();

[Link](false);

[Link](true);

}
});

[Link](new [Link]() {

@Override

public void onClick(View v) {

int temp = (int)startTime;

if((temp+forwardTime)<=finalTime){

startTime = startTime + forwardTime;

[Link]((int) startTime);

[Link](getApplicationContext(),"You have Jumped forward 5


seconds",Toast.LENGTH_SHORT).show();

else{

[Link](getApplicationContext(),"Cannot jump forward 5


seconds",Toast.LENGTH_SHORT).show();

});

[Link](new [Link]() {

@Override

public void onClick(View v) {

int temp = (int)startTime;

if((temp-backwardTime)>0){

startTime = startTime - backwardTime;

[Link]((int) startTime);

[Link](getApplicationContext(),"You have Jumped backward 5


seconds",Toast.LENGTH_SHORT).show();

else{

[Link](getApplicationContext(),"Cannot jump backward 5


seconds",Toast.LENGTH_SHORT).show();
}

});

private Runnable UpdateSongTime = new Runnable() {

public void run() {

startTime = [Link]();

[Link]([Link]("%d min, %d sec",

[Link]((long) startTime),

[Link]((long) startTime) -

[Link]([Link].

toMinutes((long) startTime)))

);

[Link]((int)startTime);

[Link](this, 100);

};

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link].menu_main, menu);

return true;

@Override

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 [Link].


int id = [Link]();

//noinspection SimplifiableIfStatement

if (id == [Link].action_settings) {

return true;

return [Link](item);

Following is the modified content of the xml res/layout/activity_main.xml.

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView android:text="Music Palyer" android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/textview"

android:textSize="35dp"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials point"

android:id="@+id/textView"
android:layout_below="@+id/textview"

android:layout_centerHorizontal="true"

android:textColor="#ff7aff24"

android:textSize="35dp" />

<ImageView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/imageView"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true"

android:src="@drawable/abc"/>

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text=">>"

android:id="@+id/button"

android:layout_alignParentBottom="true"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="||"

android:id="@+id/button2"

android:layout_alignParentBottom="true"

android:layout_alignLeft="@+id/imageView"

android:layout_alignStart="@+id/imageView" />

<Button

android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:text="<"

android:id="@+id/button3"

android:layout_alignTop="@+id/button2"

android:layout_toRightOf="@+id/button2"

android:layout_toEndOf="@+id/button2" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="<<"

android:id="@+id/button4"

android:layout_alignTop="@+id/button3"

android:layout_toRightOf="@+id/button3"

android:layout_toEndOf="@+id/button3" />

<SeekBar

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/seekBar"

android:layout_alignLeft="@+id/textview"

android:layout_alignStart="@+id/textview"

android:layout_alignRight="@+id/textview"

android:layout_alignEnd="@+id/textview"

android:layout_above="@+id/button" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textAppearance="?android:attr/textAppearanceSmall"

android:text="Small Text"

android:id="@+id/textView2"

android:layout_above="@+id/seekBar"
android:layout_toLeftOf="@+id/textView"

android:layout_toStartOf="@+id/textView" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textAppearance="?android:attr/textAppearanceSmall"

android:text="Small Text"

android:id="@+id/textView3"

android:layout_above="@+id/seekBar"

android:layout_alignRight="@+id/button4"

android:layout_alignEnd="@+id/button4" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textAppearance="?android:attr/textAppearanceMedium"

android:text="Medium Text"

android:id="@+id/textView4"

android:layout_alignBaseline="@+id/textView2"

android:layout_alignBottom="@+id/textView2"

android:layout_centerHorizontal="true" />

</RelativeLayout>

Following is the content of the res/values/[Link].

<resources>

<string name="app_name">My Application</string>

<string name="hello_world">Hello world!</string>

<string name="action_settings">Settings</string>

</resources>

Following is the content of [Link] file.


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

<manifest xmlns:android="[Link]

package="[Link]"

android:versionCode="1"

android:versionName="1.0" >

<uses-sdk

android:minSdkVersion="13"

android:targetSdkVersion="22" />

<application

android:allowBackup="true"

android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name="[Link]"

android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>

</manifest>

Android - Multitouch Tutorial


Multi-touch gesture happens when more then one finger touches the screen at the same time.
Android allows us to detect these gestures.

Android system generates the following touch events whenever multiple fingers touches the screen
at the same time.

[Link] Event & description

1 ACTION_DOWN

For the first pointer that touches the screen. This starts the gesture.

2 ACTION_POINTER_DOWN

For extra pointers that enter the screen beyond the first.

3 ACTION_MOVE

A change has happened during a press gesture.

4 ACTION_POINTER_UP

Sent when a non-primary pointer goes up.

5 ACTION_UP

Sent when the last pointer leaves the screen.

So in order to detect any of the above mention event , you need to


overrideonTouchEvent() method and check these events manually. Its syntax is given below −

public boolean onTouchEvent(MotionEvent ev){

final int actionPeformed = [Link]();

switch(actionPeformed){

case MotionEvent.ACTION_DOWN:{

break;

}
case MotionEvent.ACTION_MOVE:{

break;

return true;

In these cases, you can perform any calculation you like. For example zooming , shrinking e.t.c. In
order to get the co-ordinates of the X and Y axis, you can call getX() and getY()method. Its syntax
is given below:

final float x = [Link]();

final float y = [Link]();

Apart from these methods, there are other methods provided by this MotionEvent class for better
dealing with multitouch. These methods are listed below:

[Link] Method & description

1 getAction()

This method returns the kind of action being performed

2 getPressure()

This method returns the current pressure of this event for the first index

3 getRawX()

This method returns the original raw X coordinate of this event

4 getRawY()

This method returns the original raw Y coordinate of this event

5 getSize()
This method returns the size for the first pointer index

6 getSource()

This method gets the source of the event

7 getXPrecision()

This method return the precision of the X coordinates being reported

8 getYPrecision()

This method return the precision of the Y coordinates being reported

Example
Here is an example demonstrating the use of Multitouch. It creates a basic Multitouch gesture
application that allows you to view the co-ordinates when multitouch is performed.

To experiment with this example , you need to run this on an actual device.

Step Description
s

1 You will use android studio to create an Android application under a package
[Link]. 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/[Link] file to add multitouch code.

3 Modify the res/layout/activity_main to add respective XML components.

4 Run the application and choose a running android device and install the application
on it and verify the results.

Following is the content of the modified main activity file src/[Link].


package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends Activity {

float xAxis = 0f;

float yAxis = 0f;

float lastXAxis = 0f;

float lastYAxis = 0f;

EditText ed1, ed2, ed3, ed4;

TextView tv1;

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);

ed1 = (EditText) findViewById([Link]);

ed2 = (EditText) findViewById([Link].editText2);

ed3 = (EditText) findViewById([Link].editText3);

ed4 = (EditText) findViewById([Link].editText4);

tv1=(TextView)findViewById([Link].textView2);
[Link](new [Link]() {

@Override

public boolean onTouch(View v, MotionEvent event) {

final int actionPeformed = [Link]();

switch(actionPeformed){

case MotionEvent.ACTION_DOWN:{

final float x = [Link]();

final float y = [Link]();

lastXAxis = x;

lastYAxis = y;

[Link]([Link](lastXAxis));

[Link]([Link](lastYAxis));

break;

case MotionEvent.ACTION_MOVE:{

final float x = [Link]();

final float y = [Link]();

final float dx = x - lastXAxis;

final float dy = y - lastYAxis;

xAxis += dx;

yAxis += dy;

[Link]([Link](xAxis));

[Link]([Link](yAxis));

break;

}
return true;

});

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link].menu_main, menu);

return true;

@Override

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 [Link].

int id = [Link]();

//noinspection SimplifiableIfStatement

if (id == [Link].action_settings) {

return true;

return [Link](item);

Following is the modified content of the xml res/layout/activity_main.xml.

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"

tools:context=".MainActivity"

android:transitionGroup="true">

<TextView android:text="Multitouch example" android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/textview"

android:textSize="35dp"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials point"

android:id="@+id/textView"

android:layout_below="@+id/textview"

android:layout_centerHorizontal="true"

android:textColor="#ff7aff24"

android:textSize="35dp" />

<ImageView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/imageView"

android:src="@drawable/abc"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true"

android:theme="@style/[Link]" />

<EditText
android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/editText"

android:layout_below="@+id/imageView"

android:layout_alignRight="@+id/textview"

android:layout_alignEnd="@+id/textview"

android:hint="X-Axis"

android:layout_alignLeft="@+id/textview"

android:layout_alignStart="@+id/textview"

android:textColorHint="#ff69ff0e" />

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/editText2"

android:layout_below="@+id/editText"

android:layout_alignLeft="@+id/editText"

android:layout_alignStart="@+id/editText"

android:textColorHint="#ff21ff11"

android:hint="Y-Axis"

android:layout_alignRight="@+id/editText"

android:layout_alignEnd="@+id/editText" />

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/editText3"

android:layout_below="@+id/editText2"

android:layout_alignLeft="@+id/editText2"

android:layout_alignStart="@+id/editText2"

android:hint="Move X"

android:textColorHint="#ff33ff20"

android:layout_alignRight="@+id/editText2"
android:layout_alignEnd="@+id/editText2" />

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/editText4"

android:layout_below="@+id/editText3"

android:layout_alignLeft="@+id/editText3"

android:layout_alignStart="@+id/editText3"

android:textColorHint="#ff31ff07"

android:hint="Move Y"

android:layout_alignRight="@+id/editText3"

android:layout_alignEnd="@+id/editText3" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Touch here"

android:id="@+id/textView2"

android:layout_alignParentBottom="true"

android:layout_alignLeft="@+id/imageView"

android:layout_alignStart="@+id/imageView"

android:focusable="true"

android:typeface="sans"

android:clickable="true"

android:textColor="#ff5480ff"

android:textSize="35dp" />

</RelativeLayout>

Following is the content of the res/values/[Link].

<resources>

<string name="app_name">My Application</string>


<string name="hello_world">Hello world!</string>

<string name="action_settings">Settings</string>

</resources>

Following is the content of [Link] file.

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

<manifest xmlns:android="[Link]

package="[Link]" >

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name=".MainActivity"

android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>

</manifest>

Android - Navigation Tutorial


In this chapter, we will see that how you can provide navigation forward and backward between an
application. We will first look at how to provide up navigation in an application.
Providing Up Navigation
The up navigation will allow our application to move to previous activity from the next activity. It can
be done like this.

To implement Up navigation, the first step is to declare which activity is the appropriate parent for
each activity. You can do it by specifying parentActivityName attribute in an activity. Its syntax is
given below −

android:parentActivityName="[Link]"

After that you need to call setDisplayHomeAsUpEnabled method of getActionBar() in the


onCreate method of the activity. This will enable the back button in the top action bar.

getActionBar().setDisplayHomeAsUpEnabled(true);

The last thing you need to do is to override onOptionsItemSelected method. when the user
presses it, your activity receives a call to onOptionsItemSelected(). The ID for the action
is [Link] syntax is given below −

public boolean onOptionsItemSelected(MenuItem item) {

switch ([Link]()) {

case [Link]:

[Link](this);

return true;

Handling device back button


Since you have enabled your back button to navigate within your application, you might want to put
the application close function in the device back button.

It can be done by overriding onBackPressed and then


calling moveTaskToBack andfinish method. Its syntax is given below −

@Override

public void onBackPressed() {


moveTaskToBack(true);

[Link]();

Apart from this setDisplayHomeAsUpEnabled method, there are other methods available in
ActionBar API class. They are listed below −

[Link] Method & description

1 addTab([Link] tab, boolean setSelected)

This method adds a tab for use in tabbed navigation mode

2 getSelectedTab()

This method returns the currently selected tab if in tabbed navigation mode and there
is at least one tab present

3 hide()

This method hide the ActionBar if it is currently showing

4 removeAllTabs()

This method remove all tabs from the action bar and deselect the current tab

5 selectTab([Link] tab)

This method select the specified tab

Example
The below example demonstrates the use of Navigation. It crates a basic application that allows
you to navigate withing your application.

To experiment with this example , you need to run this on an actual device or in an emulator .

Step Description
s

1 You will use Android studio to create an Android application under a package
[Link];. 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/[Link] file to add Activity code.

3 Create a new activity with the name of second_main.java and edit it to add activity
code.

4 Modify layout XML file res/layout/activity_main.xml add any GUI component if


required.

5 Modify layout XML file res/layout/[Link] add any GUI component if required.

6 Modify [Link] to add necessary code.

7 Run the application and choose a running android device and install the application
on it and verify the results.

Here is the content of src/[Link].

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends Activity {

Button b1;

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);

b1 = (Button) findViewById([Link]);

[Link](new [Link]() {

@Override

public void onClick(View v) {


Intent in=new Intent([Link],second_main.class);

startActivity(in);

});

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link].menu_main, menu);

return true;

@Override

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 [Link].

int id = [Link]();

//noinspection SimplifiableIfStatement

if (id == [Link].action_settings) {

return true;

return [Link](item);

Here is the content of src/second_main.java.

package [Link];

import [Link];
import [Link];

import [Link];

import [Link];

/**

* Created by Sairamkrishna on 4/6/2015.

*/

public class second_main extends Activity {

WebView wv;

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link]);

wv = (WebView) findViewById([Link]);

[Link](new MyBrowser());

[Link]().setLoadsImagesAutomatically(true);

[Link]().setJavaScriptEnabled(true);

[Link]("[Link]

private class MyBrowser extends WebViewClient {

@Override

public boolean shouldOverrideUrlLoading(WebView view, String url) {

[Link](url);

return true;

Here is the content of activity_main.xml.

<RelativeLayout xmlns:android="[Link]
xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"

tools:context=".MainActivity"

android:transitionGroup="true">

<TextView android:text="Navigation example" android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/textview"

android:textSize="35dp"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials point"

android:id="@+id/textView"

android:layout_below="@+id/textview"

android:layout_centerHorizontal="true"

android:textColor="#ff7aff24"

android:textSize="35dp" />

<ImageView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/imageView"

android:src="@drawable/abc"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true"
android:theme="@style/[Link]" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="first page"

android:id="@+id/button"

android:layout_below="@+id/imageView"

android:layout_alignRight="@+id/textView"

android:layout_alignEnd="@+id/textView"

android:layout_marginTop="61dp"

android:layout_alignLeft="@+id/imageView"

android:layout_alignStart="@+id/imageView" />

</RelativeLayout>

Here is the content of activity_main_activity2.xml.

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

<LinearLayout xmlns:android="[Link]

android:orientation="vertical" android:layout_width="match_parent"

android:layout_height="match_parent"

android:weightSum="1">

<WebView

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:id="@+id/webView"

android:layout_gravity="center_horizontal"

android:layout_weight="1.03" />

</LinearLayout>

Here is the content of [Link].


<resources>

<string name="app_name">My Application</string>

<string name="hello_world">Hello world!</string>

<string name="action_settings">Settings</string>

</resources>

Here is the content of [Link].

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

<manifest xmlns:android="[Link]

package="[Link]" >

<uses-permission android:name="[Link]"></uses-permission>

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name=".MainActivity"

android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

<activity android:name=".second_main"></activity>

</application>

</manifest>
Android - Network Connection Tutorial
Android lets your application connect to the internet or any other local network and allows you to
perform network operations.

A device can have various types of network connections. This chapter focuses on using either a Wi-
Fi or a mobile network connection.

Checking Network Connection


Before you perform any network operations, you must first check that are you connected to that
network or internet e.t.c. For this android provides ConnectivityManager class. You need to
instantiate an object of this class by calling getSystemService() method. Its syntax is given below

ConnectivityManager check = (ConnectivityManager)

[Link](Context.CONNECTIVITY_SERVICE);

Once you instantiate the object of ConnectivityManager class, you can


usegetAllNetworkInfo method to get the information of all the networks. This method returns an
array of NetworkInfo. So you have to receive it like this.

NetworkInfo[] info = [Link]();

The last thing you need to do is to check Connected State of the network. Its syntax is given below

for (int i = 0; i<[Link]; i++){

if (info[i].getState() == [Link]){

[Link](context, "Internet is connected

Toast.LENGTH_SHORT).show();

Apart from this connected states, there are other states a network can achieve. They are listed
below:

[Link] State
1 Connecting

2 Disconnected

3 Disconnecting

4 Suspended

5 Unknown

Performing Network Operations


After checking that you are connected to the internet, you can perform any network operation. Here
we are fetching the html of a website from a url.

Android provides HttpURLConnection and URL class to handle these operations. You need to
instantiate an object of URL class by providing the link of website. Its syntax is as follows −

String link = "[Link]

URL url = new URL(link);

After that you need to call openConnection method of url class and receive it in a
HttpURLConnection object. After that you need to call the connect method of HttpURLConnection
class.

HttpURLConnection conn = (HttpURLConnection) [Link]();

[Link]();

And the last thing you need to do is to fetch the HTML from the website. For this you will
use InputStream and BufferedReader class. Its syntax is given below −

InputStream is = [Link]();

BufferedReader reader =new BufferedReader(new InputStreamReader(is, "UTF-8"));

String webPage = "",data="";

while ((data = [Link]()) != null){


webPage += data + "\n";

Apart from this connect method, there are other methods available in HttpURLConnection class.
They are listed below −

[Link] Method & description

1 disconnect()

This method releases this connection so that its resources may be either reused or
closed

2 getRequestMethod()

This method returns the request method which will be used to make the request to
the remote HTTP server

3 getResponseCode()

This method returns response code returned by the remote HTTP server

4 setRequestMethod(String method)

This method Sets the request command which will be sent to the remote HTTP
server

5 usingProxy()

This method returns whether this connection uses a proxy server or not

Example
The below example demonstrates the use of HttpURLConnection class. It crates a basic application
that allows you to download HTML from a given web page.

To experiment with this example , you need to run this on an actual device on which wifi internet is
connected .
Step Description
s

1 You will use Android studio IDE to create an Android application under a package
[Link]. 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/[Link] file to add Activity code.

4 Modify layout XML file res/layout/activity_main.xml add any GUI component if


required.

6 Modify [Link] to add necessary permissions.

7 Run the application and choose a running android device and install the application
on it and verify the results.

Here is the content of src/[Link].

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends ActionBarActivity {

private ProgressDialog progressDialog;

private Bitmap bitmap = null;

Button b1;

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);

b1 = (Button) findViewById([Link]);

[Link](new [Link]() {

@Override

public void onClick(View v) {


checkInternetConenction();

downloadImage("[Link]

});

private void downloadImage(String urlStr) {

progressDialog = [Link](this, "", "Downloading Image from " +


urlStr);

final String url = urlStr;

new Thread() {

public void run() {

InputStream in = null;

Message msg = [Link]();

[Link] = 1;

try {

in = openHttpConnection(url);

bitmap = [Link](in);

Bundle b = new Bundle();

[Link]("bitmap", bitmap);

[Link](b);

[Link]();

catch (IOException e1) {

[Link]();

[Link](msg);

}.start();
}

private InputStream openHttpConnection(String urlStr) {

InputStream in = null;

int resCode = -1;

try {

URL url = new URL(urlStr);

URLConnection urlConn = [Link]();

if (!(urlConn instanceof HttpURLConnection)) {

throw new IOException("URL is not an Http URL");

HttpURLConnection httpConn = (HttpURLConnection) urlConn;

[Link](false);

[Link](true);

[Link]("GET");

[Link]();

resCode = [Link]();

if (resCode == HttpURLConnection.HTTP_OK) {

in = [Link]();

catch (MalformedURLException e) {

[Link]();

catch (IOException e) {

[Link]();

return in;
}

private Handler messageHandler = new Handler() {

public void handleMessage(Message msg) {

[Link](msg);

ImageView img = (ImageView) findViewById([Link]);

[Link]((Bitmap) ([Link]().getParcelable("bitmap")));

[Link]();

};

private boolean checkInternetConenction() {

// get Connectivity Manager object to check connection

ConnectivityManager connec
=(ConnectivityManager)getSystemService(getBaseContext().CONNECTIVITY_SERVICE);

// Check for network connections

if ( [Link](0).getState() ==
[Link] ||

[Link](0).getState() == [Link]
||

[Link](1).getState() == [Link]
||

[Link](1).getState() == [Link] )
{

[Link](this, " Connected ", Toast.LENGTH_LONG).show();

return true;

}else if (

[Link](0).getState() ==
[Link] ||

[Link](1).getState() ==
[Link] ) {

[Link](this, " Not Connected ", Toast.LENGTH_LONG).show();

return false;
}

return false;

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link].menu_main, menu);

return true;

@Override

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 [Link].

int id = [Link]();

//noinspection SimplifiableIfStatement

if (id == [Link].action_settings) {

return true;

return [Link](item);

Here is the content of activity_main.xml.

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="UI Animator Viewer"

android:id="@+id/textView"

android:textSize="25sp"

android:layout_centerHorizontal="true" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials point"

android:id="@+id/textView2"

android:layout_below="@+id/textView"

android:layout_alignRight="@+id/textView"

android:layout_alignEnd="@+id/textView"

android:textColor="#ff36ff15"

android:textIsSelectable="false"

android:textSize="35dp" />

<ImageView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/imageView"

android:layout_below="@+id/textView2"

android:layout_centerHorizontal="true" />

<Button

android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:text="Button"

android:id="@+id/button"

android:layout_below="@+id/imageView"

android:layout_centerHorizontal="true"

android:layout_marginTop="76dp" />

</RelativeLayout>

Here is the content of [Link].

<resources>

<string name="app_name">My Application</string>

<string name="hello_world">Hello world!</string>

<string name="action_settings">Settings</string>

</resources>

Here is the content of [Link]

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

<manifest xmlns:android="[Link]

package="[Link]" >

<uses-permission android:name="[Link]"/>

<uses-permission android:name="[Link].ACCESS_NETWORK_STATE" />

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name=".MainActivity"

android:label="@string/app_name" >
<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>

</manifest>

Android - NFC Guide Tutorial


NFC stands for Near Field Communication, and as the name implies it provides a wireless
communication mechanism between two compatible devices. NFC is a short range wireless
technology having a range of 4cm or less for two devices to share data.

How It Works
Like Bluetooth and WiFi, and all manner of other wireless signals, NFC works on the principle of
sending information over radio waves. Through NFC data is send through electromagnetic
induction between two devices.

NFC works on the bases of tags , it allows you to share some amount of data between an NFC tag
and an android powered device or between two android powered devices. Tags have various set of
complexities. The Data stored in the tag can be written in a variety of formats, but android APIs are
based around a NFC standard called as NFC Data Exchange Format(NDEF)..

The transmission frequency for data across NFC is 13.56 megahertz, and data can be sent at either
106, 212 or 424 kilobits per second, which is quick enough for a range of data transfers from
contact details to swapping pictures, songs and videos.

Android powered devices with NFC supports following three main modes of operations −

Three Modes of Operation


 Reader/Writer Mode:

It allows the NFC device to read or write passive NFC tags.


 P2P mode:

This mode allows NFC device to exchange data with other NFC peers.

 Card emulation mode:

It allows the NFC device itself to act as an NFC card, so it can be accessed by an external
NFC reader.

How it works with Android:


To get the permission to access NFC Hardware, add the following permission in your
[Link] file.

<uses-sdk android:minSdkVersion="10"/>

First thing to note is that not all android powered devices provide NFC technology. So to make sure
that your application shows up in google play for only those devices that have NFC Hardware, add
the following line in your [Link] file.

<uses-feature android:name="[Link]" android:required="true"/>

Android provides a [Link] package for communicating with another device. This package
contains following classes −

[Link] Classes

1 NdefMessage

It represents an immutable NDEF Message. .

2 NdefRecord

It represents an immutable NDEF Record.

3 NfcAdapter

It represents the local NFC adapter.


4 NfcEvent

It wraps information associated with any NFC event.

5 NfcManager

It is a high level manager used to obtain an instance of an NfcAdapter.

6 Tag

It represents an NFC tag that has been discovered.

NFC tags system works in android with the help of some intent filters that are listed below:

[Link] Filters & Features

1 ACTION_NDEF_DISCOVERED

This intent is used to start an Activity when a tag contains an NDEF payload.

2 ACTION_TECH_DISCOVERED

This intent is used to start an activity if the tag does not contain NDEF data, but is of
known technology.

3 ACTION_TAG_DISCOVERED

This intent is started if no activities handle the ACTION_NDEF_DISCOVERED or


ACTION_TECH_DISCOVERED intents.

To code an application that uses NFC technology is complex so don't use it in your app unless
necessary. The use of NFC is not common in devices but it is getting popular. Let's see what is the
future of this technology −
Future Applications
With this technology growing day by day and due to introduction of contact less payment systems
this technology is getting a boom. A service known as Google Wallet is already introduced in the
US which purpose is to make our smartphones a viable alternative to credit and transport cards.

Android - PHP/MYSQL Tutorial


In this chapter , we are going to explain, how you can integrate PHP and MYSQL with your android
application. This is very useful in case you have a webserver, and you want to access its data on
your android application.

MYSQL is used as a database at the webserver and PHP is used to fetch data from the database.
Our application will communicate with the PHP page with necessary parameters and PHP will
contact MYSQL database and will fetch the result and return the results to us.

PHP - MYSQL
Creating Database
MYSQL database can be created easily using this simple script. The CREATE
DATABASEstatement creates the database.

<?php

$con=mysqli_connect("[Link]","username","password");

$sql="CREATE DATABASE my_db";

if (mysqli_query($con,$sql))

echo "Database my_db created successfully";

?>

Creating Tables
Once database is created, its time to create some tables in the database. The CREATE
TABLE statement creates the database.

<?php
$con=mysqli_connect("[Link]","username","password","my_db");

$sql="CREATE TABLE table1(Username CHAR(30),Password CHAR(30),Role CHAR(30))";

if (mysqli_query($con,$sql))

echo "Table have been created successfully";

?>

Inserting Values in tables


When the database and tables are created. Now its time to insert some data into the tables.
The Insert Into statement creates the database.

<?php

$con=mysqli_connect("[Link]","username","password","my_db");

$sql="INSERT INTO table1 (FirstName, LastName, Age) VALUES ('admin',


'admin','adminstrator')";

if (mysqli_query($con,$sql))

echo "Values have been inserted successfully";

?>

PHP - GET and POST methods


PHP is also used to fetch the record from the mysql database once it is created. In order to fetch
record some information must be passed to PHP page regarding what record to be fetched.

The first method to pass information is through GET method in which $_GET command is used.
The variables are passed in the url and the record is fetched. Its syntax is given below −

<?php

$con=mysqli_connect("[Link]","username","password","database name");

if (mysqli_connect_errno($con))

echo "Failed to connect to MySQL: " . mysqli_connect_error();

}
$username = $_GET['username'];

$password = $_GET['password'];

$result = mysqli_query($con,"SELECT Role FROM table1 where Username='$username' and


Password='$password'");

$row = mysqli_fetch_array($result);

$data = $row[0];

if($data){

echo $data;

mysqli_close($con);

?>

The second method is to use POST method. The only change in the above script is to replace
$_GET with $_POST. In Post method , the variables are not passed through URL.

Android - Connecting MYSQL


Connecting Via Get Method
There are two ways to connect to MYSQL via PHP page. The first one is called Get method. We
will use HttpGet and HttpClient class to connect. Their syntax is given below −

URL url = new URL(link);

HttpClient client = new DefaultHttpClient();

HttpGet request = new HttpGet();

[Link](new URI(link));

After that you need to call execute method of HttpClient class and receive it in a HttpResponse
object. After that you need to open streams to receive the data.

HttpResponse response = [Link](request);

BufferedReader in = new BufferedReader

(new InputStreamReader([Link]().getContent()));

Connecting Via Post Method


In the Post method , the URLEncoder,URLConnection class will be used. The urlencoder will
encode the information of the passing variables. It's syntax is given below −
URL url = new URL(link);

String data = [Link]("username", "UTF-8")

+ "=" + [Link](username, "UTF-8");

data += "&" + [Link]("password", "UTF-8")

+ "=" + [Link](password, "UTF-8");

URLConnection conn = [Link]();

The last thing you need to do is to write this data to the link. After writing , you need to open stream
to receive the responded data.

OutputStreamWriter wr = new OutputStreamWriter([Link]());

[Link]( data );

BufferedReader reader = new BufferedReader(new

InputStreamReader([Link]()));

Example
The below example is a complete example of connecting your android application with MYSQL
database via PHP page. It crates a basic application that allows you to login using GET and POST
method.

PHP - MYSQL part


In this example a database with the name of temp has been created at [Link]. In that
database , a table has been created with the name of table1. This table has three fields.
(Username, Password, Role). The table has only one record which is
("admin","admin","administrator").

The php page has been given below which takes parameters by post method.

<?php

$con=mysqli_connect("[Link]","username","password","db_name");

if (mysqli_connect_errno($con))

echo "Failed to connect to MySQL: " . mysqli_connect_error();

$username = $_POST['username'];
$password = $_POST['password'];

$result = mysqli_query($con,"SELECT Role FROM table1 where

Username='$username' and Password='$password'");

$row = mysqli_fetch_array($result);

$data = $row[0];

if($data){

echo $data;

mysqli_close($con);

?>

Android Part
To experiment with this example , you need to run this on an actual device on which wifi internet is
connected.

Step Description
s

1 You will use Android studio IDE to create an Android application and name it as
PHPMYSQL under a package [Link]. 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/[Link] file to add Activity code.

3 Create src/[Link] file to add PHPMYSQL code.

4 Modify layout XML file res/layout/activity_main.xml add any GUI component if


required.

5 Modify res/values/[Link] file and add necessary string components.

6 Modify [Link] to add necessary permissions.


7 Run the application and choose a running android device and install the application
on it and verify the results.

Here is the content of src/[Link]/[Link].

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends Activity {

private EditText usernameField,passwordField;

private TextView status,role,method;

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);

usernameField = (EditText)findViewById([Link].editText1);

passwordField = (EditText)findViewById([Link].editText2);

status = (TextView)findViewById([Link].textView6);

role = (TextView)findViewById([Link].textView7);

method = (TextView)findViewById([Link].textView9);

}
@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link], menu);

return true;

public void login(View view){

String username = [Link]().toString();

String password = [Link]().toString();

[Link]("Get Method");

new SigninActivity(this,status,role,0).execute(username,password);

public void loginPost(View view){

String username = [Link]().toString();

String password = [Link]().toString();

[Link]("Post Method");

new SigninActivity(this,status,role,1).execute(username,password);

Here is the content of src/[Link]/[Link].

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class SigninActivity extends AsyncTask<String,Void,String>{

private TextView statusField,roleField;

private Context context;

private int byGetOrPost = 0;

//flag 0 means get and 1 means post.(By default it is get.)

public SigninActivity(Context context,TextView statusField,TextView roleField,int


flag) {

[Link] = context;

[Link] = statusField;

[Link] = roleField;

byGetOrPost = flag;

protected void onPreExecute(){

@Override

protected String doInBackground(String... arg0) {

if(byGetOrPost == 0){ //means by Get Method


try{

String username = (String)arg0[0];

String password = (String)arg0[1];

String link = "[Link]


username="+username+"& password="+password;

URL url = new URL(link);

HttpClient client = new DefaultHttpClient();

HttpGet request = new HttpGet();

[Link](new URI(link));

HttpResponse response = [Link](request);

BufferedReader in = new BufferedReader(new


InputStreamReader([Link]().getContent()));

StringBuffer sb = new StringBuffer("");

String line="";

while ((line = [Link]()) != null) {

[Link](line);

break;

[Link]();

return [Link]();

catch(Exception e){

return new String("Exception: " + [Link]());

else{

try{

String username = (String)arg0[0];

String password = (String)arg0[1];


String link="[Link]

String data = [Link]("username", "UTF-8") + "=" +


[Link](username, "UTF-8");

data += "&" + [Link]("password", "UTF-8") + "=" +


[Link](password, "UTF-8");

URL url = new URL(link);

URLConnection conn = [Link]();

[Link](true);

OutputStreamWriter wr = new OutputStreamWriter([Link]());

[Link]( data );

[Link]();

BufferedReader reader = new BufferedReader(new


InputStreamReader([Link]()));

StringBuilder sb = new StringBuilder();

String line = null;

// Read Server Response

while((line = [Link]()) != null)

[Link](line);

break;

return [Link]();

catch(Exception e){

return new String("Exception: " + [Link]());

}
}

@Override

protected void onPostExecute(String result){

[Link]("Login Successful");

[Link](result);

Here is the content of activity_main.xml.

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link]

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" >

<EditText

android:id="@+id/editText2"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignRight="@+id/editText1"

android:layout_below="@+id/editText1"

android:layout_marginTop="25dp"

android:ems="10"

android:inputType="textPassword" >

</EditText>

<EditText

android:id="@+id/editText1"
android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentRight="true"

android:layout_alignParentTop="true"

android:layout_marginTop="44dp"

android:ems="10" >

<requestFocus android:layout_width="wrap_content" />

</EditText>

<TextView

android:id="@+id/textView1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignBottom="@+id/editText1"

android:layout_alignParentLeft="true"

android:text="@string/Username" />

<TextView

android:id="@+id/textView3"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true"

android:text="@string/App"

android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView

android:id="@+id/textView7"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignBottom="@+id/textView5"
android:layout_alignLeft="@+id/textView6"

android:text="@string/Role"

android:textAppearance="?android:attr/textAppearanceMedium"

android:textSize="10sp" />

<TextView

android:id="@+id/textView5"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_below="@+id/textView6"

android:layout_marginTop="27dp"

android:layout_toLeftOf="@+id/editText1"

android:text="@string/LoginRole" />

<TextView

android:id="@+id/textView8"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_above="@+id/textView6"

android:layout_alignLeft="@+id/textView5"

android:layout_marginBottom="27dp"

android:text="@string/method" />

<TextView

android:id="@+id/textView4"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignLeft="@+id/textView8"

android:layout_below="@+id/button1"

android:layout_marginTop="86dp"

android:text="@string/LoginStatus" />

<TextView
android:id="@+id/textView6"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignTop="@+id/textView4"

android:layout_centerHorizontal="true"

android:text="@string/Status"

android:textAppearance="?android:attr/textAppearanceMedium"

android:textSize="10sp" />

<TextView

android:id="@+id/textView9"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignBottom="@+id/textView8"

android:layout_alignLeft="@+id/textView6"

android:text="@string/Choose"

android:textAppearance="?android:attr/textAppearanceMedium"

android:textSize="10sp" />

<Button

android:id="@+id/button2"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerVertical="true"

android:layout_toRightOf="@+id/textView6"

android:onClick="loginPost"

android:text="@string/LoginPost" />

<Button

android:id="@+id/button1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignBaseline="@+id/button2"
android:layout_alignBottom="@+id/button2"

android:layout_alignLeft="@+id/textView2"

android:onClick="login"

android:text="@string/LoginGet" />

<TextView

android:id="@+id/textView2"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignBaseline="@+id/editText2"

android:layout_alignBottom="@+id/editText2"

android:layout_alignParentLeft="true"

android:text="@string/Password" />

</RelativeLayout>

Here is the content of [Link].

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

<resources>

<string name="app_name">PHPMYSQL</string>

<string name="action_settings">Settings</string>

<string name="hello_world">Hello world!</string>

<string name="Username">Username</string>

<string name="Password">Password</string>

<string name="LoginGet">Login - Get</string>

<string name="LoginPost">Login - Post</string>

<string name="App">Login Application</string>

<string name="LoginStatus">Login Status</string>

<string name="LoginRole">Login Role</string>

<string name="Status">Not login</string>

<string name="Role">Not assigned</string>

<string name="method">Login Method</string>


<string name="Choose">Choose Method</string>

</resources>

Here is the content of [Link].

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

<manifest xmlns:android="[Link]

package="[Link]"

android:versionCode="1"

android:versionName="1.0" >

<uses-sdk

android:minSdkVersion="8"

android:targetSdkVersion="17" />

<uses-permission android:name="[Link]"/>

<uses-permission android:name="[Link].ACCESS_NETWORK_STATE" />

<application

android:allowBackup="true"

android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name="[Link]"

android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>
</application>

</manifest>

Android - Progress Circle Tutorial


The easiest way to make a progress circle is using through a class called ProgressDialog. The
loading bar can also be made through that class. The only logical difference between bar and circle
is , that the former is used when you know the total time for waiting for a particular task whereas the
later is used when you don't know the waiting time

In order to this , you need to instantiate an object of this class. Its syntax is.

ProgressDialog progress = new ProgressDialog(this);

Now you can set some properties of this dialog. Such as , its style,its text e.t.c

[Link]("Downloading Music :) ");

[Link](ProgressDialog.STYLE_SPINNER);

[Link](true);

Apart from these methods, there are other methods that are provided by the ProgressDialog class

[Link] description

1 getMax()

This methods returns the maximum value of the progress

2 incrementProgressBy(int diff)

This method increment the progress bar by the difference of value passed as a
parameter

3 setIndeterminate(boolean indeterminate)
This method set the progress indicator as determinate or indeterminate

4 setMax(int max)

This method set the maximum value of the progress dialog

5 setProgress(int value)

This method is used to update the progress dialog with some specific value

6 show(Context context, CharSequence title, CharSequence message)

This is a static method , used to display progress dialog

Example
This example demonstrates the spinning use of the progress dialog. It display a spinning progress
dialog on pressing the button.

To experiment with this example, you need to run this on an actual device on after developing the
application according to the steps below.

Step Description
s

1 You will use Android Studio to create an Android application under a package
[Link];. 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/[Link] 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 Run the application and choose a running android device and install the application
on it and verify the results.

Following is the content of the modified main activity file src/[Link].

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends Activity {

Button b1;

private ProgressDialog progressBar;

private int progressBarStatus = 0;

private Handler progressBarbHandler = new Handler();

private long fileSize = 0;

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);

b1=(Button)findViewById([Link]);

[Link](new [Link]() {

@Override

public void onClick(View v) {

progressBar = new ProgressDialog([Link]());

[Link](true);
[Link]("File downloading ...");

[Link](ProgressDialog.STYLE_SPINNER);

[Link](0);

[Link](100);

[Link]();

progressBarStatus = 0;

fileSize = 0;

new Thread(new Runnable() {

public void run() {

while (progressBarStatus < 100) {

progressBarStatus = downloadFile();

try {

[Link](1000);

catch (InterruptedException e) {

[Link]();

[Link](new Runnable() {

public void run() {

[Link](progressBarStatus);

});

if (progressBarStatus >= 100) {

try {

[Link](2000);

}
catch (InterruptedException e) {

[Link]();

[Link]();

}).start();

});

public int downloadFile() {

while (fileSize <= 1000000) {

fileSize++;

if (fileSize == 100000) {

return 10;

else if (fileSize == 200000) {

return 20;

else if (fileSize == 300000) {

return 30;

else if (fileSize == 400000) {

return 40;

else if (fileSize == 500000) {

return 50;

}
else if (fileSize == 700000) {

return 70;

else if (fileSize == 800000) {

return 80;

return 100;

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link].menu_main, menu);

return true;

@Override

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 [Link].

int id = [Link]();

//noinspection SimplifiableIfStatement

if (id == [Link].action_settings) {

return true;

return [Link](item);

}
Modify the content of res/layout/activity_main.xml to the following

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView android:text="Music Palyer" android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/textview"

android:textSize="35dp"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials point"

android:id="@+id/textView"

android:layout_below="@+id/textview"

android:layout_centerHorizontal="true"

android:textColor="#ff7aff24"

android:textSize="35dp" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="download"

android:id="@+id/button"

android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"

android:layout_marginBottom="112dp" />

<ImageView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/imageView"

android:src="@drawable/abc"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true" />

</RelativeLayout>

Modify the res/values/[Link] to the following

<resources>

<string name="app_name">My Application</string>

<string name="hello_world">Hello world!</string>

<string name="action_settings">Settings</string>

</resources>

This is the default [Link]

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

<manifest xmlns:android="[Link]

package="[Link]"

android:versionCode="1"

android:versionName="1.0" >

<application

android:allowBackup="true"

android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >
<activity

android:name="[Link]"

android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>

</manifest>

Android Progress Bar using ProgressDialog


Progress bars are used to show progress of a task. For example, when you are uploading or
downloading something from the internet, it is better to show the progress of download/upload to
the user.

In android there is a class called ProgressDialog that allows you to create progress bar. In order to
do this, you need to instantiate an object of this class. Its syntax is.

ProgressDialog progress = new ProgressDialog(this);

Now you can set some properties of this dialog. Such as, its style, its text etc.

[Link]("Downloading Music :) ");

[Link](ProgressDialog.STYLE_HORIZONTAL);

[Link](true);

Apart from these methods, there are other methods that are provided by the ProgressDialog class

Sr. No Title and description


1 getMax()

This method returns the maximum value of the progress.

2 incrementProgressBy(int diff)

This method increments the progress bar by the difference of value passed as a
parameter.

3 setIndeterminate(boolean indeterminate)

This method sets the progress indicator as determinate or indeterminate.

4 setMax(int max)

This method sets the maximum value of the progress dialog.

5 setProgress(int value)

This method is used to update the progress dialog with some specific value.

6 show(Context context, CharSequence title, CharSequence message)

This is a static method, used to display progress dialog.

Example
This example demonstrates the horizontal use of the progress dialog which is in fact a progress
bar. It display a progress bar on pressing the button.

To experiment with this example, you need to run this on an actual device after developing the
application according to the steps below.

Step Description
s

1 You will use Android studio to create an Android application under a package
[Link]. 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/[Link] file to add progress code to display the progress dialog.

3 Modify res/layout/activity_main.xml file to add respective XML code.

4 Run the application and choose a running android device and install the application
on it and verify the results.

Following is the content of the modified main activity file src/[Link].

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends ActionBarActivity {

Button b1;

private ProgressDialog progress;

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);

b1 = (Button) findViewById([Link].button2);
}

public void download(View view){

progress=new ProgressDialog(this);

[Link]("Downloading Music");

[Link](ProgressDialog.STYLE_HORIZONTAL);

[Link](true);

[Link](0);

[Link]();

final int totalProgressTime = 100;

final Thread t = new Thread() {

@Override

public void run() {

int jumpTime = 0;

while(jumpTime < totalProgressTime) {

try {

sleep(200);

jumpTime += 5;

[Link](jumpTime);

catch (InterruptedException e) {

// TODO Auto-generated catch block

[Link]();

};

[Link]();

}
Modify the content of res/layout/activity_main.xml to the following −

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/textView"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true"

android:textSize="30dp"

android:text="Progress bar" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials Point"

android:id="@+id/textView2"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true"

android:textSize="35dp"

android:textColor="#ff16ff01" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Download"
android:onClick="download"

android:id="@+id/button2"

android:layout_marginLeft="125dp"

android:layout_marginStart="125dp"

android:layout_centerVertical="true" />

</RelativeLayout>

This is the default [Link]−

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

<manifest xmlns:android="[Link]

package="[Link]" >

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name=".MainActivity"

android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>

</manifest>
Android - Push Notification Tutorial
A notification is a message you can display to the user outside of your application's normal UI. You
can create your own notifications in android very easily.

Android provides NotificationManager class for this purpose. In order to use this class, you need
to instantiate an object of this class by requesting the android system throughgetSystemService()
method. Its syntax is given below −

NotificationManager NM;

NM=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

After that you will create Notification through Notification class and specify its attributes such as
icon,title and time e.t.c. Its syntax is given below −

Notification notify=new
Notification([Link].stat_notify_more,title,[Link]());

The next thing you need to do is to create a PendingIntent by passing context and intent as a
parameter. By giving a PendingIntent to another application, you are granting it the right to perform
the operation you have specified as if the other application was yourself.

PendingIntent pending=[Link](getApplicationContext(), 0, new


Intent(),0);

The last thing you need to do is to call setLatestEventInfo method of the Notification class and
pass the pending intent along with notification subject and body details. Its syntax is given below.
And then finally call the notify method of the NotificationManager class.

[Link](getApplicationContext(), subject, body,pending);

[Link](0, notify);

Apart from the notify method, there are other methods available in the NotificationManager class.
They are listed below −

[Link] Method & description

1 cancel(int id)
This method cancel a previously shown notification.

2 cancel(String tag, int id)

This method also cancel a previously shown notification.

3 cancelAll()

This method cancel all previously shown notifications.

4 notify(int id, Notification notification)

This method post a notification to be shown in the status bar.

5 notify(String tag, int id, Notification notification)

This method also Post a notification to be shown in the status bar.

Example
The below example demonstrates the use of NotificationManager class. It crates a basic application
that allows you to create a notification.

To experiment with this example , you need to run this on an actual device or in an emulator.

Step Description
s

1 You will use Android studio to create an Android application under a


[Link]. 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/[Link] file to add Notification code.

3 Modify layout XML file res/layout/activity_main.xml add any GUI component if


required.
4 Run the application and choose a running android device and install the application
on it and verify the results.

Here is the content of [Link].

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import static [Link];

public class MainActivity extends ActionBarActivity {

EditText ed1,ed2,ed3;

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);
setContentView([Link].activity_main);

ed1=(EditText)findViewById([Link]);

ed2=(EditText)findViewById([Link].editText2);

ed3=(EditText)findViewById([Link].editText3);

Button b1=(Button)findViewById([Link]);

[Link](new [Link]() {

@Override

public void onClick(View v) {

String tittle=[Link]().toString().trim();

String subject=[Link]().toString().trim();

String body=[Link]().toString().trim();

NotificationManager
notif=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

Notification notify=new
Notification([Link],tittle,[Link]());

PendingIntent pending= [Link](getApplicationContext(),


0, new Intent(), 0);

[Link](getApplicationContext(),subject,body,pending);

[Link](0, notify);

});

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link].menu_main, menu);

return true;

}
@Override

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 [Link].

int id = [Link]();

//noinspection SimplifiableIfStatement

if (id == [Link].action_settings) {

return true;

return [Link](item);

Here is the content of activity_main.xml

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Notification"

android:id="@+id/textView"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true"
android:textSize="30dp" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials Point"

android:id="@+id/textView2"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true"

android:textSize="35dp"

android:textColor="#ff16ff01" />

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/editText"

android:layout_below="@+id/textView2"

android:layout_alignLeft="@+id/textView2"

android:layout_alignStart="@+id/textView2"

android:layout_marginTop="52dp"

android:layout_alignRight="@+id/textView2"

android:layout_alignEnd="@+id/textView2"

android:hint="Name" />

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/editText2"

android:hint="Subject"

android:layout_below="@+id/editText"

android:layout_alignLeft="@+id/editText"

android:layout_alignStart="@+id/editText"

android:layout_alignRight="@+id/editText"
android:layout_alignEnd="@+id/editText" />

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:inputType="textPersonName"

android:ems="10"

android:id="@+id/editText3"

android:hint="Body"

android:layout_below="@+id/editText2"

android:layout_alignLeft="@+id/editText2"

android:layout_alignStart="@+id/editText2"

android:layout_alignRight="@+id/editText2"

android:layout_alignEnd="@+id/editText2" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Notification"

android:id="@+id/button"

android:layout_marginTop="77dp"

android:layout_below="@+id/editText3"

android:layout_alignRight="@+id/textView"

android:layout_alignEnd="@+id/textView" />

</RelativeLayout/7gt;

Here is the content of [Link].

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

<manifest xmlns:android="[Link]

package="[Link]" >

<application
android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name=".MainActivity"

android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>

</manifest>

Android - RenderScript Tutorial

In this chapter, we will learn about Android RenderScript. Usually the apps on android are designed
as to consume as minimum resources as possible. But some applications like some 3D games
need high level processing on android.

To provide these applications high performance android introduced the RenderScript. It is android
based framework which is used for running applications that perform very highly computational
tasks. The development on this framework is done in Native Development Kit(NDK) provided by
android. RenderScript is extremely useful for applications which performs following types of actions

 3D Rendering
 Image Processing

 Computational Photography

 Computer Vision

How RenderScript Works


RenderScript framework is basically based on data parallel computation. It distributes your
application workload on all the processors available on your device like multi-core CPUs or GPUs.

This parallel distribution of workload frees the programmer from the tension of load balancing and
work scheduling. You can write more detailed and complex algorithms for your app without the
worry of computational power.

How to Begin:
To use the RenderScript Framework you must have following two things:

 A RenderScript Kernel
 RenderScript APIs

A RenderScript Kernel
A kernel is a program which manages data processing instructions and manage workload on
Central Processing Units.A kernel is a fundamental part of the operating system.

Similarly to run the RenderScript framework we need a written script named as Kernel to manage
all the data processing requests from our app and utilize more features of the android OS provided
by the NDK and as mentioned earlier that the development of RenderScript is done in the Native
Development Kit of Android.

The Kernel Script is written in C-99 standard of C-language. This Standard was before the
development of C++. A RenderScript kernel script file usually placed in .rs file. Each file is called as
a script. A RenderScript Kernel script can contain following elements −

[Link] Elements

1 A Language declaration

It declares the version of RenderScript Kernel language used in this script.


2 A package declaration

This declaration names the package name of the Java class which will be affected by
this Kernel Code.

3 Invokable functions

You can call these invokable functions from your JAVA code with arbitrary
arguments.

4 Script Global Variables

These are just like the variables defined in C and C++ programming language. You
can access these variables from your JAVA code.

Following is the Sample Code of a Kernel −

uchar4 __convert__((kernel)) invert(uchar4 in, uint32_t x, uint32_t y) {

uchar4 out = in;

out.r = 255 - in.r;

out.g = 255 - in.g;

return out;

RenderScript APIs
If you want to use RenderScript in your API, you can do it in following two ways:

[Link] APIs

1 [Link]

This API is available on devices running Android 3.0 and higher.

2 [Link]

This API is available on devices running Android 2.2 and higher.


To android support library following tools are required −

 Android SDK Tools version 22.2


 Android SDK Build-tools version 18.1.0

How to use RenderScript Support Library


First Open the [Link] file in your project and add following lines in the file −

[Link]=18

[Link]=true

[Link]=18.1.0

Now open your main class which use RenderScript and add an import for the Support Library
classes as following −

import [Link].*;

Following are the purposes of above mentioned properties that we add in


[Link] file.

[Link] Project properties

1 [Link]

It specifies the byte code version to be generated.

2 [Link]

It specifies a compatible version for the generated byte code to fall back.

3 [Link]

It Specifies the versions of Android SDK build tools to use.

Now call your RenderScript Kernel functions and compute complex algorithms in your app.

Android - RSS Reader Tutorial


RSS stands for Really Simple Syndication. RSS is an easy way to share your website updates and
content with your users so that users might not have to visit your site daily for any kind of updates.

RSS Example
RSS is a document that is created by the website with .xml extension. You can easily parse this
document and show it to the user in your application. An RSS document looks like this.

<rss version="2.0">

<channel>

<title>Sample RSS</title>

<link>[Link]

<description>World's best search engine</description>

</channel>

</rss>

RSS Elements
An RSS document such as above has the following elements.

[Link] Component & description

1 channel

This element is used to describe the RSS feed

2 title

Defines the title of the channel

3 link

Defines the hyper link to the channel

4 description

Describes the channel


Parsing RSS
Parsing an RSS document is more like parsing XML. So now lets see how to parse an XML
document.

For this, We will create XMLPullParser object , but in order to create that we will first create
XmlPullParserFactory object and then call its newPullParser() method to create XMLPullParser. Its
syntax is given below −

private XmlPullParserFactory xmlFactoryObject = [Link]();

private XmlPullParser myparser = [Link]();

The next step involves specifying the file for XmlPullParser that contains XML. It could be a file or
could be a Stream. In our case it is a [Link] syntax is given below −

[Link](stream, null);

The last step is to parse the XML. An XML file consist of events , Name , Text , AttributesValue
e.t.c. So XMLPullParser has a separate function for parsing each of the component of XML file. Its
syntax is given below −

int event = [Link]();

while (event != XmlPullParser.END_DOCUMENT)

String name=[Link]();

switch (event){

case XmlPullParser.START_TAG:

break;

case XmlPullParser.END_TAG:

if([Link]("temperature")){

temperature = [Link](null,"value");

break;

event = [Link]();
}

The method getEventType returns the type of event that happens. e.g: Document start , tag start
e.t.c. The method getName returns the name of the tag and since we are only interested in
temperature , so we just check in conditional statement that if we got a temperature tag , we call the
method getAttributeValue to return us the value of temperature tag.

Apart from the these methods, there are other methods provided by this class for better parsing
XML files. These methods are listed below −

[Link] Method & description

1 getAttributeCount()

This method just Returns the number of attributes of the current start tag.

2 getAttributeName(int index)

This method returns the name of the attribute specified by the index value.

3 getColumnNumber()

This method returns the Returns the current column number, starting from 0.

4 getDepth()

This method returns Returns the current depth of the element.

5 getLineNumber()

Returns the current line number, starting from 1.

6 getNamespace()

This method returns the name space URI of the current element.

7 getPrefix()
This method returns the prefix of the current element.

8 getName()

This method returns the name of the tag.

9 getText()

This method returns the text for that particular element.

10 isWhitespace()

This method checks whether the current TEXT event contains only white space
characters.

Example
Here is an example demonstrating the use of XMLPullParser class. It creates a basic Parsing
application that allows you to parse an RSS document present here
at[Link] and then show the result.

To experiment with this example, you can run this on an actual device or in an emulator.

Step Description
s

1 You will use Android studio to create an Android application under a package
[Link]. 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/[Link] file to add necessary code.

3 Modify the res/layout/activity_main to add respective XML components.

4 Create a new java file under src/[Link] to fetch and parse XML data.
5 Create a new java file under src/[Link] to display result of XML

5 Modify [Link] to add necessary internet permission.

6 Run the application and choose a running android device and install the application
on it and verify the results.

Following is the content of the modified main activity file src/[Link].

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends Activity {

EditText title,link,description;

Button b1,b2;

private String finalUrl="[Link]

private HandleXML obj;

@Override
protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);

title = (EditText) findViewById([Link]);

link = (EditText) findViewById([Link].editText2);

description = (EditText) findViewById([Link].editText3);

b1=(Button)findViewById([Link]);

b2=(Button)findViewById([Link].button2);

[Link](new [Link]() {

@Override

public void onClick(View v) {

obj = new HandleXML(finalUrl);

[Link]();

while([Link]);

[Link]([Link]());

[Link]([Link]());

[Link]([Link]());

});

[Link](new [Link]() {

@Override

public void onClick(View v) {

Intent in=new Intent([Link],[Link]);

startActivity(in);

});

@Override
public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link].menu_main, menu);

return true;

@Override

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 [Link].

int id = [Link]();

//noinspection SimplifiableIfStatement

if (id == [Link].action_settings) {

return true;

return [Link](item);

Following is the content of the java file src/[Link].

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];
public class HandleXML {

private String title = "title";

private String link = "link";

private String description = "description";

private String urlString = null;

private XmlPullParserFactory xmlFactoryObject;

public volatile boolean parsingComplete = true;

public HandleXML(String url){

[Link] = url;

public String getTitle(){

return title;

public String getLink(){

return link;

public String getDescription(){

return description;

public void parseXMLAndStoreIt(XmlPullParser myParser) {

int event;

String text=null;

try {

event = [Link]();

while (event != XmlPullParser.END_DOCUMENT) {


String name=[Link]();

switch (event){

case XmlPullParser.START_TAG:

break;

case [Link]:

text = [Link]();

break;

case XmlPullParser.END_TAG:

if([Link]("title")){

title = text;

else if([Link]("link")){

link = text;

else if([Link]("description")){

description = text;

else{

break;

event = [Link]();

}
parsingComplete = false;

catch (Exception e) {

[Link]();

public void fetchXML(){

Thread thread = new Thread(new Runnable(){

@Override

public void run() {

try {

URL url = new URL(urlString);

HttpURLConnection conn = (HttpURLConnection) [Link]();

[Link](10000 /* milliseconds */);

[Link](15000 /* milliseconds */);

[Link]("GET");

[Link](true);

// Starts the query

[Link]();

InputStream stream = [Link]();

xmlFactoryObject = [Link]();

XmlPullParser myparser = [Link]();

[Link](XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);

[Link](stream, null);

parseXMLAndStoreIt(myparser);
[Link]();

catch (Exception e) {

});

[Link]();

Create a file and named as [Link] file under directory java/[Link]

package [Link];

import [Link];

import [Link];

import [Link];

/**

* Created by Sairamkrishna on 4/6/2015.

*/

public class second extends Activity {

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].second_activity);

WebView w1=(WebView)findViewById([Link]);

[Link]("[Link]

Create a xml file at res/layout/second_main.xml

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


<LinearLayout xmlns:android="[Link]

android:orientation="vertical" android:layout_width="match_parent"

android:layout_height="match_parent">

<WebView

android:layout_width="match_parent"

android:layout_height="match_parent"

android:id="@+id/webView"

android:layout_gravity="center_horizontal" />

</LinearLayout>

Modify the content of res/layout/activity_main.xml to the following −

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"

tools:context=".MainActivity"

android:transitionGroup="true">

<TextView android:text="RSS example" android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/textview"

android:textSize="35dp"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials point"
android:id="@+id/textView"

android:layout_below="@+id/textview"

android:layout_centerHorizontal="true"

android:textColor="#ff7aff24"

android:textSize="35dp" />

<ImageView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/imageView"

android:src="@drawable/abc"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true"

android:theme="@style/[Link]" />

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/editText"

android:layout_below="@+id/imageView"

android:hint="Tittle"

android:textColorHint="#ff69ff0e"

android:layout_alignParentRight="true"

android:layout_alignParentEnd="true"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true" />

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/editText2"

android:layout_below="@+id/editText"

android:layout_alignLeft="@+id/editText"
android:layout_alignStart="@+id/editText"

android:textColorHint="#ff21ff11"

android:hint="Link"

android:layout_alignRight="@+id/editText"

android:layout_alignEnd="@+id/editText" />

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/editText3"

android:layout_below="@+id/editText2"

android:layout_alignLeft="@+id/editText2"

android:layout_alignStart="@+id/editText2"

android:hint="Description"

android:textColorHint="#ff33ff20"

android:layout_alignRight="@+id/editText2"

android:layout_alignEnd="@+id/editText2" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Fetch"

android:id="@+id/button"

android:layout_below="@+id/editText3"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:layout_toLeftOf="@+id/imageView"

android:layout_toStartOf="@+id/imageView" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Result"
android:id="@+id/button2"

android:layout_alignTop="@+id/button"

android:layout_alignRight="@+id/editText3"

android:layout_alignEnd="@+id/editText3" />

</RelativeLayout>

Modify the res/values/[Link] to the following

<resources>

<string name="app_name">My Application</string>

<string name="hello_world">Hello world!</string>

<string name="action_settings">Settings</string>

</resources>

This is the default [Link].

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

<manifest xmlns:android="[Link]

package="[Link]" >

<uses-permission android:name="[Link]"/>

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name=".MainActivity"

android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />


</intent-filter>

</activity>

<activity android:name=".second"></activity>

</application>

</manifest>

Android - Sensors Tutorial


Most of the android devices have built-in sensors that measure motion, orientation, and various
environmental condition. The android platform supports three broad categories of sensors.

 Motion Sensors

 Environmental sensors

 Position sensors

Some of the sensors are hardware based and some are software based sensors. Whatever the
sensor is, android allows us to get the raw data from these sensors and use it in our application.
For this android provides us with some classes.

Android provides SensorManager and Sensor classes to use the sensors in our application. In
order to use sensors , first thing you need to do is to instantiate the object of SensorManager class.
It can be achieved as follows.

SensorManager sMgr;

sMgr = (SensorManager)[Link](SENSOR_SERVICE);

The next thing you need to do is to instantiate the object of Sensor class by calling the
getDefaultSensor() method of the SensorManager class. Its syntax is given below −

Sensor light;

light = [Link](Sensor.TYPE_LIGHT);

Once that sensor is declared , you need to register its listener and override two methods which are
onAccuracyChanged and onSensorChanged. Its syntax is as follows −
[Link](this, light,SensorManager.SENSOR_DELAY_NORMAL);

public void onAccuracyChanged(Sensor sensor, int accuracy) {

public void onSensorChanged(SensorEvent event) {

Getting list of sensors supported.


You can get a list of sensors supported by your device by calling the getSensorList method , which
will return a list of sensors containing their name and version number and much more information.
You can then iterate the list to get the information. Its syntax is given below:

sMgr = (SensorManager)[Link](SENSOR_SERVICE);

List<Sensor> list = [Link](Sensor.TYPE_ALL);

for(Sensor sensor: list){

Apart from the these methods , there are other methods provided by the SensorManager class for
managing sensors framework. These methods are listed below −

[Link] Method & description

1 getDefaultSensor(int type)

This method get the default sensor for a given type.

2 getOrientation(float[] R, float[] values)

This method returns a description of the current primary clip on the clipboard but not
a copy of its data.

3 getInclination(float[] I)

This method computes the geomagnetic inclination angle in radians from the
inclination matrix.

4 registerListener(SensorListener listener, int sensors, int rate)


This method registers a listener for the sensor

5 unregisterListener(SensorEventListener listener, Sensor sensor)

This method unregisters a listener for the sensors with which it is registered.

6 getOrientation(float[] R, float[] values)

This method computes the device's orientation based on the rotation matrix.

7 getAltitude(float p0, float p)

This method computes the Altitude in meters from the atmospheric pressure and the
pressure at sea level.

Example
Here is an example demonstrating the use of SensorManager class. It creates a basic application
that allows you to view the list of sensors on your device.

To experiment with this example , you can run this on an actual device or in an emulator.

Step Description
s

1 You will use Android studio to create an Android application under a package
[Link]. 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/[Link] file to add necessary code.

3 Modify the res/layout/activity_main to add respective XML components.

4 Run the application and choose a running android device and install the application
on it and verify the results.
Following is the content of the modified [Link].

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends Activity {

TextView tv1=null;

private SensorManager mSensorManager;

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);

tv1 = (TextView) findViewById([Link].textView2);

[Link]([Link]);

mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);


List<Sensor> mList= [Link](Sensor.TYPE_ALL);

for (int i = 1; i < [Link](); i++) {

[Link]([Link]);

[Link]("\n" + [Link](i).getName() + "\n" + [Link](i).getVendor() +


"\n" + [Link](i).getVersion());

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link].menu_main, menu);

return true;

@Override

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 [Link].

int id = [Link]();

//noinspection SimplifiableIfStatement

if (id == [Link].action_settings) {

return true;

return [Link](item);

Following is the modified content of the xml activity_main.xml.

<RelativeLayout xmlns:android="[Link]
xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"

tools:context=".MainActivity"

android:transitionGroup="true">

<TextView android:text="Sensor " android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/textview"

android:textSize="35dp"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials point"

android:id="@+id/textView"

android:layout_below="@+id/textview"

android:layout_centerHorizontal="true"

android:textColor="#ff7aff24"

android:textSize="35dp" />

<ImageView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/imageView"

android:src="@drawable/abc"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true"
android:theme="@style/[Link]" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="New Text"

android:id="@+id/textView2"

android:layout_below="@+id/imageView"

android:layout_alignParentBottom="true"

android:layout_alignParentRight="true"

android:layout_alignParentEnd="true"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true" />

</RelativeLayout>

Following is the content of the res/values/[Link].

<resources>

<string name="app_name">My Application</string>

<string name="hello_world">Hello world!</string>

<string name="action_settings">Settings</string>

</resources>

Following is the content of [Link] file.

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

<manifest xmlns:android="[Link]

package="[Link]" >

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >
<activity

android:name=".MainActivity"

android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>

</manifest>

Android - Session Management Tutorial


Session help you when want to store user data outside your application, so that when the next time
user use your application, you can easily get back his details and perform accordingly.

This can be done in many ways. But the most easiest and nicest way of doing this is
through Shared Preferences.

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 pointing to the file that contains the values of preferences.

SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES,


Context.MODE_PRIVATE);

You can save something in the sharedpreferences by using [Link] class. You
will call the edit method of SharedPreference instance and will receive it in an editor object. Its
syntax is −

Editor editor = [Link]();


[Link]("key", "value");

[Link]();

Apart from the putString method, there are methods available in the editor class that allows
manipulation of data inside shared preferences. They are listed as follows −

[Link] Mode and description

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

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

Session Management through Shared Preferences


In order to perform session management from shared preferences , we need to check the values or
data stored in shared preferences in the onResume method. If we don't have the data, we will start
the application from the beginning as it is newly installed. But if we got the data, we will start from
the where the user left it. It is demonstrated in the example below:

Example
The below example demonstrates the use of Session Management. It crates a basic application
that allows you to login for the first time. And then when you exit the application without logging out,
you will be brought back to the same place if you start the application again. But if you logout from
the application, you will be brought back to the main login screen.

To experiment with this example , you need to run this on an actual device or in an emulator .

Step Description
s

1 You will use android studio IDE to create an Android application under a package
[Link];. 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/[Link] file to add progress code to add session code.

3 Create New Activity and it name as [Link] this file to add progress code to
add session code.

4 Modify res/layout/activity_main.xml file to add respective XML code.

5 Modify res/layout/second_main.xml file to add respective XML code.

7 Run the application and choose a running android device and install the application
on it and verify the results.

Here is the content of [Link].

package [Link];
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends ActionBarActivity {

EditText ed1,ed2,ed3;

Button b1;

Intent in;

public static final String MyPREFERENCES = "MyPrefs" ;

public static final String Name = "nameKey";

public static final String Phone = "phoneKey";

public static final String Email = "emailKey";

SharedPreferences sharedpreferences;

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);

ed1=(EditText)findViewById([Link]);

ed2=(EditText)findViewById([Link].editText2);

ed3=(EditText)findViewById([Link].editText3);

b1=(Button)findViewById([Link]);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

[Link](new [Link]() {

@Override

public void onClick(View v) {

String n = [Link]().toString();

String ph = [Link]().toString();

String e = [Link]().toString();

[Link] editor = [Link]();

[Link](Name, n);

[Link](Phone, ph);

[Link](Email, e);

[Link]();

in = new Intent([Link],[Link]);

startActivity(in);

});

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link].menu_main, menu);

return true;

@Override

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 [Link].

int id = [Link]();

//noinspection SimplifiableIfStatement

if (id == [Link].action_settings) {

return true;

return [Link](item);

Here is the content of second_main.java.

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import static [Link].button3;

/**

* Created by Sairamkrishna on 4/7/2015.

*/

public class second extends Activity {

Button bu=null;

Button bu2=null;

@Override

protected void onCreate(Bundle savedInstanceState) {


[Link](savedInstanceState);

setContentView([Link].second_main);

bu=(Button)findViewById([Link].button2);

bu2=(Button)findViewById([Link].button3);

public void logout(View view){

SharedPreferences sharedpreferences =
getSharedPreferences([Link], Context.MODE_PRIVATE);

[Link] editor = [Link]();

[Link]();

[Link]();

public void close(View view){

finish();

Here is the content of activity_main.xml.

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Shared Preference"
android:id="@+id/textView"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true"

android:textSize="35dp" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials Point"

android:id="@+id/textView2"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true"

android:textSize="35dp"

android:textColor="#ff16ff01" />

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/editText"

android:layout_below="@+id/textView2"

android:layout_marginTop="67dp"

android:hint="Name"

android:layout_alignParentRight="true"

android:layout_alignParentEnd="true"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true" />

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/editText2"

android:layout_below="@+id/editText"

android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"

android:layout_alignParentRight="true"

android:layout_alignParentEnd="true"

android:hint="Pass" />

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/editText3"

android:layout_below="@+id/editText2"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:layout_alignParentRight="true"

android:layout_alignParentEnd="true"

android:hint="Email" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="login"

android:id="@+id/button"

android:layout_below="@+id/editText3"

android:layout_centerHorizontal="true"

android:layout_marginTop="50dp" />

</RelativeLayout>

Here is the content of activity_welcome.xml.

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

<RelativeLayout xmlns:android="[Link]

android:orientation="vertical" android:layout_width="match_parent"

android:layout_height="match_parent">
<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Logout"

android:onClick="logout"

android:id="@+id/button2"

android:layout_gravity="center_horizontal"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true"

android:layout_marginTop="191dp" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Close"

android:onClick="close"

android:id="@+id/button3"

android:layout_below="@+id/button2"

android:layout_centerHorizontal="true"

android:layout_marginTop="69dp" />

</RelativeLayout>

Here is the content of [Link].

<resources>

<string name="app_name">My Application</string>

<string name="hello_world">Hello world!</string>

<string name="action_settings">Settings</string>

</resources>

Here is the content of [Link].

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

<manifest xmlns:android="[Link]
package="[Link]" >

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name=".MainActivity"

android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

<activity android:name=".second"></activity>

</application>

</manifest>

Let's try to run your application. I assume you had created your AVD while doing environment
setup. To run the app from Android studio, open one of your project's activity files and click Run
icon from the tool bar. Android studio installs the app on your AVD and starts it and if everything is
fine with your set-up and application, it will display following Emulator window −
Type in your username and password (type anything you like, but remember what you type),
and click on login button. It is shown in the image below −
As soon as you click on login button, you will be brought to this Welcome screen. Now your login
information is stored in shared preferences.
Now click on Exit without logout button and you will be brought back to the home screen and in
preference file out put would be as shown below image
If you open [Link] file as note file, it would be as follows

If you click on logout button, it will erase preference values. and if you entered different values as
inputs,it will enter those values as preference in XML
Android - Shared Preferences Tutorial
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 pointing 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 available that are listed below:

[Link] Mode and description

1 MODE_APPEND

This will append the new preferences with the already existing preferences

2 MODE_ENABLE_WRITE_AHEAD_LOGGING

Database open flag. When it is set , it would enable write ahead logging by default

3 MODE_MULTI_PROCESS

This method will check for modification of preferences even if the sharedpreference
instance has already been loaded

4 MODE_PRIVATE

By setting this mode , the file can only be accessed using calling application

5 MODE_WORLD_READABLE

This mode allow other application to read the preferences

6 MODE_WORLD_WRITEABLE
This mode allow other application to write the preferences

You can save something in the sharedpreferences by using [Link] class. You
will call the edit method of SharedPreference instance and will receive it in an editor object. Its
syntax is −

Editor editor = [Link]();

[Link]("key", "value");

[Link]();

Apart from the putString method , there are methods available in the editor class that allows
manipulation of data inside shared preferences. They are listed as follows:

Sr. Mode and description


NO

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

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 .

To experiment with this example , you need to run this on an actual device on after developing the
application according to the steps below:

Step Description
s

1 You will use Android studio to create an Android application under a package
[Link]. 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/[Link] 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 Run the application and choose a running android device and install the application
on it and verify the results.

Following is the content of the modified [Link].

package [Link];

import [Link];

import [Link];

import [Link];
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends ActionBarActivity {

EditText ed1,ed2,ed3;

Button b1;

public static final String MyPREFERENCES = "MyPrefs" ;

public static final String Name = "nameKey";

public static final String Phone = "phoneKey";

public static final String Email = "emailKey";

SharedPreferences sharedpreferences;

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);

ed1=(EditText)findViewById([Link]);

ed2=(EditText)findViewById([Link].editText2);

ed3=(EditText)findViewById([Link].editText3);

b1=(Button)findViewById([Link]);

sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

[Link](new [Link]() {

@Override

public void onClick(View v) {

String n = [Link]().toString();
String ph = [Link]().toString();

String e = [Link]().toString();

[Link] editor = [Link]();

[Link](Name, n);

[Link](Phone, ph);

[Link](Email, e);

[Link]();

[Link]([Link],"Thanks",Toast.LENGTH_LONG).show();

});

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link].menu_main, menu);

return true;

@Override

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 [Link].

int id = [Link]();

//noinspection SimplifiableIfStatement

if (id == [Link].action_settings) {

return true;

return [Link](item);
}

Following is the content of the modified main activity file res/layout/activiy_main.xml.

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Shared Preference "

android:id="@+id/textView"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true"

android:textSize="35dp" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials Point"

android:id="@+id/textView2"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true"

android:textSize="35dp"

android:textColor="#ff16ff01" />

<EditText
android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/editText"

android:layout_below="@+id/textView2"

android:layout_marginTop="67dp"

android:hint="Name"

android:layout_alignParentRight="true"

android:layout_alignParentEnd="true"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true" />

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/editText2"

android:layout_below="@+id/editText"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:layout_alignParentRight="true"

android:layout_alignParentEnd="true"

android:hint="Pass" />

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/editText3"

android:layout_below="@+id/editText2"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:layout_alignParentRight="true"

android:layout_alignParentEnd="true"

android:hint="Email" />
<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Save"

android:id="@+id/button"

android:layout_below="@+id/editText3"

android:layout_centerHorizontal="true"

android:layout_marginTop="50dp" />

</RelativeLayout>

Following is the content of the modified content of file res/values/[Link].

<resources>

<string name="app_name">My Application</string>

<string name="hello_world">Hello world!</string>

<string name="action_settings">Settings</string>

</resources>

Following is the content default file [Link].

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

<manifest xmlns:android="[Link]

package="[Link]" >

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name=".MainActivity"

android:label="@string/app_name" >
<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>

</manifest>

Let's try to run your application. I assume you have connected your actual Android Mobile device
with your computer. To run the app from Android studio, open one of your project's activity files and
click Run icon from the toolbar. Before starting your application, Android studio will display
following window to select an option where you want to run your Android application.
Select your mobile device as an option and then check your mobile device which will display
following screen −

Now just put in some text in the field. Like i put some random name and other information and click
on save button.
Now when you press save button , the text will be saved in the shared preferences. Now press
back button and exit the application. Now open it again and you will see all the text you have written
back in your application.

Android - SIP Protocol Tutorial


SIP stands for (Session Initiation Protocol). It is a protocol that let applications easily set up
outgoing and incoming voice calls, without having to manage sessions, transport-level
communication, or audio record or playback directly.

Applications
Some of the common applications of SIP are.

 Video conferencing

 Instant messaging

Requirements
Here are the requirements for developing a SIP application −

 Android OS must be 2.3 or higher

 You must have a data connection or WIFI

 You must have an SIP account in order to use this service.


SIP Classes
Here is a summary of the classes that are included in the Android SIP API:

[Link] Class and description

1 SipAudioCall

Handles an Internet audio call over SIP

2 SipErrorCode

Defines error codes returned during SIP actions

3 SipManager

Provides APIs for SIP tasks, such as initiating SIP connections, and provides access
to related SIP services

4 SipProfile

Defines a SIP profile, including a SIP account, domain and server information

5 SipSession

Represents a SIP session that is associated with a SIP dialog or a standalone


transaction not within a dialog

Functions of SIP
SIP has following major functions.

 SIP allows for the establishment of user location

 SIP provides a mechanism for call management

 SIP provides feature negotiation, so that all the parties in the call can agree to the features
supported among them
Components of SIP
SIP has two major components which are listed below.

 User Agent Client (UAC)

 User Agent Server (UAS)


UAC
UAC or User Agent Client are those end users who generates requests and send those requests to
the [Link] requests are generated by the client applications running on their systems.

UAS
UAS or User Agent Server are those systems which get the request generated by UAC. The UAS
process those requests and then according to the requests it generates responses accordingly.

SipManager
SipManager is an android API for SIP tasks, such as initiating SIP connections, and provides
access to related SIP services. This class is the starting point for any SIP actions. You can acquire
an instance of it with newInstance().

The SipManager has many functions for managing SIP tasks. Some of the functions are listed
below.

[Link] Class and description

1 close(String localProfileUri)

Closes the specified profile to not make/receive calls

2 getCallId(Intent incomingCallIntent)

Gets the call ID from the specified incoming call broadcast intent

3 isOpened(String localProfileUri)

Checks if the specified profile is opened in the SIP service for making and/or
receiving calls
4 isSipWifiOnly(Context context)

Returns true if SIP is only available on WIFI

5 isRegistered(String localProfileUri)

Checks if the SIP service has successfully registered the profile to the SIP provider
(specified in the profile) for receiving calls

6 isVoipSupported(Context context)

Returns true if the system supports SIP-based VOIP API

7 takeAudioCall(Intent incomingCallIntent, [Link] listener)

Creates a SipAudioCall to take an incoming call

8 unregister(SipProfile localProfile, SipRegistrationListener listener)

Manually unregisters the profile from the corresponding SIP provider for stop
receiving further calls

Android - Spelling Checker Tutorial


The Android platform offers a spelling checker framework that lets you implement and access spell
checking in your application.

In order to use spelling checker , you need to implement SpellCheckerSessionListenerinterface


and override its methods. Its syntax is given below:

public class HelloSpellCheckerActivity extends Activity implements


SpellCheckerSessionListener {

@Override

public void onGetSuggestions(final SuggestionsInfo[] arg0) {

// TODO Auto-generated method stub

}
@Override

public void onGetSentenceSuggestions(SentenceSuggestionsInfo[] arg0) {

// TODO Auto-generated method stub

Next thing you need to do is to create an object of SpellCheckerSession class. This object can be
instantiated by calling newSpellCheckerSession method of TextServicesManager class. This
class handles interaction between application and text services. You need to request system
service to instantiate it. Its syntax is given below −

private SpellCheckerSession mScs;

final TextServicesManager tsm = (TextServicesManager) getSystemService(

Context.TEXT_SERVICES_MANAGER_SERVICE);

mScs = [Link](null, null, this, true);

The last thing you need to do is to call getSuggestions method to get suggestion for any text , you
want. The suggestions will be passed onto the onGetSuggestions method from where you can do
whatever you want.

[Link](new TextInfo([Link]().toString()), 3);

This method takes two parameters. First parameter is the string in the form of Text Info object , and
second parameter is the cookie number used to distinguish suggestions.

Apart from the the methods , there are other methods provided by theSpellCheckerSession class
for better handling suggestions. These methods are listed below:

[Link] Method & description

1 cancel()

Cancel pending and running spell check tasks

2 close()

Finish this session and allow TextServicesManagerService to disconnect the bound


spell checker

3 getSentenceSuggestions(TextInfo[] textInfos, int suggestionsLimit)

Get suggestions from the specified sentences

4 getSpellChecker()

Get the spell checker service info this spell checker session has.

5 isSessionDisconnected()

True if the connection to a text service of this session is disconnected and not alive.

Example
Here is an example demonstrating the use of Spell Checker. It creates a basic spell checking
application that allows you to write text and get suggestions.

To experiment with this example , you can run this on an actual device or in an emulator.

Step Description
s

1 You will use Android studio to create an Android application under a package
[Link]. 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/[Link] file to add necessary code.

3 Modify the res/layout/main to add respective XML components

4 Run the application and choose a running android device and install the application
on it and verify the results

Following is the content of the modified main activity file src/[Link].


package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends Activity implements SpellCheckerSessionListener {

Button b1;

TextView tv1;

EditText ed1;

private SpellCheckerSession mScs;

@Override
protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);

b1=(Button)findViewById([Link]);

tv1=(TextView)findViewById([Link].textView3);

ed1=(EditText)findViewById([Link]);

[Link](new [Link]() {

@Override

public void onClick(View v) {

[Link](getApplicationContext(),
[Link]().toString(),Toast.LENGTH_SHORT).show();

[Link](new TextInfo([Link]().toString()), 3);

});

public void onResume() {

[Link]();

final TextServicesManager tsm = (TextServicesManager)


getSystemService(Context.TEXT_SERVICES_MANAGER_SERVICE);

mScs = [Link](null, null, this, true);

public void onPause() {

[Link]();

if (mScs != null) {

[Link]();

public void onGetSuggestions(final SuggestionsInfo[] arg0) {


final StringBuilder sb = new StringBuilder();

for (int i = 0; i < [Link]; ++i) {

// Returned suggestions are contained in SuggestionsInfo

final int len = arg0[i].getSuggestionsCount();

[Link]('\n');

for (int j = 0; j < len; ++j) {

[Link]("," + arg0[i].getSuggestionAt(j));

[Link](" (" + len + ")");

runOnUiThread(new Runnable() {

public void run() {

[Link]([Link]());

});

@Override

public void onGetSentenceSuggestions(SentenceSuggestionsInfo[] arg0) {

// TODO Auto-generated method stub

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link].menu_main, menu);

return true;

@Override
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 [Link].

int id = [Link]();

//noinspection SimplifiableIfStatement

if (id == [Link].action_settings) {

return true;

return [Link](item);

Following is the modified content of the xml res/layout/[Link].

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView android:text="Spell checker " android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/textview"

android:textSize="35dp"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true" />

<TextView
android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials point"

android:id="@+id/textView"

android:layout_below="@+id/textview"

android:layout_centerHorizontal="true"

android:textColor="#ff7aff24"

android:textSize="35dp" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Suggestions"

android:id="@+id/button"

android:layout_alignParentBottom="true"

android:layout_centerHorizontal="true" />

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/editText"

android:hint="Enter Text"

android:layout_above="@+id/button"

android:layout_marginBottom="56dp"

android:focusable="true"

android:textColorHighlight="#ff7eff15"

android:textColorHint="#ffff25e6"

android:layout_alignRight="@+id/textview"

android:layout_alignEnd="@+id/textview"

android:layout_alignLeft="@+id/textview"

android:layout_alignStart="@+id/textview" />

<ImageView
android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/imageView"

android:src="@drawable/abc"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Suggestions"

android:id="@+id/textView3"

android:textSize="25sp"

android:layout_below="@+id/imageView" />

</RelativeLayout>

Following is the content of the res/values/[Link].

<resources>

<string name="app_name">My Application</string>

<string name="hello_world">Hello world!</string>

<string name="action_settings">Settings</string>

</resources>

Following is the content of [Link] file.

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

<manifest xmlns:android="[Link]

package="[Link]" >

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity

android:name=".MainActivity"

android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>

</manifest>

Android - SQLite Database Tutorial


SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in
with built in SQLite database implementation.

SQLite supports all the relational database features. In order to access this database, you don't
need to establish any kind of connections for it like JDBC,ODBC e.t.c

Database - Package
The main package is [Link] that contains the classes to manage your own
databases

Database - Creation
In order to create a database you just need to call this method openOrCreateDatabase with your
database name and mode as a parameter. It returns an instance of SQLite database which you
have to receive in your own [Link] syntax is given below
SQLiteDatabse mydatabase = openOrCreateDatabase("your database
name",MODE_PRIVATE,null);

Apart from this , there are other functions available in the database package , that does this job.
They are listed below

[Link] Method & Description

1 openDatabase(String path, [Link] factory, int flags,


DatabaseErrorHandler errorHandler)

This method only opens the existing database with the appropriate flag mode. The
common flags mode could be OPEN_READWRITE OPEN_READONLY

2 openDatabase(String path, [Link] factory, int flags)

It is similar to the above method as it also opens the existing database but it does not
define any handler to handle the errors of databases

3 openOrCreateDatabase(String path, [Link] factory)

It not only opens but create the database if it not exists. This method is equivalent to
openDatabase method

4 openOrCreateDatabase(File file, [Link] factory)

This method is similar to above method but it takes the File object as a path rather
then a string. It is equivalent to [Link]()

Database - Insertion
we can create table or insert data into table using execSQL method defined in SQLiteDatabase
class. Its syntax is given below

[Link]("CREATE TABLE IF NOT EXISTS TutorialsPoint(Username


VARCHAR,Password VARCHAR);");
[Link]("INSERT INTO TutorialsPoint VALUES('admin','admin');");
This will insert some values into our table in our database. Another method that also does the same
job but take some additional parameter is given below

[Link] Method & Description

1 execSQL(String sql, Object[] bindArgs)

This method not only insert data , but also used to update or modify already existing
data in database using bind arguments

Database - Fetching
We can retrieve anything from database using an object of the Cursor class. We will call a method
of this class called rawQuery and it will return a resultset with the cursor pointing to the table. We
can move the cursor forward and retrieve the data.

Cursor resultSet = [Link]("Select * from TutorialsPoint",null);


[Link]();
String username = [Link](1);
String password = [Link](2);

There are other functions available in the Cursor class that allows us to effectively retrieve the data.
That includes

[Link] Method & Description

1 getColumnCount()This method return the total number of columns of the table.

2 getColumnIndex(String columnName)

This method returns the index number of a column by specifying the name of the
column

3 getColumnName(int columnIndex)

This method returns the name of the column by specifying the index of the column
4 getColumnNames()

This method returns the array of all the column names of the table.

5 getCount()

This method returns the total number of rows in the cursor

6 getPosition()

This method returns the current position of the cursor in the table

7 isClosed()

This method returns true if the cursor is closed and return false otherwise

Database - Helper class


For managing all the operations related to the database , an helper class has been given and is
called SQLiteOpenHelper. It automatically manages the creation and update of the database. Its
syntax is given below

public class DBHelper extends SQLiteOpenHelper {

public DBHelper(){

super(context,DATABASE_NAME,null,1);

public void onCreate(SQLiteDatabase db) {}

public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {}

Example
Here is an example demonstrating the use of SQLite Database. It creates a basic contacts
applications that allows insertion , deletion and modification of contacts.

To experiment with this example , you need to run this on an actual device on which camera is
supported.

s
Step Description
s

1 You will use Android studio to create an Android application under a package
[Link]. 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/[Link] file to get references of all the XML components and
populate the contacts on listView.

3 Create new src/[Link] that will manage the database work

4 Create a new Activity as [Link] that will display the contact on the
screen

5 Modify the res/layout/activity_main to add respective XML components

6 Modify the res/layout/activity_display_contact.xml to add respective XML components

7 Modify the res/values/[Link] to add necessary string components

8 Modify the res/menu/display_contact.xml to add necessary menu components

9 Create a new menu as res/menu/[Link] to add the insert contact option

10 Run the application and choose a running android device and install the application
on it and verify the results.

Following is the content of the modified [Link].

package [Link];

import [Link];
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends ActionBarActivity {

public final static String EXTRA_MESSAGE = "MESSAGE";

private ListView obj;

DBHelper mydb;

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);

mydb = new DBHelper(this);

ArrayList array_list = [Link]();

ArrayAdapter arrayAdapter=new
ArrayAdapter(this,[Link].simple_list_item_1, array_list);

obj = (ListView)findViewById([Link].listView1);
[Link](arrayAdapter);

[Link](new OnItemClickListener(){

@Override

public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {

// TODO Auto-generated method stub

int id_To_Search = arg2 + 1;

Bundle dataBundle = new Bundle();

[Link]("id", id_To_Search);

Intent intent = new Intent(getApplicationContext(),[Link]);

[Link](dataBundle);

startActivity(intent);

});

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link].menu_main, menu);

return true;

@Override

public boolean onOptionsItemSelected(MenuItem item){

[Link](item);

switch([Link]())

case [Link].item1:Bundle dataBundle = new Bundle();

[Link]("id", 0);
Intent intent = new Intent(getApplicationContext(),[Link]);

[Link](dataBundle);

startActivity(intent);

return true;

default:

return [Link](item);

public boolean onKeyDown(int keycode, KeyEvent event) {

if (keycode == KeyEvent.KEYCODE_BACK) {

moveTaskToBack(true);

return [Link](keycode, event);

Following is the modified content of display contact activity [Link]

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];
import [Link];

import [Link];

import [Link];

public class DisplayContact extends Activity {

int from_Where_I_Am_Coming = 0;

private DBHelper mydb ;

TextView name ;

TextView phone;

TextView email;

TextView street;

TextView place;

int id_To_Update = 0;

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_display_contact);

name = (TextView) findViewById([Link]);

phone = (TextView) findViewById([Link]);

email = (TextView) findViewById([Link]);

street = (TextView) findViewById([Link]);

place = (TextView) findViewById([Link]);

mydb = new DBHelper(this);

Bundle extras = getIntent().getExtras();

if(extras !=null)

int Value = [Link]("id");


if(Value>0){

//means this is the view part not the add contact part.

Cursor rs = [Link](Value);

id_To_Update = Value;

[Link]();

String nam =
[Link]([Link](DBHelper.CONTACTS_COLUMN_NAME));

String phon =
[Link]([Link](DBHelper.CONTACTS_COLUMN_PHONE));

String emai =
[Link]([Link](DBHelper.CONTACTS_COLUMN_EMAIL));

String stree =
[Link]([Link](DBHelper.CONTACTS_COLUMN_STREET));

String plac =
[Link]([Link](DBHelper.CONTACTS_COLUMN_CITY));

if (![Link]())

[Link]();

Button b = (Button)findViewById([Link].button1);

[Link]([Link]);

[Link]((CharSequence)nam);

[Link](false);

[Link](false);

[Link]((CharSequence)phon);

[Link](false);

[Link](false);

[Link]((CharSequence)emai);

[Link](false);

[Link](false);
[Link]((CharSequence)stree);

[Link](false);

[Link](false);

[Link]((CharSequence)plac);

[Link](false);

[Link](false);

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

Bundle extras = getIntent().getExtras();

if(extras !=null)

int Value = [Link]("id");

if(Value>0){

getMenuInflater().inflate([Link].display_contact, menu);

else{

getMenuInflater().inflate([Link], menu);

return true;

public boolean onOptionsItemSelected(MenuItem item)

{
[Link](item);

switch([Link]())

case [Link].Edit_Contact:

Button b = (Button)findViewById([Link].button1);

[Link]([Link]);

[Link](true);

[Link](true);

[Link](true);

[Link](true);

[Link](true);

[Link](true);

[Link](true);

[Link](true);

[Link](true);

[Link](true);

[Link](true);

[Link](true);

[Link](true);

[Link](true);

[Link](true);

return true;

case [Link].Delete_Contact:

[Link] builder = new [Link](this);

[Link]([Link])

.setPositiveButton([Link], new [Link]() {

public void onClick(DialogInterface dialog, int id) {


[Link](id_To_Update);

[Link](getApplicationContext(), "Deleted Successfully",


Toast.LENGTH_SHORT).show();

Intent intent = new Intent(getApplicationContext(),[Link]);

startActivity(intent);

})

.setNegativeButton([Link], new [Link]() {

public void onClick(DialogInterface dialog, int id) {

// User cancelled the dialog

});

AlertDialog d = [Link]();

[Link]("Are you sure");

[Link]();

return true;

default:

return [Link](item);

public void run(View view)

Bundle extras = getIntent().getExtras();

if(extras !=null)

int Value = [Link]("id");

if(Value>0){

if([Link](id_To_Update,[Link]().toString(),
[Link]().toString(), [Link]().toString(), [Link]().toString(),
[Link]().toString())){
[Link](getApplicationContext(), "Updated",
Toast.LENGTH_SHORT).show();

Intent intent = new Intent(getApplicationContext(),[Link]);

startActivity(intent);

else{

[Link](getApplicationContext(), "not Updated",


Toast.LENGTH_SHORT).show();

else{

if([Link]([Link]().toString(),
[Link]().toString(), [Link]().toString(), [Link]().toString(),
[Link]().toString())){

[Link](getApplicationContext(), "done",
Toast.LENGTH_SHORT).show();

else{

[Link](getApplicationContext(), "not done",


Toast.LENGTH_SHORT).show();

Intent intent = new Intent(getApplicationContext(),[Link]);

startActivity(intent);

Following is the content of Database class [Link]

package [Link];

import [Link];

import [Link];

import [Link];
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class DBHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "[Link]";

public static final String CONTACTS_TABLE_NAME = "contacts";

public static final String CONTACTS_COLUMN_ID = "id";

public static final String CONTACTS_COLUMN_NAME = "name";

public static final String CONTACTS_COLUMN_EMAIL = "email";

public static final String CONTACTS_COLUMN_STREET = "street";

public static final String CONTACTS_COLUMN_CITY = "place";

public static final String CONTACTS_COLUMN_PHONE = "phone";

private HashMap hp;

public DBHelper(Context context)

super(context, DATABASE_NAME , null, 1);

@Override

public void onCreate(SQLiteDatabase db) {

// TODO Auto-generated method stub

[Link](

"create table contacts " +

"(id integer primary key, name text,phone text,email text, street text,place
text)"

);

}
@Override

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

// TODO Auto-generated method stub

[Link]("DROP TABLE IF EXISTS contacts");

onCreate(db);

public boolean insertContact (String name, String phone, String email, String
street,String place)

SQLiteDatabase db = [Link]();

ContentValues contentValues = new ContentValues();

[Link]("name", name);

[Link]("phone", phone);

[Link]("email", email);

[Link]("street", street);

[Link]("place", place);

[Link]("contacts", null, contentValues);

return true;

public Cursor getData(int id){

SQLiteDatabase db = [Link]();

Cursor res = [Link]( "select * from contacts where id="+id+"", null );

return res;

public int numberOfRows(){

SQLiteDatabase db = [Link]();

int numRows = (int) [Link](db, CONTACTS_TABLE_NAME);

return numRows;

}
public boolean updateContact (Integer id, String name, String phone, String email,
String street,String place)

SQLiteDatabase db = [Link]();

ContentValues contentValues = new ContentValues();

[Link]("name", name);

[Link]("phone", phone);

[Link]("email", email);

[Link]("street", street);

[Link]("place", place);

[Link]("contacts", contentValues, "id = ? ", new String[]


{ [Link](id) } );

return true;

public Integer deleteContact (Integer id)

SQLiteDatabase db = [Link]();

return [Link]("contacts",

"id = ? ",

new String[] { [Link](id) });

public ArrayList<String> getAllCotacts()

ArrayList<String> array_list = new ArrayList<String>();

//hp = new HashMap();

SQLiteDatabase db = [Link]();

Cursor res = [Link]( "select * from contacts", null );

[Link]();
while([Link]() == false){

array_list.add([Link]([Link](CONTACTS_COLUMN_NAME)));

[Link]();

return array_list;

Following is the content of the res/layout/activity_main.xml

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/textView"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true"

android:textSize="30dp"

android:text="Data Base" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials Point"

android:id="@+id/textView2"

android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"

android:textSize="35dp"

android:textColor="#ff16ff01" />

<ImageView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/imageView"

android:layout_below="@+id/textView2"

android:layout_centerHorizontal="true"

android:src="@drawable/logo"/>

<ScrollView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/scrollView"

android:layout_below="@+id/imageView"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:layout_alignParentBottom="true"

android:layout_alignParentRight="true"

android:layout_alignParentEnd="true">

<ListView

android:id="@+id/listView1"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_centerHorizontal="true"

android:layout_centerVertical="true" >

</ListView>

</ScrollView>

</RelativeLayout>;
Following is the content of the res/layout/activity_display_contact.xml

<ScrollView xmlns:android="[Link]

xmlns:tools="[Link]

android:id="@+id/scrollView1"

android:layout_width="match_parent"

android:layout_height="wrap_content"

tools:context=".DisplayContact" >

<RelativeLayout

android:layout_width="match_parent"

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">

<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>

<EditText

android:id="@+id/editTextEmail"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignLeft="@+id/editTextStreet"
android:layout_below="@+id/editTextStreet"

android:layout_marginTop="22dp"

android:ems="10"

android:inputType="textEmailAddress" />

<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_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignLeft="@+id/editTextCity"

android:layout_alignParentBottom="true"

android:layout_marginBottom="28dp"

android:onClick="run"

android:text="@string/save" />

<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:layout_alignLeft="@+id/textView1"

android:text="@string/phone"

android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView

android:id="@+id/textView4"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_above="@+id/editTextEmail"

android:layout_alignLeft="@+id/textView5"

android:text="@string/street"

android:textAppearance="?android:attr/textAppearanceMedium" />

<EditText

android:id="@+id/editTextCity"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignRight="@+id/editTextName"

android:layout_below="@+id/editTextEmail"

android:layout_marginTop="30dp"

android:ems="10"

android:inputType="text" />

<TextView

android:id="@+id/textView3"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignBaseline="@+id/editTextCity"
android:layout_alignBottom="@+id/editTextCity"

android:layout_alignParentLeft="true"

android:layout_toLeftOf="@+id/editTextEmail"

android:text="@string/country"

android:textAppearance="?android:attr/textAppearanceMedium" />

<EditText

android:id="@+id/editTextStreet"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignLeft="@+id/editTextName"

android:layout_below="@+id/editTextPhone"

android:ems="10"

android:inputType="text" >

<requestFocus />

</EditText>

<EditText

android:id="@+id/editTextPhone"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignLeft="@+id/editTextStreet"

android:layout_below="@+id/editTextName"

android:ems="10"

android:inputType="phone|text" />

</RelativeLayout>

</ScrollView>

Following is the content of the res/value/[Link]

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

<resources>
<string name="app_name">Address Book</string>

<string name="action_settings">Settings</string>

<string name="hello_world">Hello world!</string>

<string name="Add_New">Add New</string>

<string name="edit">Edit Contact</string>

<string name="delete">Delete Contact</string>

<string name="title_activity_display_contact">DisplayContact</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>

<string name="deleteContact">Are you sure, you want to delete it.</string>

<string name="yes">Yes</string>

<string name="no">No</string>

</resources>

Following is the content of the res/menu/main_menu.xml

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

<menu xmlns:android="[Link] >

<item android:id="@+id/item1"

android:icon="@drawable/add"

android:title="@string/Add_New" >

</item>

</menu>

Following is the content of the res/menu/display_contact.xml

<menu xmlns:android="[Link] >

<item

android:id="@+id/Edit_Contact"
android:orderInCategory="100"

android:title="@string/edit"/>

<item

android:id="@+id/Delete_Contact"

android:orderInCategory="100"

android:title="@string/delete"/>

</menu>

This is the defualt [Link] of this project

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

<manifest xmlns:android="[Link]

package="[Link]" >

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name=".MainActivity"

android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

<activity android:name=".DisplayContact"/>
</application>

</manifest>

Let's try to run your application. I assume you have connected your actual Android Mobile device
with your computer. To run the app from Android studio , open one of your project's activity files and
click Run icon from the tool bar. Before starting your application,Android studio will display
following window to select an option where you want to run your Android application.

Select your mobile device as an option and then check your mobile device which will display
following screen −
Now open your optional menu, it will show as below image: Optional menu appears different
places on different versions
Click on the add button of the menu screen to add a new contact. It will display the following screen

It will display the following fields. Please enter the required information and click on save contact. It
will bring you back to main screen.
Now our contact john has been added. Tap on this to edit it or delete [Link] will bring you to the
following screen. Now select menu from your mobile. And there will be two options there.
Select delete contact and an dialog box would appear asking you about deleting this contact. It
would be like this
Select Yes from the above screen that appears and a notification will appear that the contact has
been deleted successfully. It would appear like this
In order to see that where is your database is created. Open your android studio, connect your
mobile. Go tools/android/android device monitor. Now browse the file explorer tab. Now browse
this folder/data/data/<[Link]>/databases<database-name>.

Android - Testing Tutorial


The Android framework includes an integrated testing framework that helps you test all aspects of
your application and the SDK tools include tools for setting up and running test applications.
Whether you are working in Eclipse with ADT or working from the command line, the SDK tools
help you set up and run your tests within an emulator or the device you are targeting.
Test Structure
Android's build and test tools assume that test projects are organized into a standard structure of
tests, test case classes, test packages, and test projects.

Testing Tools in android


There are many tools that can be used for testing android applications. Some are official like
Junit,Monkey and some are third party tools that can be used to test android applications. In this
chapter we are going to explain these two tools to test android applications.

 JUnit

 Monkey
JUnit
You can use the JUnit TestCase class to do unit testing on a class that doesn't call Android APIs.
TestCase is also the base class for AndroidTestCase, which you can use to test Android-dependent
objects. Besides providing the JUnit framework, AndroidTestCase offers Android-specific setup,
teardown, and helper methods.

In order to use TestCase, extend your class with TestCase class and implement a method call
setUp(). Its syntax is given below −

public class MathTest extends TestCase {

protected double fValue1;

protected double fValue2;

protected void setUp() {

fValue1= 2.0;

fValue2= 3.0;

For each test implement a method which interacts with the fixture. Verify the expected results with
assertions specified by calling assertTrue(String, boolean) with a boolean.

public void testAdd() {

double result= fValue1 + fValue2;

assertTrue(result == 5.0);

The assert methods compare values you expect from a test to the actual results and throw an
exception if the comparison fails.

Once the methods are defined you can run them. Its syntax is given below −

TestCase test= new MathTest("testAdd");

[Link]();
Monkey
The UI/Application Exerciser Monkey, usually called "monkey", is a command-line tool that sends
pseudo-random streams of keystrokes, touches, and gestures to a device. You run it with the
Android Debug Bridge (adb) tool.

You use it to stress-test your application and report back errors that are encountered. You can
repeat a stream of events by running the tool each time with the same random number seed.

Monkey features
Monkey has many features, but it can be all be summed up to these four categories.

 Basic configuration options

 Operational constraints

 Event types and frequencies

 Debugging options
Monkey Usage
In order to use monkey, open up a command prompt and just navigate to the following directory.

android ->sdk ->platform-tools

Once inside the directory, attach your device with the PC , and run the following command.

adb shell monkey -p [Link] -v 500

This command can be broken down into these steps.

 adb - Android Debug Bridge. A tool used to connect and sends commands to your Android
phone from a desktop or laptop computer.

 shell - shell is just an interface on the device that translates our commands to system
commands.

 monkey - monkey is the testing tool.

 v - v stands for verbose method.

 500- it is the frequency conut or the number of events to be sent for testing.

This is also shown in the figure −


In the above command, you run the monkey tool on the default android UI application. Now in order
to run it to your application , here what you have to do.

finally you will get finish as shown bellow

This has also been shown in the figure below. By typing this command , you are actually generating
500 random events for testing.
Example
The below example demonstrates the use of Testing. It crates a basic application which can be
used for monkey.

To experiment with this example , you need to run this on an actual device and then follow the
monkey steps explained in the beginning.

Step Description
s

1 You will useAndroid studio to create an Android application under a package


[Link]. 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/[Link] file to add Activity code.

3 Modify layouta XML file res/layout/activity_main.xml add any GUI component if


required.

4 Create src/[Link] file to add Activity code.

5 Modify layout XML file res/layout/[Link] add any GUI component if required.

6 Run the application and choose a running android device and install the application
on it and verify the results.

Here is the content of [Link].

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends ActionBarActivity {

Button b1;

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);

b1=(Button)findViewById([Link]);

}
public void button(View v){

Intent in =new Intent([Link],[Link]);

startActivity(in);

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link].menu_main, menu);

return true;

@Override

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 [Link].

int id = [Link]();

//noinspection SimplifiableIfStatement

if (id == [Link].action_settings) {

return true;

return [Link](item);

Here is the content of [Link].

package [Link];

import [Link];
import [Link];

import [Link];

import [Link];

import [Link];

/**

* Created by Sairamkrishna on 4/10/2015.

*/

public class second extends Activity{

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link]);

Button b1=(Button)findViewById([Link].button2);

[Link](new [Link]() {

@Override

public void onClick(View v) {

[Link]([Link],"Thanks",Toast.LENGTH_SHORT).show();

});

Here is the content of activity_main.xml.

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="UI Animator Viewer"

android:id="@+id/textView"

android:textSize="25sp"

android:layout_centerHorizontal="true" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials point"

android:id="@+id/textView2"

android:layout_below="@+id/textView"

android:layout_alignRight="@+id/textView"

android:layout_alignEnd="@+id/textView"

android:textColor="#ff36ff15"

android:textIsSelectable="false"

android:textSize="35dp" />

<ImageView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/imageView"

android:src="@drawable/logo"

android:layout_below="@+id/textView2"

android:layout_centerHorizontal="true" />

<Button

android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:text="Button"

android:onClick="button"

android:id="@+id/button"

android:layout_below="@+id/imageView"

android:layout_centerHorizontal="true"

android:layout_marginTop="100dp" />

</RelativeLayout>

Here is the content of [Link]

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

<RelativeLayout xmlns:android="[Link]

android:layout_width="match_parent" android:layout_height="match_parent">

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="button"

android:id="@+id/button2"

android:layout_centerVertical="true"

android:layout_centerHorizontal="true" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials point "

android:id="@+id/textView3"

android:textColor="#ff3aff22"

android:textSize="35dp"

android:layout_above="@+id/button2"

android:layout_centerHorizontal="true"

android:layout_marginBottom="90dp" />
</RelativeLayout>

Here is the content of [Link].

<resources>

<string name="app_name">My Application</string>

<string name="hello_world">Hello world!</string>

<string name="action_settings">Settings</string>

</resources>

Here is the content of [Link].

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

<manifest xmlns:android="[Link]

package="[Link]" >

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name=".MainActivity"

android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

<activity android:name=".second"></activity>
</application>

</manifest>

Android - Text To Speech Tutorial


Android allows you convert your text into voice. Not only you can convert it but it also allows you to
speak text in variety of different languages.

Android provides TextToSpeech class for this purpose. In order to use this class, you need to
instantiate an object of this class and also specify the initListnere. Its syntax is given below:

private EditText write;

ttobj=new TextToSpeech(getApplicationContext(), new [Link]() {

@Override

public void onInit(int status) {

);

In this listener, you have to specify the properties for TextToSpeech object , such as its
language ,pitch e.t.c. Language can be set by calling setLanguage() method. Its syntax is given
below −

[Link]([Link]);

The method setLanguage takes an Locale object as parameter. The list of some of the locales
available are given below −

[Link] Locale

1 US

2 CANADA_FRENCH
3 GERMANY

4 ITALY

5 JAPAN

6 CHINA

Once you have set the language, you can call speak method of the class to speak the text. Its
syntax is given below −

[Link](toSpeak, TextToSpeech.QUEUE_FLUSH, null);

Apart from the speak method, there are some other methods available in the TextToSpeech class.
They are listed below:

[Link] Method & description

1 addSpeech(String text, String filename)

This method adds a mapping between a string of text and a sound file.

2 getLanguage()

This method returns a Locale instance describing the language.

3 isSpeaking()

This method checks whether the TextToSpeech engine is busy speaking.

4 setPitch(float pitch)

This method sets the speech pitch for the TextToSpeech engine.

5 setSpeechRate(float speechRate)
This method sets the speech rate.

6 shutdown()

This method releases the resources used by the TextToSpeech engine.

7 stop()

This method stop the speak.

Example
The below example demonstrates the use of TextToSpeech class. It crates a basic application that
allows you to set write text and speak it.

To experiment with this example , you need to run this on an actual device.

Step Description
s

1 You will use Android studio to create an Android application under a package
[Link]. 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/[Link] file to add TextToSpeech code.

3 Modify layout XML file res/layout/activity_main.xml add any GUI component if


required.

4 Run the application and choose a running android device and install the application
on it and verify the results.

Here is the content of src/[Link].

package [Link];
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends Activity {

TextToSpeech t1;

EditText ed1;

Button b1;

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);

ed1=(EditText)findViewById([Link]);

b1=(Button)findViewById([Link]);
t1=new TextToSpeech(getApplicationContext(), new [Link]() {

@Override

public void onInit(int status) {

if(status != [Link]) {

[Link]([Link]);

});

[Link](new [Link]() {

@Override

public void onClick(View v) {

String toSpeak = [Link]().toString();

[Link](getApplicationContext(),
toSpeak,Toast.LENGTH_SHORT).show();

[Link](toSpeak, TextToSpeech.QUEUE_FLUSH, null);

});

public void onPause(){

if(t1 !=null){

[Link]();

[Link]();

[Link]();

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link].menu_main, menu);
return true;

@Override

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 [Link].

int id = [Link]();

//noinspection SimplifiableIfStatement

if (id == [Link].action_settings) {

return true;

return [Link](item);

Here is the content of activity_main.xml

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"

tools:context=".MainActivity"

android:transitionGroup="true">

<TextView android:text="Text to Speech" android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/textview"
android:textSize="35dp"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials point"

android:id="@+id/textView"

android:layout_below="@+id/textview"

android:layout_centerHorizontal="true"

android:textColor="#ff7aff24"

android:textSize="35dp" />

<ImageView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/imageView"

android:src="@drawable/abc"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true"

android:theme="@style/[Link]" />

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/editText"

android:layout_below="@+id/imageView"

android:layout_marginTop="46dp"

android:hint="Enter Text"

android:layout_alignParentRight="true"

android:layout_alignParentEnd="true"

android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"

android:textColor="#ff7aff10"

android:textColorHint="#ffff23d1" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Text to Speech"

android:id="@+id/button"

android:layout_below="@+id/editText"

android:layout_centerHorizontal="true"

android:layout_marginTop="46dp" />

</RelativeLayout>

Here is the content of [Link].

<resources>

<string name="app_name">My Application</string>

<string name="hello_world">Hello world!</string>

<string name="action_settings">Settings</string>

</resources>

Here is the content of [Link]

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

<manifest xmlns:android="[Link]

package="[Link]" >

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity
android:name=".MainActivity"

android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" >

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>

</manifest>

Android - TextureView Tutorial


If you want to display a live video stream or any content stream such as video or an OpenGL
scene, you can use TextureView provided by android in order to do that.

In order to use TextureView, all you need to do is get its [Link] SurfaceTexture can
then be used to render content. In order to do this, you just need to do instantiate an object of this
class and implement SurfaceTextureListener interface. Its syntax is given below:

private TextureView myTexture;

public class MainActivity extends Activity implements SurfaceTextureListener{

protected void onCreate(Bundle savedInstanceState) {

myTexture = new TextureView(this);

[Link](this);

setContentView(myTexture);

After that, what you need to do is to override its methods. The methods are listed as follows −

@Override
public void onSurfaceTextureAvailable(SurfaceTexture arg0, int arg1, int arg2) {

@Override

public boolean onSurfaceTextureDestroyed(SurfaceTexture arg0) {

@Override

public void onSurfaceTextureSizeChanged(SurfaceTexture arg0, int arg1,int arg2) {

@Override

public void onSurfaceTextureUpdated(SurfaceTexture arg0) {

Any view that is displayed in the texture view can be rotated and its alpha property can be adjusted
by using setAlpha and setRotation methods. Its syntax is given below −

[Link](1.0f);

[Link](90.0f);

Apart from these methods, there are other methods available in TextureView class. They are listed
below −

[Link] Method & description

1 getSurfaceTexture()

This method returns the SurfaceTexture used by this view.

2 getBitmap(int width, int height)

This method returns Returns a Bitmap representation of the content of the


associated surface texture.

3 getTransform(Matrix transform)

This method returns the transform associated with this texture view.
4 isOpaque()

This method indicates whether this View is opaque.

5 lockCanvas()

This method start editing the pixels in the surface

6 setOpaque(boolean opaque)

This method indicates whether the content of this TextureView is opaque.

7 setTransform(Matrix transform)

This method sets the transform to associate with this texture view.

8 unlockCanvasAndPost(Canvas canvas)

This method finish editing pixels in the surface.

Example
The below example demonstrates the use of TextureView class. It crates a basic application that
allows you to view camera inside a texture view and change its angle , orientation e.t.c.

To experiment with this example , you need to run this on an actual device on which camera is
present.

Step Description
s

1 You will use android studio IDE to create an Android application and name it as
TextureView under a package [Link]. 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/[Link] file to add Activity code.


3 Modify layout XML file res/layout/activity_main.xml add any GUI component if
required.

5 Run the application and choose a running android device and install the application
on it and verify the results.

Here is the content of src/[Link]/[Link].

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends Activity implements SurfaceTextureListener {

private TextureView myTexture;

private Camera mCamera;

@SuppressLint("NewApi")

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);
setContentView([Link].activity_main);

myTexture = new TextureView(this);

[Link](this);

setContentView(myTexture);

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link], menu);

return true;

@SuppressLint("NewApi")

@Override

public void onSurfaceTextureAvailable(SurfaceTexture arg0, int arg1, int arg2) {

mCamera = [Link]();

[Link] previewSize = [Link]().getPreviewSize();

[Link](new [Link](

[Link], [Link], [Link]));

try {

[Link](arg0);

catch (IOException t) {

[Link]();

[Link](1.0f);

[Link](90.0f);

}
@Override

public boolean onSurfaceTextureDestroyed(SurfaceTexture arg0) {

[Link]();

[Link]();

return true;

@Override

public void onSurfaceTextureSizeChanged(SurfaceTexture arg0, int arg1,

int arg2) {

// TODO Auto-generated method stub

@Override

public void onSurfaceTextureUpdated(SurfaceTexture arg0) {

// TODO Auto-generated method stub

Here is the content of activity_main.xml

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link]

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" >

<TextureView

android:id="@+id/textureView1"

android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true" />

</RelativeLayout>

Here is the default content of [Link]

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

<manifest xmlns:android="[Link]

package="[Link]"

android:versionCode="1"

android:versionName="1.0" >

<uses-permission android:name="[Link]"/>

<application

android:allowBackup="true"

android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name="[Link]"

android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>

</manifest>
Android - WebView Tutorial
WebView is a view that display web pages inside your application. You can also specify HTML
string and can show it inside your application using WebView. WebView makes turns your
application to a web application.

In order to add WebView to your application, you have to add <WebView> element to your xml
layout file. Its syntax is as follows −

<WebView xmlns:android="[Link]

android:id="@+id/webview"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

/>

In order to use it, you have to get a reference of this view in Java file. To get a reference, create an
object of the class WebView. Its syntax is −

WebView browser = (WebView) findViewById([Link]);

In order to load a web url into the WebView, you need to call a method loadUrl(String url) of the
WebView class, specifying the required url. Its syntax is:

[Link]("[Link]

Apart from just loading url, you can have more control over your WebView by using the methods
defined in WebView class. They are listed as follows −

[Link] Method & Description

1 canGoBack()

This method specifies the WebView has a back history item.

2 canGoForward()

This method specifies the WebView has a forward history item.


3 clearHistory()

This method will clear the WebView forward and backward history.

4 destroy()

This method destroy the internal state of WebView.

5 findAllAsync(String find)

This method find all instances of string and highlight them.

6 getProgress()

This method gets the progress of the current page.

7 getTitle()

This method return the title of the current page.

8 getUrl()

This method return the url of the current page.

If you click on any link inside the webpage of the WebView , that page will not be loaded inside your
WebView. In order to do that you need to extend your class fromWebViewClient and override its
method. Its syntax is −

private class MyBrowser extends WebViewClient {

@Override

public boolean shouldOverrideUrlLoading(WebView view, String url) {

[Link](url);

return true;

}
Example
Here is an example demonstrating the use of WebView Layout. It creates a basic web application
that will ask you to specify a url and will load this url website in the WebView.

To experiment with this example, you need to run this on an actual device on which internet is
running.

Step Description
s

1 You will use Android studio to create an Android application under a package
[Link]. 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/[Link] file to add WebView code.

3 Modify the res/layout/activity_main to add respective XML components

4 Modify the [Link] to add the necessary permissions

5 Run the application and choose a running android device and install the application
on it and verify the results.

Following is the content of the modified main activity file src/[Link].

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends Activity {

Button b1;

EditText ed1;

private WebView wv1;

@Override

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);

b1=(Button)findViewById([Link]);

ed1=(EditText)findViewById([Link]);

wv1=(WebView)findViewById([Link]);

[Link](new MyBrowser());

[Link](new [Link]() {

@Override

public void onClick(View v) {

String url = [Link]().toString();


[Link]().setLoadsImagesAutomatically(true);

[Link]().setJavaScriptEnabled(true);

[Link](View.SCROLLBARS_INSIDE_OVERLAY);

[Link](url);

});

private class MyBrowser extends WebViewClient {

@Override

public boolean shouldOverrideUrlLoading(WebView view, String url) {

[Link](url);

return true;

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link].menu_main, menu);

return true;

@Override

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 [Link].

int id = [Link]();

//noinspection SimplifiableIfStatement

if (id == [Link].action_settings) {
return true;

return [Link](item);

Following is the modified content of the xml res/layout/activity_main.xml.

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView android:text="WebView" android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/textview"

android:textSize="35dp"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials point"

android:id="@+id/textView"

android:layout_below="@+id/textview"

android:layout_centerHorizontal="true"

android:textColor="#ff7aff24"

android:textSize="35dp" />
<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/editText"

android:hint="Enter Text"

android:focusable="true"

android:textColorHighlight="#ff7eff15"

android:textColorHint="#ffff25e6"

android:layout_marginTop="46dp"

android:layout_below="@+id/imageView"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:layout_alignRight="@+id/imageView"

android:layout_alignEnd="@+id/imageView" />

<ImageView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/imageView"

android:src="@drawable/abc"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Enter"

android:id="@+id/button"

android:layout_alignTop="@+id/editText"

android:layout_toRightOf="@+id/imageView"

android:layout_toEndOf="@+id/imageView" />

<WebView
android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/webView"

android:layout_below="@+id/button"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:layout_alignParentRight="true"

android:layout_alignParentEnd="true"

android:layout_alignParentBottom="true" />

</RelativeLayout>

Following is the content of the res/values/[Link].

<resources>

<string name="app_name">My Application</string>

<string name="hello_world">Hello world!</string>

<string name="action_settings">Settings</string>

</resources>

Following is the content of [Link] file.

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

<manifest xmlns:android="[Link]

package="[Link]" >

<uses-permission android:name="[Link]" />

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name=".MainActivity"

android:label="@string/app_name" >
<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>

</manifest>

Android - Wi-Fi Tutorial


Android allows applications to access to view the access the state of the wireless connections at
very low level. Application can access almost all the information of a wifi connection.

The information that an application can access includes connected network's link speed,IP address,
negotiation state, other networks information. Applications can also scan, add, save, terminate and
initiate Wi-Fi connections.

Android provides WifiManager API to manage all aspects of WIFI connectivity. We can instantiate
this class by calling getSystemService method. Its syntax is given below −

WifiManager mainWifiObj;

mainWifiObj = (WifiManager) getSystemService(Context.WIFI_SERVICE);

In order to scan a list of wireless networks, you also need to register your BroadcastReceiver. It can
be registered using registerReceiver method with argument of your receiver class object. Its
syntax is given below −

class WifiScanReceiver extends BroadcastReceiver {

public void onReceive(Context c, Intent intent) {

WifiScanReceiver wifiReciever = new WifiScanReceiver();


registerReceiver(wifiReciever, new
IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

The wifi scan can be start by calling the startScan method of the WifiManager class. This method
returns a list of ScanResult objects. You can access any object by calling the getmethod of list. Its
syntax is given below −

List<ScanResult> wifiScanList = [Link]();

String data = [Link](0).toString();

Apart from just Scanning, you can have more control over your WIFI by using the methods defined
in WifiManager class. They are listed as follows −

[Link] Method & Description

1 addNetwork(WifiConfiguration config)

This method add a new network description to the set of configured networks.

2 createWifiLock(String tag)

This method creates a new WifiLock.

3 disconnect()

This method disassociate from the currently active access point.

4 enableNetwork(int netId, boolean disableOthers)

This method allow a previously configured network to be associated with.

5 getWifiState()

This method gets the Wi-Fi enabled state

6 isWifiEnabled()

This method return whether Wi-Fi is enabled or disabled.


7 setWifiEnabled(boolean enabled)

This method enable or disable Wi-Fi.

8 updateNetwork(WifiConfiguration config)

This method update the network description of an existing configured network.

Example
Here is an example demonstrating the use of WIFI. It creates a basic application that scans a list of
wireless networks and populate them in a list view.

To experiment with this example, you need to run this on an actual device on which wifi is turned
on.

Step Description
s

1 You will use Android studio to create an Android application under a package
[Link]. 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/[Link] file to add WebView code.

3 Modify the res/layout/activity_main to add respective XML components

4 Modify the [Link] to add the necessary permissions

5 Run the application and choose a running android device and install the application
on it and verify the results.

Following is the content of the modified main activity file src/[Link].

package [Link];
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends Activity {

ListView lv;

WifiManager wifi;

String wifis[];

WifiScanReceiver wifiReciever;

@Override

protected void onCreate(Bundle savedInstanceState) {


[Link](savedInstanceState);

setContentView([Link].activity_main);

lv=(ListView)findViewById([Link]);

wifi=(WifiManager)getSystemService(Context.WIFI_SERVICE);

wifiReciever = new WifiScanReceiver();

[Link]();

protected void onPause() {

unregisterReceiver(wifiReciever);

[Link]();

protected void onResume() {

registerReceiver(wifiReciever, new
IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

[Link]();

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link].menu_main, menu);

return true;

@Override

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 [Link].


int id = [Link]();

//noinspection SimplifiableIfStatement

if (id == [Link].action_settings) {

return true;

return [Link](item);

private class WifiScanReceiver extends BroadcastReceiver{

public void onReceive(Context c, Intent intent) {

List<ScanResult> wifiScanList = [Link]();

wifis = new String[[Link]()];

for(int i = 0; i < [Link](); i++){

wifis[i] = (([Link](i)).toString());

[Link](new
ArrayAdapter<String>(getApplicationContext(),[Link].simple_list_item_1,wifis
));

Following is the modified content of the xml res/layout/activity_main.xml.

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView android:text="Wifi" android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/textview"

android:textSize="35dp"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials point"

android:id="@+id/textView"

android:layout_below="@+id/textview"

android:layout_centerHorizontal="true"

android:textColor="#ff7aff24"

android:textSize="35dp" />

<mageView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/imageView"

android:src="@drawable/abc"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true" />

<ListView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/listView"

android:layout_below="@+id/imageView"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:background="#fff5d376" />
</RelativeLayout>

Following is the content of [Link] file.

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

<manifest xmlns:android="[Link]

package="[Link]" >

<uses-permission android:name="[Link].ACCESS_WIFI_STATE" />

<uses-permission android:name="[Link].CHANGE_WIFI_STATE" />

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name=".MainActivity"

android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>

</manifest>

Android - Widgets Tutorial


A widget is a small gadget or control of your android application placed on the home screen.
Widgets can be very handy as they allow you to put your favourite applications on your home
screen in order to quickly access them. You have probably seen some common widgets, such as
music widget, weather widget, clock widget e.t.c

Widgets could be of many types such as information widgets, collection widgets, control widgets
and hybrid widgets. Android provides us a complete framework to develop our own widgets.

Widget - XML file


In order to create an application widget , first thing you need is AppWidgetProviderInfo object,
which you will define in a separate widget XML file. In order to do that, right click on your project
and create a new folder called xml. Now right click on the newly created folder and create a new
XML file. The resource type of the XML file should be set toAppWidgetProvider. In the xml file,
define some properties which are as follows −

<appwidget-provider

xmlns:android="[Link]

android:minWidth="146dp"

android:updatePeriodMillis="0"

android:minHeight="146dp"

android:initialLayout="@layout/activity_main">

</appwidget-provider>

Widget - Layout file


Now you have to define the layout of your widget in your default XML file. You can drag
components to generate auto xml.

Widget - Java file


After defining layout, now create a new JAVA file or use existing one, and extend it
withAppWidgetProvider class and override its update method as follows.

In the update method, you have to define the object of two classes which are PendingIntent and
RemoteViews. Its syntax is −

PendingIntent pending = [Link](context, 0, intent, 0);

RemoteViews views = new RemoteViews([Link](), [Link].activity_main);


In the end you have to call an update method updateAppWidget() of the AppWidgetManager class.
Its syntax is −

[Link](currentWidgetId,views);

A part from the updateAppWidget method, there are other methods defined in this class to
manipulate widgets. They are as follows −

[Link] Method & Description

1 onDeleted(Context context, int[] appWidgetIds)

This is called when an instance of AppWidgetProvider is deleted.

2 onDisabled(Context context)

This is called when the last instance of AppWidgetProvider is deleted

3 onEnabled(Context context)

This is called when an instance of AppWidgetProvider is created.

4 onReceive(Context context, Intent intent)

It is used to dispatch calls to the various methods of the class

Widget - Manifest file


You also have to declare the AppWidgetProvider class in your manifest file as follows:

<receiver android:name="ExampleAppWidgetProvider" >

<intent-filter>

<action android:name="[Link].APPWIDGET_UPDATE" />

</intent-filter>

<meta-data android:name="[Link]"
android:resource="@xml/example_appwidget_info" />

</receiver>

Example
Here is an example demonstrating the use of application Widget. It creates a basic widget
applications that will open this current website in the browser.

To experiment with this example, you need to run this on an actual device on which internet is
running.

Step Description
s

1 You will use Android studio to create an Android application under a package
[Link]. 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/[Link] file to add widget code.

3 Modify the res/layout/activity_main to add respective XML components

4 Create a new folder and xml file under res/xml/[Link] to add respective XML
components

5 Modify the [Link] to add the necessary permissions

6 Run the application and choose a running android device and install the application
on it and verify the results.

Following is the content of the modified [Link].

package [Link];

import [Link];
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MainActivity extends AppWidgetProvider{

public void onUpdate(Context context, AppWidgetManager appWidgetManager,int[]


appWidgetIds) {

for(int i=0; i<[Link]; i++){

int currentWidgetId = appWidgetIds[i];

String url = "[Link]

Intent intent = new Intent(Intent.ACTION_VIEW);

[Link](Intent.FLAG_ACTIVITY_NEW_TASK);

[Link]([Link](url));

PendingIntent pending = [Link](context, 0,intent, 0);

RemoteViews views = new


RemoteViews([Link](),[Link].activity_main);

[Link]([Link], pending);

[Link](currentWidgetId,views);

[Link](context, "widget added", Toast.LENGTH_SHORT).show();

Following is the modified content of the xml res/layout/activity_main.xml.

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link] android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"

tools:context=".MainActivity"

android:transitionGroup="true">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials point"

android:id="@+id/textView"

android:layout_centerHorizontal="true"

android:textColor="#ff3412ff"

android:textSize="35dp" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Widget"

android:id="@+id/button"

android:layout_centerHorizontal="true"

android:layout_marginTop="61dp"

android:layout_below="@+id/textView" />

&lr;/RelativeLayout>

Following is the content of the res/xml/[Link].

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

<appwidget-provider

xmlns:android="[Link]

android:minWidth="146dp"
android:updatePeriodMillis="0"

android:minHeight="146dp"

android:initialLayout="@layout/activity_main">

</appwidget-provider>

Following is the content of the res/values/[Link].

<resources>

<string name="app_name">My Application</string>

<string name="hello_world">Hello world!</string>

<string name="action_settings">Settings</string>

</resources>

Following is the content of [Link] file.

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

<manifest xmlns:android="[Link]

package="[Link]" >

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<receiver android:name=".MainActivity">

<intent-filter>

<action android:name="[Link].APPWIDGET_UPDATE"></action>

</intent-filter>

<meta-data android:name="[Link]"

android:resource="@xml/mywidget"></meta-data>

</receive>
</application>

</manifest>

Android - XML Parser Tutorial


XML stands for Extensible Mark-up [Link] is a very popular format and commonly used for
sharing data on the internet. This chapter explains how to parse the XML file and extract necessary
information from it.

Android provides three types of XML parsers which are DOM,SAX and XMLPullParser. Among all
of them android recommend XMLPullParser because it is efficient and easy to use. So we are
going to use XMLPullParser for parsing XML

The first step is to identify the fields in the XML data in which you are interested in. For example. In
the XML given below we interested in getting temperature only.

<?xml version="1.0"?>

<current>

<city id="2643743" name="London">

<coord lon="-0.12574" lat="51.50853"/>

<country>GB</country>

<sun rise="2013-10-08T06:13:56" set="2013-10-08T17:21:45"/>

</city>

<temperature value="289.54" min="289.15" max="290.15" unit="kelvin"/>

<humidity value="77" unit="%"/>

<pressure value="1025" unit="hPa"/>

</country>

XML - Elements
An xml file consist of many components. Here is the table defining the components of an XML file
and their description.

[Link] Component & description


1 Prolog

An XML file starts with a prolog. The first line that contains the information about a
file is prolog

2 Events

An XML file has many events. Event could be like this. Document starts , Document
ends, Tag start , Tag end and Text e.t.c

3 Text

Apart from tags and events, and xml file also contains simple text. Such as GBis a
text in the country tag.

4 Attributes

Attributes are the additional properties of a tag such as value e.t.c

XML - Parsing
In the next step, we will create XMLPullParser object , but in order to create that we will first create
XmlPullParserFactory object and then call its newPullParser() method to create XMLPullParser. Its
syntax is given below −

private XmlPullParserFactory xmlFactoryObject = [Link]();

private XmlPullParser myparser = [Link]();

The next step involves specifying the file for XmlPullParser that contains XML. It could be a file or
could be a Stream. In our case it is a [Link] syntax is given below −

[Link](stream, null);

The last step is to parse the XML. An XML file consist of events, Name, Text, AttributesValue e.t.c.
So XMLPullParser has a separate function for parsing each of the component of XML file. Its syntax
is given below −
int event = [Link]();

while (event != XmlPullParser.END_DOCUMENT)

String name=[Link]();

switch (event){

case XmlPullParser.START_TAG:

break;

case XmlPullParser.END_TAG:

if([Link]("temperature")){

temperature = [Link](null,"value");

break;

event = [Link]();

The method getEventType returns the type of event that happens. e.g: Document start , tag start
e.t.c. The method getName returns the name of the tag and since we are only interested in
temperature , so we just check in conditional statement that if we got a temperature tag , we call the
method getAttributeValue to return us the value of temperature tag.

Apart from the these methods, there are other methods provided by this class for better parsing
XML files. These methods are listed below −

[Link] Method & description

1 getAttributeCount()

This method just Returns the number of attributes of the current start tag

2 getAttributeName(int index)

This method returns the name of the attribute specified by the index value
3 getColumnNumber()

This method returns the Returns the current column number, starting from 0.

4 getDepth()

This method returns Returns the current depth of the element.

5 getLineNumber()

Returns the current line number, starting from 1.

6 getNamespace()

This method returns the name space URI of the current element.

7 getPrefix()

This method returns the prefix of the current element

8 getName()

This method returns the name of the tag

9 getText()

This method returns the text for that particular element

10 isWhitespace()

This method checks whether the current TEXT event contains only whitespace
characters.

Example
Here is an example demonstrating the use of XMLPullParser class. It creates a basic Weather
application that allows you to parse XML from google weather api and show the result.

To experiment with this example, you can run this on an actual device or in an emulator.
Step Description
s

1 You will use Android studio to create an Android application under a package
[Link]. 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/[Link] file to add necessary code.

3 Modify the res/layout/activity_main to add respective XML components

4 Create a new java file under src/[Link] to fetch and parse XML data

5 Modify [Link] to add necessary internet permission

6 Run the application and choose a running android device and install the application
on it and verify the results

Following is the content of the modified main activity file [Link].

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];
import [Link];

import [Link];

import [Link];

import [Link];

[Link]

public class MainActivity extends ActionBarActivity {

EditText ed1,ed2,ed3,ed4,ed5;

private String url1 = "[Link]

private String url2 = "&mode=xml";

private HandleXML obj;

Button b1;

protected void onCreate(Bundle savedInstanceState) {

[Link](savedInstanceState);

setContentView([Link].activity_main);

b1=(Button)findViewById([Link]);

ed1=(EditText)findViewById([Link]);

ed2=(EditText)findViewById([Link].editText2);

ed3=(EditText)findViewById([Link].editText3);

ed4=(EditText)findViewById([Link].editText4);

ed5=(EditText)findViewById([Link].editText5);

[Link](new [Link]() {

@Override

public void onClick(View v) {

String url = [Link]().toString();

String finalUrl = url1 + url + url2;

[Link](finalUrl);
obj = new HandleXML(finalUrl);

[Link]();

while([Link]);

[Link]([Link]());

[Link]([Link]());

[Link]([Link]());

[Link]([Link]());

});

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate([Link].menu_main, menu);

return true;

@Override

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 [Link].

int id = [Link]();

//noinspection SimplifiableIfStatement

if (id == [Link].action_settings) {

return true;

return [Link](item);

}
}

Following is the content of src/[Link]/[Link].

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

/**

* Created by Sairamkrishna on 4/11/2015.

*/

public class HandleXML {

private String country = "county";

private String temperature = "temperature";

private String humidity = "humidity";

private String pressure = "pressure";

private String urlString = null;

private XmlPullParserFactory xmlFactoryObject;

public volatile boolean parsingComplete = true;

public HandleXML(String url){

[Link] = url;

public String getCountry(){

return country;

public String getTemperature(){

return temperature;
}

public String getHumidity(){

return humidity;

public String getPressure(){

return pressure;

public void parseXMLAndStoreIt(XmlPullParser myParser) {

int event;

String text=null;

try {

event = [Link]();

while (event != XmlPullParser.END_DOCUMENT) {

String name=[Link]();

switch (event){

case XmlPullParser.START_TAG:

break;

case [Link]:

text = [Link]();

break;

case XmlPullParser.END_TAG:

if([Link]("country")){

country = text;

}
else if([Link]("humidity")){

humidity = [Link](null,"value");

else if([Link]("pressure")){

pressure = [Link](null,"value");

else if([Link]("temperature")){

temperature = [Link](null,"value");

else{

break;

event = [Link]();

parsingComplete = false;

catch (Exception e) {

[Link]();

public void fetchXML(){

Thread thread = new Thread(new Runnable(){

@Override

public void run() {

try {

URL url = new URL(urlString);

HttpURLConnection conn = (HttpURLConnection)[Link]();


[Link](10000 /* milliseconds */);

[Link](15000 /* milliseconds */);

[Link]("GET");

[Link](true);

[Link]();

InputStream stream = [Link]();

xmlFactoryObject = [Link]();

XmlPullParser myparser = [Link]();

[Link](XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);

[Link](stream, null);

parseXMLAndStoreIt(myparser);

[Link]();

catch (Exception e) {

[Link]();

});

[Link]();

Following is the modified content of the xml res/layout/activity_main.xml.

<RelativeLayout xmlns:android="[Link]

xmlns:tools="[Link] android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="XML Fetch"

android:id="@+id/textView"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true"

android:textSize="30dp" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tutorials Point"

android:id="@+id/textView2"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true"

android:textSize="35dp"

android:textColor="#ff16ff01" />

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/editText"

android:hint="Location"

android:layout_below="@+id/textView2"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:layout_marginTop="61dp"

android:layout_alignParentRight="true"

android:layout_alignParentEnd="true" />
<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Weather "

android:id="@+id/button"

android:layout_below="@+id/editText"

android:layout_centerHorizontal="true" />

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/editText2"

android:layout_below="@+id/button"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:layout_alignRight="@+id/editText"

android:layout_alignEnd="@+id/editText"

android:text="Currency" />

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/editText3"

android:layout_below="@+id/editText2"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:layout_alignParentRight="true"

android:layout_alignParentEnd="true"

android:text="Temp" />

<EditText

android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:id="@+id/editText4"

android:layout_below="@+id/editText3"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:layout_alignRight="@+id/editText3"

android:layout_alignEnd="@+id/editText3"

android:text="Humidity" />

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/editText5"

android:layout_below="@+id/editText4"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:layout_alignParentRight="true"

android:layout_alignParentEnd="true"

android:text="Pressure" />

</RelativeLayout>

Following is the content of [Link] file.

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

<manifest xmlns:android="[Link]

package="[Link]" >

<uses-permission android:name="[Link]"/>

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >
<activity

android:name=".MainActivity"

android:label="@string/app_name" >

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>

</manifest>

You might also like