MAD Notes
MAD Notes
5.1 Intent:
An intent is a description of an operation to be performed.
Android uses Intent for communicating between the components of an Application and also from one application
to another application.
Intent are the objects which is used in android for passing the information among Activities in an Application and
from one app to another also. Intent are used for communicating between the Application components and it also
provides the connectivity between two apps.
For example: Intent facilitate you to redirect your activity to another activity on occurrence of any event. By calling,
startActivity() you can perform this task.
In the above example, foreground activity is getting redirected to another activity i.e. SecondActivity.java.
getApplicationContext() returns the context for your foreground activity.
An Intent can be used to:
1. Start an Activity
2. Start a Service
3. Deliver a Broadcast
Types of Intent:-
5.1.1 Implicit Intent:
An implicit intent allows you to start an activity in another app by describing an action you intend to perform
such as “Share an article”, “View a map” or “take a picture”.
An implicit intent specifies an action and may provide data with which to perform the action.
Implicit intent do not specify the target activity class, just the intended class.
In implicit intent we do need to specify the name of the component. We just specify the Action which has to
be performed and further this action is handled by the component of another application.
The basic example of implicit intent is to open any web page.
Syntax:-
Intent intentObj = new Intent(Intent.ACTION_VIEW);
intentObj.setData(Uri.parse(“https://www.google.com”));
startActivity(intentObj);
Intent Example :
Step 1: Let’s design the UI of activity_main.xml:
First design the text view displaying basic details of the App
Second design the two button of Explicit Intent Example and Implicit Intent Example
Below is the complete code of activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android: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:textAppearance="?android:attr/textAppearanceMedium"
android:text="If you click on Explicit example we will navigate to second activity within App
and if you click on Implicit example AbhiAndroid Homepage will open in Browser"
android:id="@+id/textView2"
android:clickable="false"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginTop="42dp"
android:background="#3e7d02"
android:textColor="#ffffff" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Explicit Intent Example"
android:id="@+id/explicit_Intent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="147dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Implicit Intent Example"
android:id="@+id/implicit_Intent"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
In this activity we will simply use TextView to tell user he is now on second activity.
Below is the complete code of activity_second.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:background="#CCEEAA"
tools:context="com.example.android.intents.SecondActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="This is Second Activity"
android:id="@+id/textView"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Step 3: Implement onClick event for Implicit And Explicit Button inside MainActivity.java
Now we will use setOnClickListener() method to implement OnClick event on both the button. Implicit button will
open AbhiAndroid.com homepage in browser and Explicit button will move to SecondActivity.java.
Below is the complete code of MainActivity.java
package com.example.android.intents;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
Now we need to create another SecondActivity.java which will simply open the layout of activity_second.xml . Also
we will use Toast to display message that he is on second activity.
Below is the complete code of SecondActivity.java:
package com.example.android.intents;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Toast.makeText(getApplicationContext(), "We are moved to second
Activity",Toast.LENGTH_LONG).show();
}
}
</manifest>
Output:
Now run the above program in your Emulator. The App will look like this:
First Click on Explicit Intent Example. The SecondActivity will be open within the App:
Now go back in Emulator and click on Implicit Intent Example. The AbhiAndroid.com homepage will open in
Browser (make sure you have internet):
Intent Filter:
In android, Intent Filter is an expression in the app’s manifest file (ActivityMainfest.xml) and it is used to
specify the type of intents that the component would like to receive. In case if we create Intent Filter for an
activity, there is a possibility for other apps to start our activity by sending a certain type of intent otherwise the
activity can be started only by an explicit intent.
Generally, the Intent Filters (<intent-filter>) whatever we define in the manifest file can be nested in the
corresponding app components and we can specify the type of intents to accept using these three elements.
<action>
It defines the name of an intended action to be accepted and it must be a literal string value of an action, not the
class constant.
<category>
It defines the name of an intent category to be accepted and it must be the literal string value of an action, not
the class constant.
<data>
It defines the type of data to be accepted and by using one or more attributes we can specify various aspects of
the data URI (scheme, host, port, path) and MIME type.
Intent Filter in Manifest File
Following is the code snippet of defining an activity with Intent Filter (<intent-filter>) in the Android Manifest
file (AndroidManifest.xml) like as shown below.
<activity android:name=".MainActivity">
<intent-filter
android:icon=”@drawable/icon”
android:label=”@string/label”
>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>
We can define a filter with multiple instances of <action>, <category> or <data> elements and we need to
make sure that component can handle all the combinations of filter elements.
If you are using above code make sure below things are correct:
1. Icon :- This is displayed as icon for activity. You can sketch or save png image of name icon in
drawable folder.
2. Label:- The lable/title that appears at top in toolbar of the particular activity.
Following is the code snippet of defining multiple Intent filters in the android manifest file to handle multiple
Intents.
<activity android:name=".MainActivity">
<!-- This activity is the main entry, should appear in app launcher -->
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>
<activity android:name=".ResultActivity">
<!-- This activity handles "SEND" actions with text data -->
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>
Create a new android application using android studio and open an activity_main.xml file from \src\main\res\
layout path. In case if you are not aware of creating an app in android studio check this article Android Hello
World App.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/sendMail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="150dp"
android:layout_marginTop="230dp"
android:text="Send Mail" />
</LinearLayout>
Now open our main activity file MainActivity.java from \src\main\java\
com.tutlane.intents path and write the code like as shown below
MainActivity.java
package com.tutlane.intentfilters;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnSend = (Button)findViewById(R.id.sendMail);
btnSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent si = new Intent(Intent.ACTION_SEND);
si.setType("message/rfc822");
si.putExtra(Intent.EXTRA_EMAIL, new String[]{"[email protected]"});
si.putExtra(Intent.EXTRA_SUBJECT, "Welcome to Tutlane");
si.putExtra(Intent.EXTRA_TEXT, "Hi Guest, Welcome to Tutlane Tutorial
Site");
startActivity(Intent.createChooser(si,"Choose Mail App"));
}
});
}
}
If you observe above code we used multiple components to send email, as
ACTION_SEND - It’s an activity action that specifies that we are sending some data.
setType - We use this property to set the MIME type of data that we want to send. Here we used
“message/rfc822” and other MIME types are “text/plain” and “image/jpg”
putExtra - we use this putExtra() method to add extra information to our Intent. Here we add the following
things.
EXTRA_EMAIL – It’s an array of email addresses
Now open android manifest file (AndroidManifest.xml) and write the code like as shown below
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutlane.intentfilters">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="message/rfc822"/>
</intent-filter>
</activity>
</application>
</manifest>
If you observe above AndroidManifest.xml file we added following extra fields of Intent filters.
action - we use this property to define that the activity can perform SEND action.
category - we included the DEFAULT category for this activity to be able to receive implicit intents.
An activity lifecycle shows all the states an activity can be in, and the callbacks associated with transitioning
from each state to the next one.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// The activity is being created.
}
2. onStart( ) – Activity Started:
called when the activity is becoming visible to user.
Can be called more than once during lifecycle.
Followed by onResume( ) if the activity comes to the foreground , or onStop( ) if it becomes
hidden.
@Override
protected void onStart() {
super.onStart();
// The activity is about to become visible.
}
3. onRestart( ) – Activity Started:
called after activity has been stopped, immediately before it is started again.
Always followed by onStart( )
@Override
protected void onRestart() {
super.onRestart();
// The activity is about to be restarted.
}
4. onResume( ) – Activity Resumed/Running:
Called when the activity will start interacting with user.
Activity has moved to top of the activity stack.
Start accepting user input.
Running State
Always followed by onPause( )
@Override
protected void onResume() {
super.onResume();
// The activity has become visible (it is now "resumed").
}
5. onPause( ) – Activity Paused:
Called when system is about to resume a previous activity.
The activity is partly visible but user is leaving the activity.
Typically used to commit unsaved changes to persistent data, stop animations and anything that
consumes resources.
Followed by either onResume( ) if the activity returns back to the front or onStop( ) if it
becomes invisible to the user.
@Override
protected void onPause() {
super.onPause();
// Another activity is taking focus
// (this activity is about to be "paused").
}
6. onStop( ) – Activity Stopped:
Called when the activity is no longer visible to the user.
New activity is being started, an existing one is brought in front of this one or this one is being
destroyed.
Followed by either onRestart( ) if the activity is coming back to interact with the user or
onDestroy( ) if this activity is going away.
@Override
protected void onStop() {
super.onStop();
// The activity is no longer visible (it is now "stopped")
}
7. onDestroy ( ) – Activity Destroyed:
Final call before activity is destroyed.
Activity is finishing or system is destroying it to save space.
Call isFinishing( ) method to check.
System may destroy activity without calling this, so use onPause( ) or onStop( ) to save data or
state.
@Override
protected void onDestroy() {
super.onDestroy();
// The activity is about to be destroyed.
}
1. Implicit intents are used to start activities based on registered components that the system is aware of
general functionality.
2. Explicit intents are used to start specific, fully qualified activities as well as to pass information
between activities in yor app.
5.3.1 Broadcast Intents:
We required third party of intent that can be delivered to any interested application know as the broadcast
intent.
A broadcast intent is a background operation, on the other hand, is a foreground operation that modifies what
the user is currently interacting with.
If you want your application itself should generate and send custom intents then you will have to create and
send those intents by using the sendBroadcast() method inside your activity class. If you use
the sendStickyBroadcast(Intent) method, the Intent is sticky, meaning the Intent you are sending stays around
after the broadcast is complete.
public void broadcastIntent(View view) {
Intent intent = new Intent();
intent.setAction("com.tutorialspoint.CUSTOM_INTENT");
sendBroadcast(intent);
}
This intent com.tutorialspoint.CUSTOM_INTENT can also be registered in similar way as we have regsitered
system generated intent.
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:name="MyReceiver">
<intent-filter>
<action android:name="com.tutorialspoint.CUSTOM_INTENT">
</action>
</intent-filter>
</receiver>
</application>
Broadcast-Receiver
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:name="MyReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED">
</action>
</intent-filter>
</receiver>
</application>
Now whenever your Android device gets booted, it will be intercepted by BroadcastReceiver MyReceiver and
implemented logic inside onReceive() will be executed.
There are several system generated events defined as final static fields in the Intent class. The following table
lists a few important system events.
2 android.intent.action.BATTERY_LOW
Indicates low battery condition on the device.
3 android.intent.action.BATTERY_OKAY
Indicates the battery is now okay after being low.
4 android.intent.action.BOOT_COMPLETED
This is broadcast once, after the system has finished booting.
5 android.intent.action.BUG_REPORT
Show activity for reporting a bug.
6 android.intent.action.CALL
Perform a call to someone specified by the data.
android.intent.action.CALL_BUTTON
7
The user pressed the "call" button to go to the dialer or other appropriate UI for
placing a call.
8 android.intent.action.DATE_CHANGED
The date has changed.
9 android.intent.action.REBOOT
Have the device reboot.
A content provider component supplies data from one application to others on request. Such requests are
handled by the methods of the ContentResolver class. A content provider can use different ways to store its
data and the data can be stored in a database, in files, or even over a network.
ContentProvider
sometimes it is required to share data across applications. This is where content providers become
very useful.
Content providers let you centralize content in one place and have many different applications access it as
needed. A content provider behaves very much like a database where you can query it, edit its content, as well
as add or delete content using insert(), update(), delete(), and query() methods. In most cases this data is
stored in an SQlite database.
A content provider is implemented as a subclass of ContentProvider class and must implement a standard
set of APIs that enable other applications to perform transactions.
public class My Application extends ContentProvider {
}
Content URIs
To query a content provider, you specify the query string in the form of a URI which has following format −
<prefix>://<authority>/<data_type>/<id>
1 prefix
This is always set to content://
authority
2 This specifies the name of the content provider, for
example contacts, browser etc. For third-party content providers, this could be the
fully qualified name, such as com.tutorialspoint.statusprovider
3
data_type
This indicates the type of data that this particular provider provides. For example,
if you are getting all the contacts from the Contacts content provider, then the
data path would be people and URI would look like thiscontent://contacts/people
id
4 This specifies the specific record requested. For example, if you are looking for
contact number 5 in the Contacts content provider then URI would look like
this content://contacts/people/5.
ContentProvider
Once you are done with adding records in the database, now its time to ask ContentProvider to give us those
records back, so let's click Retrieve Students button which will fetch and display all the records one by one
which is as per our the implementation of our query() method.
You can write activities against update and delete operations by providing callback functions
in MainActivity.java file and then modify user interface to have buttons for update and deleted operations in
the same way as we have done for add and read operations.
5.5 Fragments:
A Fragment is a piece of an activity which enable more modular activity design. It will not be wrong if we say,
a fragment is a kind of sub-activity.
The application can embed two fragments in Activity A, when running on a tablet-sized device. However, on a
handset-sized screen, there's not enough room for both fragments, so Activity A includes only the fragment for
the list of articles, and when the user selects an article, it starts Activity B, which includes the second fragment
to read the article.
Here is the list of methods which you can to override in your fragment class −
onAttach()The fragment instance is associated with an activity instance.The fragment and the activity
is not fully initialized. Typically you get in this method a reference to the activity which uses the
fragment for further initialization work.
onCreate() The system calls this method when creating the fragment. You should initialize essential
components of the fragment that you want to retain when the fragment is paused or stopped, then
resumed.
onCreateView() The system calls this callback when it's time for the fragment to draw its user interface
for the first time. To draw a UI for your fragment, you must return a View component from this method
that is the root of your fragment's layout. You can return null if the fragment does not provide a UI.
onActivityCreated()The onActivityCreated() is called after the onCreateView() method when the host
activity is created. Activity and fragment instance have been created as well as the view hierarchy of
the activity. At this point, view can be accessed with the findViewById() method. example. In this
method you can instantiate objects which require a Context object
onStart()The onStart() method is called once the fragment gets visible.
onResume()Fragment becomes active.
onPause() The system calls this method as the first indication that the user is leaving the fragment.
This is usually where you should commit any changes that should be persisted beyond the current
user session.
onStop()Fragment going to be stopped by calling onStop()
onDestroyView()Fragment view will destroy after call this method
onDestroy()onDestroy() called to do final clean up of the fragment's state but Not guaranteed to be
called by the Android platform.
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.res.Configuration;
import android.os.Bundle;
/**
* Check the device orientation and act accordingly
*/
if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) {
/**
* Landscape mode of the device
*/
LM_Fragement ls_fragment = new LM_Fragement();
fragmentTransaction.replace(android.R.id.content, ls_fragment);
}else{
/**
* Portrait mode of the device
*/
PM_Fragement pm_fragment = new PM_Fragement();
fragmentTransaction.replace(android.R.id.content, pm_fragment);
}
fragmentTransaction.commit();
}
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by TutorialsPoint7 on 8/23/2016.
*/
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by TutorialsPoint7 on 8/23/2016.
*/
Create two layout files lm_fragement.xml and pm_fragment.xml under res/layout directory.
Following is the content of lm_fragement.xml file −
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#7bae16">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/landscape_message"
android:textColor="#000000"
android:textSize="20px" />
</LinearLayout>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/portrait_message"
android:textColor="#000000"
android:textSize="20px" />
</LinearLayout>
Following will be the content of res/layout/activity_main.xml file which includes your fragments −
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<fragment
android:name="com.example.fragments"
android:id="@+id/lm_fragment"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
<fragment
android:name="com.example.fragments"
android:id="@+id/pm_fragment"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
Let's try to run our modified MyFragments application we just created. I assume you had created
your AVD while doing environment set-up. 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 Emulator window where you will click on
Menu button to see the following window. Be patience because it may take sometime based on your computer
speed −
To change the mode of the emulator screen, let's do the following −
fn+control+F11 on Mac to change the landscape to portrait and vice versa.
ctrl+F11 on Windows.
ctrl+F11 on Linux.
Once you changed the mode, you will be able to see the GUI which you have implemented for landscape
mode as below −
2. List Fragment:
fragments having special list view is called as list fragment
Static library support version of the framework's ListFragment. Used to write apps that run on
platforms prior to Android 3.0. When running on Android 3.0 or above, this implementation is still
used.
The basic implementation of list fragment is for creating list of items in fragments
List in Fragments
Example
Before start coding i will initialize of the string constants inside string.xml file under res/values directory
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">ListFragmentDemo</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="imgdesc">imgdesc</string>
<string-array name="Planets">
<item>Sun</item>
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
<item>Jupiter</item>
<item>Saturn</item>
<item>Uranus</item>
<item>Neptune</item>
</string-array>
</resources>
Following will be the content of res/layout/activity_main.xml file. it contained linear layout and fragment tag.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<fragment
android:id="@+id/fragment1"
android:name="com.example.tutorialspoint7.myapplication.MyListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Following will be the content of res/layout/list_fragment.xml file. it contained linear layout,list view and text
view
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<TextView
android:id="@android:id/empty"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TextView>
</LinearLayout>
following will be the content of src/main/java/myListFragment.java file.before writing to code, need to follow
few steps as shown below
Create a class MyListFragment and extend it to ListFragment.
Inside the onCreateView() method , inflate the view with above defined list_fragment xml layout.
Inside the onActivityCreated() method , create a arrayadapter from resource ie using String array
R.array.planet which you can find inside the string.xml and set this adapter to listview and also set the
onItem click Listener.
Inside the OnItemClickListener() method , display a toast message with Item name which is being
clicked.
package com.example.tutorialspoint7.myapplication;
import android.annotation.SuppressLint;
import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Toast;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.Planets, android.R.layout.simple_list_item_1);
setListAdapter(adapter);
getListView().setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
Toast.makeText(getActivity(), "Item: " + position, Toast.LENGTH_SHORT).show();
}
}
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
following code will be the content of manifest.xml, which has placed at res/AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tutorialspoint7.myapplication">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
3. Fragment Transaction:
Using with fragment transaction. we can move one fragment to another fragment.
What is a Transition?
Activity and Fragment transitions in Lollipop are built on top of a relatively new feature in Android called
Transitions. Introduced in KitKat, the transition framework provides a convenient API for animating between
different UI states in an application. The framework is built around two key concepts: scenes and transitions. A
scene defines a given state of an application's UI, whereas a transition defines the animated change between
two scenes.
When a scene changes, a Transition has two main responsibilities −
Capture the state of each view in both the start and end scenes.
Create an Animator based on the differences that will animate the views from one scene to the other.
Example
following will be the content of res.layout/activity_main.xml it contained TextView
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical|center_horizontal"
android:text="@string/hello_world"
android:textAppearance="?android:attr/textAppearanceMedium" />
Following will be the content of res/animation/fragment_stack.xml file. it contained frame layout and button
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<fragment
android:id="@+id/fragment1"
android:name="com.pavan.listfragmentdemo.MyListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<objectAnimator
android:interpolator="@android:interpolator/decelerate_quint"
android:valueFrom="0.0" android:valueTo="1.0"
android:valueType="floatType"
android:propertyName="alpha"
android:duration="@android:integer/config_mediumAnimTime" />
</set>
following will be the content of res/animation/fragment_slide_left_exit.xml file.it contained set and object
animator tags.
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<objectAnimator
android:interpolator="@android:interpolator/decelerate_quint"
android:valueFrom="0dp" android:valueTo="-100dp"
android:valueType="floatType"
android:propertyName="translationX"
android:duration="@android:integer/config_mediumAnimTime" />
<objectAnimator
android:interpolator="@android:interpolator/decelerate_quint"
android:valueFrom="1.0" android:valueTo="0.0"
android:valueType="floatType"
android:propertyName="alpha"
android:duration="@android:integer/config_mediumAnimTime" />
</set>
<objectAnimator
android:interpolator="@android:interpolator/decelerate_quint"
android:valueFrom="0.0" android:valueTo="1.0"
android:valueType="floatType"
android:propertyName="alpha"
android:duration="@android:integer/config_mediumAnimTime" />
</set>
<objectAnimator
android:interpolator="@android:interpolator/decelerate_quint"
android:valueFrom="1.0" android:valueTo="0.0"
android:valueType="floatType"
android:propertyName="alpha"
android:duration="@android:integer/config_mediumAnimTime" />
</set>
following code will be the content of src/main/java/MainActivity.java file. it contained button listener, stack
fragment and onCreateView
package com.example.fragmentcustomanimations;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
/**
* Demonstrates the use of custom animations in a FragmentTransaction when
* pushing and popping a stack.
*/
public class FragmentCustomAnimations extends Activity {
int mStackLevel = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_stack);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
addFragmentToStack();
}
});
if (savedInstanceState == null) {
// Do first time initialization -- add initial fragment.
Fragment newFragment = CountingFragment.newInstance(mStackLevel);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.simple_fragment, newFragment).commit();
}
else
{
mStackLevel = savedInstanceState.getInt("level");
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("level", mStackLevel);
}
void addFragmentToStack() {
mStackLevel++;
/**
* When creating, retrieve this instance's number from its arguments.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNum = getArguments() != null ? getArguments().getInt("num") : 1;
}
/**
* The Fragment's UI is just a simple text view showing its
* instance number.
*/
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.hello_world, container, false);
View tv = v.findViewById(R.id.text);
((TextView)tv).setText("Fragment #" + mNum);
tv.setBackgroundDrawable(getResources().
getDrawable(android.R.drawable.gallery_thumb));
return v;
}
}
}
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.fragmentcustomanimations.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Running the Application
Let's try to run our Fragment Transitions application we just created. I assume you had created
your AVD while doing environment set-up. To run the app from Android Studio, open one of your project's
activity files and click Run icon from the toolbar. Android installs the app on your AVD and starts it and if
everything is fine with your setup and application, it will display following Emulator window:
If click on new fragment, it going to be changed the first fragment to second fragment as shown below
5.6 Services:
In android, Service is a component which keep an app running in the background to perform long-running
operations based on our requirements. For Service, we don’t have any user interface and it will run the apps in
the background like playing the music in the background or handle network operations when the user in a
different app.
Started Service
A service is Started when an application component, such as an activity calls startService() method. Once it
started, it will run indefinitely in background even if the component that started is destroyed.
We can stop the Started service by using stopService() method or the service can stop itself by
calling stopSelf() method. In android, the Started service component will perform a single operation and it
won’t return any result to the caller.
Intent intent = new Intent(this, MyService.class);
startService(intent);
Bound Service
A service is Bound when another application component calls bindService() method. The bound service runs as
long as another application component is bound to it.
We can unbind the service by calling unbindService() method based on our requirements. In android, we can
bind multiple components to a single service at once, but the service will be destroyed in case all the
components unbind.
Implementing a bound service:
To implement a bound service, define the interface that specifies how a client can communicate with
the service . This interface, which your service returns from the onBind( ) callback method, must be an
implementation of IBinder.
To retrieve the IBinder interface, a client application component calls bindService( ).
Once the client receives the IBinder, the client interacts with the service through the interface.
@Override
public IBinder onBind(Intent intent) {
//TODO for communication return IBinder implementation
return null;
}
}
Binding to a Service:
To bind to a service that is declared in the manifest and implemented by an app component, use
bindService( ) with an explicit intent.
Manage the service lifecycle.
onStartCommand()
The system will invoke this method when another component such as an activity requests the service to be
started by calling startService(). When this method executed, the service will start and run indefinitely in
background. If we implement this in our code, it’s our responsibility to stop the service once code execution is
done by calling stopSelf() or stopService() methods. In case, if we want to provide only binding, then we don’t
need to implement this method.
In android, onStartCommand() method must return an integer and the integer is a value that describes how the
system will continue the service in the event that the system kills it.
The onStartCommand() method will return a value from one of the following constants.
onBind()
The system will invoke this method when another component wants to bind with the service by
calling bindService(). During implementation of this method, we must need to provide an interface to the clients
to communicate with the service by returning an IBinder object. In android, we must need to implement this
method, in case if we don’t need to allow binding, then we should return NULL.
onCreate()
The system will invoke this method when the service is created initially
using onStartCommand() or onBind() methods to do one-time setup procedures. In case, if the service is already
running, then this method will not call.
onDestroy()
The system will invoke this method when the service is no longer used and is being destroyed. This is the final
call that the service will receive and we need to implement this method in our service to clean up any unused
resources such as threads, receivers or listeners.
Generally, in android if we start a service by calling startService() method, the service will run continuously
even if the component that started service is destroyed until we stop it by using stopService() or it stops itself
with stopSelf().
Same way, if we create a service by calling bindService() method, the service will runs as long as the
component is bound to it. After the service is unbound from all of its clients, the system will destroy it.
In android, the service life cycle is having a set of callback methods that need to be implemented to keep a track
of services status and to execute the required things in appropriate-time.
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
@Override
public void onCreate() {
// The service is being created
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// The service is starting, due to a call to startService()
return mStartMode;
}
@Override
public IBinder onBind(Intent intent) {
// A client is binding to the service with bindService()
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
// All clients have unbound with unbindService()
return mAllowRebind;
}
@Override
public void onRebind(Intent intent) {
// A client is binding to the service with bindService(),
// after onUnbind() has already been called
}
@Override
public void onDestroy() {
// The service is no longer used and is being destroyed
}
}
Create a new android application using android studio and give names as Services. In case if you are not aware
of creating an app in android studio check this article Android Hello World App.
Now we need to create our own custom service file MyService.java in \java\com.tutlane.services path to
define our actual provider and associated methods for that right-click on your application folder Go
to New select Java Class and give name as MyService.java.
Once we create a new file MyService.java, open it and write the code like as shown below
MyService.java
package com.tutlane.services;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.provider.Settings;
import android.widget.Toast;
/**
* Created by Tutlane on 02-08-2017.
*/
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btnStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="startService"
android:layout_marginLeft="130dp"
android:layout_marginTop="150dp"
android:text="Start Service"/>
<Button
android:id="@+id/btnstop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="stopService"
android:layout_marginLeft="130dp"
android:layout_marginTop="20dp"
android:text="Stop Service"/>
</LinearLayout>
Now open MainActivity.java file from \java\com.tutlane.services path and write following to implement
custom broadcast intents.
MainActivity.java
package com.tutlane.services;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// Start the service
public void startService(View view) {
startService(new Intent(this, MyService.class));
}
// Stop the service
public void stopService(View view) {
stopService(new Intent(this, MyService.class));
}
}
Now we need to register our service in android manifest file (AndroidManifest.xml)
using <service> attribute like as shown below.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutlane.services">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyService" />
</application>
</manifest>
If we click on Start Service button, the default ringtone will start playing and it will continue until we stop the
service. This is how we can create, start or stop services in android applications based on our requirements.
5.6.4 Permission:
Permission entity mst have in order to launch the service or bind to it. If a caller of startService( ),
bindService( ) or stopService( ) has not been granted this permission, the method will not work and the
Intent object will not be delivered to the service.
If this attribute is not set, the permission set by the <application> element’s permission attribute applies
to the service. If neither attribute is set, the service is not protected by permission.
2. Requesting Permisssion:
To request permission , add the <uses-permission> attribute to the android manifest file, along
with the name of the requested permission.
For Example, to get permission to use the camera:
<uses-permission android:name=”android.permission.CAMERA”/>
Libraries
On top of Linux kernel there is a set of libraries including open-source Web browser engine WebKit, well
known library libc, SQLite database which is a useful repository for storage and sharing of application data,
libraries to play and record audio and video, SSL libraries responsible for Internet security etc.
Android Libraries
This category encompasses those Java-based libraries that are specific to Android development. Examples of
libraries in this category include the application framework libraries in addition to those that facilitate user
interface building, graphics drawing and database access. A summary of some key core Android libraries
available to the Android developer is as follows −
android.app − Provides access to the application model and is the cornerstone of all Android
applications.
android.content − Facilitates content access, publishing and messaging between applications and
application components.
android.database − Used to access data published by content providers and includes SQLite database
management classes.
android.opengl − A Java interface to the OpenGL ES 3D graphics rendering API.
android.os − Provides applications with access to standard operating system services including
messages, system services and inter-process communication.
android.text − Used to render and manipulate text on a device display.
android.view − The fundamental building blocks of application user interfaces.
android.widget − A rich collection of pre-built user interface components such as buttons, labels, list
views, layout managers, radio buttons etc.
android.webkit − A set of classes intended to allow web-browsing capabilities to be built into
applications.
Having covered the Java-based core libraries in the Android runtime, it is now time to turn our attention to the
C/C++ based libraries contained in this layer of the Android software stack.
Android Runtime
This is the third section of the architecture and available on the second layer from the bottom. This section
provides a key component called Dalvik Virtual Machine which is a kind of Java Virtual Machine specially
designed and optimized for Android.
The Dalvik VM makes use of Linux core features like memory management and multi-threading, which is
intrinsic in the Java language. The Dalvik VM enables every Android application to run in its own process,
with its own instance of the Dalvik virtual machine.
The Android runtime also provides a set of core libraries which enable Android application developers to write
Android applications using standard Java programming language.
Application Framework
The Application Framework layer provides many higher-level services to applications in the form of Java
classes. Application developers are allowed to make use of these services in their applications.
The Android framework includes the following key services −
Activity Manager − Controls all aspects of the application lifecycle and activity stack.
Content Providers − Allows applications to publish and share data with other applications.
Resource Manager − Provides access to non-code embedded resources such as strings, color settings
and user interface layouts.
Notifications Manager − Allows applications to display alerts and notifications to the user.
View System − An extensible set of views used to create application user interfaces.
Applications
You will find all the Android application at the top layer. You will write your application to be installed on this
layer only. Examples of such applications are Contacts Books, Browser, Games etc.
DVM Proxy:
The java object, we are talking to.
E.g. For a media player, it is the media player java object.
It is a proxy for the native proxy which in turn is the proxy for the actual native implementation.
Native Proxy:
Proxy object for the media service.
Native proxy is a C++ object that talks through the binder interface.
This enables to provide media service access to native applications like games.
Native application cannot communicate through JNI.
Binder:
Binder is the abstraction for IPC.
It marshals object across process boundries through a special kernel driver.
Processes can share memory enables moving data back between applications and media player, move
file descriptors duped across processes.
Used extensively in Surface Flinger and Audio Flinger.
Binder Proxy:
The marshalling code in the application side.
Binder Native:
The marshalling code in the server side Native implementation.
The Media Player service instantiate a MediaPlayer object in the service which is proxied in the
application by the MediaPlayer java object.
High overhead involved in making a call through this stack.
This is acceptable since we do not make a lot of calls to the media player service.
Media player objects must be reused as much as possible.
The android media framework provides a built in support for playing a variety of common media types, sch as
audio and video. We have multiple ways to play audio or video but the most important component of media
framework is MediaPlayer class.
Following is the code snippet, to play an audio that is available in our application’s local raw resource (res/raw)
directory.
MediaPlayer mPlayer = MediaPlayer.create(this, R.raw.baitikochi_chuste);
mPlayer.start();
The second parameter in create() method is the name of the song that we want to play from our application
resource directory (res/raw). In case if raw folder not exists in your application, create a new raw folder
under res directory and add a properly encoded and formatted media files in it.
In case, if we want to play an audio from a URI that is locally available in the system, we need to write the code
like as shown below.
Uri myUri = ....; // initialize Uri here
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setDataSource(getApplicationContext(), myUri);
mPlayer.prepare();
mPlayer.start();
If we want to play an audio from a URL via HTTP streaming, we need to write the code like as shown below.
String url = "http://........"; // your URL here
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setDataSource(url);
mPlayer.prepare(); // might take long! (for buffering, etc)
mPlayer.start();
If you observe above code snippets, we create an instance of MediaPlayer class and added required audio
source, streaming type, audio file path, etc. to play an audio from our application.
Apart from above methods, MediaPlayer class provides a different type of methods to control audio and video
files based on requirements.
Method Description
getDuration() It is used to get the total time duration of the song in milliseconds.
release() It is used to releases the resources which are associated with MediaPlayer
object.
Now we will see how to implement media playing application using MediaPlayer to play a song or audio with
multiple playback options, such as play, pause, forward, backward in android application with examples.
Create a new android application using android studio and give names as MediaPlayerExample. In case if you
are not aware of creating an app in android studio check this article Android Hello World App.
As discussed create a new raw folder in res directory and add one music file like as shown below to play it by
using MediaPlayer class.
Now open activity_main.xml file from \res\layout folder path and write the code like as shown below.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<TextView
android:id="@+id/txtVw1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Now Playing: "
android:layout_marginTop="30dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/txtSname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/txtVw1"
android:layout_toRightOf="@+id/txtVw1"
android:text="TextView" />
<ImageView
android:id="@+id/imgLogo"
android:layout_width="match_parent"
android:layout_height="450dp"
android:layout_below="@+id/txtVw1"
android:src="@drawable/tutlane" />
<ImageButton
android:id="@+id/btnBackward"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="44dp"
android:layout_marginLeft="20dp"
android:src="@android:drawable/ic_media_rew" />
<ImageButton
android:id="@+id/btnPlay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/btnBackward"
android:layout_marginLeft="20dp"
android:layout_toRightOf="@+id/btnBackward"
android:src="@android:drawable/ic_media_play" />
<ImageButton
android:id="@+id/btnPause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/btnPlay"
android:layout_marginLeft="20dp"
android:layout_toRightOf="@+id/btnPlay"
android:src="@android:drawable/ic_media_pause" />
<ImageButton
android:id="@+id/btnForward"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/btnPause"
android:layout_marginLeft="20dp"
android:layout_toRightOf="@+id/btnPause"
android:contentDescription="@+id/imageButton3"
android:src="@android:drawable/ic_media_ff" />
<TextView
android:id="@+id/txtStartTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/sBar"
android:text="0 min, 0 sec" />
<SeekBar
android:id="@+id/sBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/btnBackward"
android:layout_toLeftOf="@+id/txtSongTime"
android:layout_toRightOf="@+id/txtStartTime" />
<TextView
android:id="@+id/txtSongTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/btnForward"
android:layout_alignTop="@+id/sBar"
android:text="0 min, 0 sec " />
</RelativeLayout>
Now open your main activity file MainActivity.java from \java\com.tutlane.audioplayerexample path and
write the code like as shown below.
MainActivity.java
package com.tutlane.mediaplayerexample;
import android.media.MediaPlayer;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import java.util.concurrent.TimeUnit;
playbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Playing Audio",
Toast.LENGTH_SHORT).show();
mPlayer.start();
eTime = mPlayer.getDuration();
sTime = mPlayer.getCurrentPosition();
if(oTime == 0){
songPrgs.setMax(eTime);
oTime =1;
}
songTime.setText(String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes(eTime),
TimeUnit.MILLISECONDS.toSeconds(eTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS. toMinutes(eTime))) );
startTime.setText(String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes(sTime),
TimeUnit.MILLISECONDS.toSeconds(sTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS. toMinutes(sTime))) );
songPrgs.setProgress(sTime);
hdlr.postDelayed(UpdateSongTime, 100);
pausebtn.setEnabled(true);
playbtn.setEnabled(false);
}
});
pausebtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mPlayer.pause();
pausebtn.setEnabled(false);
playbtn.setEnabled(true);
Toast.makeText(getApplicationContext(),"Pausing Audio",
Toast.LENGTH_SHORT).show();
}
});
forwardbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if((sTime + fTime) <= eTime)
{
sTime = sTime + fTime;
mPlayer.seekTo(sTime);
}
else
{
Toast.makeText(getApplicationContext(), "Cannot jump forward 5 seconds",
Toast.LENGTH_SHORT).show();
}
if(!playbtn.isEnabled()){
playbtn.setEnabled(true);
}
}
});
backwardbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if((sTime - bTime) > 0)
{
sTime = sTime - bTime;
mPlayer.seekTo(sTime);
}
else
{
Toast.makeText(getApplicationContext(), "Cannot jump backward 5
seconds", Toast.LENGTH_SHORT).show();
}
if(!playbtn.isEnabled()){
playbtn.setEnabled(true);
}
}
});
}
Generally, the MediaController class in android will provide playback options for video player, such as play,
pause, backward, forward, etc.
The VideoView class in android will provide the functionality to fetch and play the videos using video player
with minimal setup in android applications.
Following is the code snippet, to use VideoView and MediaController classes to implement video player in
android application to play videos based on our requirements.
VideoView videoView =(VideoView)findViewById(R.id.vdVw);
MediaController mediaController= new MediaController(this);
mediaController.setAnchorView(videoView);
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.video1);
videoView.setMediaController(mediaController);
videoView.setVideoURI(uri);
videoView.requestFocus();
videoView.start();
If you observe above code snippet, we created an instance of MediaController, VideView class and added
required video source and add playback options to video player by using VideoView object.
Here we used a Uri object to play videos from our application resource directory (res/raw). In case
if raw folder does not exist in our application, create a new raw folder under res directory and add properly
encoded and formatted video files in it.
Apart from the above methods, the VideoView class provides a different type of methods to control video files
based on requirements.
Method Description
Now we will see how to implement video playing applications using MediaController and VideoView with
multiple playback options, such as play, pause, forward, backward in android application with examples.
Create a new android application using android studio and give names as VideoPlayerExample. In case if you
are not aware of creating an app in android studio check this article Android Hello World App.
As discussed create a new raw folder in res directory and add one video file like as shown below.
Now open activity_main.xml file from \res\layout folder path and write the code like as shown below.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<VideoView
android:id="@+id/vdVw"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center" />
</RelativeLayout>
Now open your main activity file MainActivity.java from \java\com.tutlane.videoplayerexample path and
write the code like as shown below
MainActivity.java
package com.tutlane.videoplayerexample;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;
If you observe above code we used MediaController and VideoView objects with required properties to
implement video player based on our requirements.
In android, by using TextToSpeech class we can easily convert our text into voice and it supports different
types of speaking languages. We can choose the speaking language based on our requirements in the android
application.
Generally, the android TextToSpeech instance can only be used to synthesize text once it has completed its
initialization so implement TextToSpeech.OnInitListener to notify the completion of initialization.
During the initialization, we can set the audio pitch rate, audio speed, type of language to speak, etc. based on
our requirements.
Following is the code snippet of converting text to voice using TextToSpeech class in android applications.
public
class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener {
....
TextToSpeech textToSpeech;
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = textToSpeech.setLanguage(Locale.US);
String text = speakText.getText().toString();
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null, null);
}
}
....
}
If you observe above code, we used TextToSpeech.OnInitListener to notify the completion of initialization
and used TextToSpeech class to convert entered text to voice.
Now we will see how to use the TextToSpeech component to convert the given text to speech conversion in
android application with examples.
Create a new android application using android studio and give names as TextSpeechExample. In case if you
are not aware of creating an app in android studio check this article Android Hello World App.
Once we create an application, open activity_main.xml file from \res\layout folder path and write the code like
as shown below.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/fstTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="150dp"
android:text="Enter Text to Speak"/>
<EditText
android:id="@+id/txtSpeak"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10"/>
<Button
android:id="@+id/btnSpeech"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="Speak" />
</LinearLayout>
Now open your main activity file MainActivity.java from \java\com.tutlane.textspeechexample path and
write the code like as shown below
MainActivity.java
package com.tutlane.textspeechexample;
import android.os.Build;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.Locale;
public
class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener {
Button speakBtn;
EditText speakText;
TextToSpeech textToSpeech;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
speakText = (EditText) findViewById(R.id.txtSpeak);
speakBtn = (Button)findViewById(R.id.btnSpeech);
textToSpeech = new TextToSpeech(this, this);
speakBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
texttoSpeak();
}
});
}
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = textToSpeech.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA || result ==
TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("error", "This Language is not supported");
} else {
texttoSpeak();
}
} else {
Log.e("error", "Failed to Initialize");
}
}
@Override
public void onDestroy() {
if (textToSpeech != null) {
textToSpeech.stop();
textToSpeech.shutdown();
}
super.onDestroy();
}
private void texttoSpeak() {
String text = speakText.getText().toString();
if ("".equals(text)) {
text = "Please enter some text to speak.";
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null, null);
}
else {
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
}
If you observe above code, we are converting the text to speech conversion using TextToSpeech class.
Output of Android TextToSpeech Example
When we run the above example in the android emulator we will get a result like as shown below.
5.7.4 Sensors:
Generally, most of the android devices have built-in sensors to measure motion, orientation, and various
environmental conditions. These sensors will provide raw data with high accuracy and are useful to monitor
three-dimensional device movement or positioning or monitor changes in the ambient environment near a
device.
For example, to report changes in the environment a weather application might use a temperature sensor and
humidity sensor or a travel application might use the geomagnetic field sensor and accelerometer to report a
compass bearing, etc.
Category Description
Motion Sensors These sensors are useful to measure acceleration forces and rotational forces along
three axes. This category includes accelerometers, gravity sensors, gyroscopes,
and rotational vector sensors.
Environmental These sensors are useful to measure various environmental parameters, such as
Sensors ambient air temperature and pressure, illumination, and humidity. This category
includes barometers, photometers, and thermometers.
Position These sensors are useful to measure the physical position of a device. This category
Sensors includes orientation sensors and magnetometers.
Android provided a framework called sensor framework to access all the sensors available on device and to
get all the raw sensor data. The sensor framework provided a wide variety of sensor-related tasks. For example,
by using a sensor framework we can perform the following things
It lists all the available sensors on the device
It determines the capabilities of each sensor, such as its maximum range, manufacturer, power
requirements, and resolution.
It can acquire raw sensor data and define the minimum rate at which you acquire sensor data.
Register and unregister sensor event listeners that monitor sensor changes.
The Android sensor framework will allow us to access many types of sensors, some of these sensors are
hardware-based and some are software-based. The Hardware-based sensors are physical components built on
the handset or tablet device and Software-based sensors are not physical devices but they mimic Hardware-
based sensors.
The Android sensor framework provided the following classes and interfaces to access device sensors and
acquire raw sensor data.
Class Description
SensorManager By using this class we can create an instance of sensor service and this class
provides a various methods for accessing and listing sensors, registering and
unregistering sensor event listeners and acquiring orientation information.
Sensor By using this class we can create an instance of a specific sensor and this class
provides various methods that let you determine the sensor's capabilities.
SensorEvent The system uses this class to create a sensor event object and it provides the raw
sensor data, type of sensor that generated the event, accuracy of the data, and
the timestamp for the event.
SensorEventListe We can use this interface to create two callback methods that receive
ner notifications (sensor events) when sensor values change or when sensor accuracy
changes.
Now we will see how to use android sensor framework to get the list of available sensors on android device
with examples.
Create a new android application using android studio and give names as SensorExample. In case if you are
not aware of creating an app in android studio check this article Android Hello World App.
Once we create an application, open activity_main.xml file from \res\layout folder path and write the code like
as shown below.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<TextView
android:id="@+id/sensorslist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="80dp"
android:text="Sensors"
android:textSize="20dp"
android:textStyle="bold"
android:layout_gravity="center"
android:visibility="gone"/>
</LinearLayout>
Now open your main activity file MainActivity.java from \java\com.tutlane.sensorsexample path and
write the code like as shown below
MainActivity.java
package com.tutlane.sensorsexample;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.util.List;
If you observe above result, we got all the available sensors on a device using android sensor framework in our
android application.
This is how we can use android sensor framework to identify list all the available sensors on a device, checking
whether the specific type of sensor exists or not, monitoring a sensor event changes, etc. based on our
requirements.
5.7.5 Async Task:
Android AsyncTask going to do background operation on background thread and update on main thread. In
android we cant directly touch background thread to main thread in android development. asynctask help us to
make communication between background thread to main thread.
Methods of AsyncTask
onPreExecute() − Before doing background operation we should show something on screen like
progressbar or any animation to user. we can directly comminicate background operation using on
doInBackground() but for the best practice, we should call all asyncTask methods .
doInBackground(Params) − In this method we have to do background operation on background
thread. Operations in this method should not touch on any mainthread activities or fragments.
onProgressUpdate(Progress…) − While doing background operation, if you want to update some
information on UI, we can use this method.
onPostExecute(Result) − In this method we can update ui of background operation result.
xmlns:tools = "http://schemas.android.com/tools"
android:id = "@+id/rootview"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:orientation = "vertical"
android:background = "#c1c1c1"
android:gravity = "center_horizontal"
tools:context = ".MainActivity">
<Button
android:id = "@+id/asyncTask"
android:text = "Download"
android:layout_width = "wrap_content"
<ImageView
android:id = "@+id/image"
android:layout_width = "300dp"
android:layout_height = "300dp" />
</LinearLayout>
In the above xml we have created a button, when user click on the button it going to download image and
append image to imageview.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
InputStream is = null;
ProgressDialog p;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button=findViewById(R.id.asyncTask);
imageView=findViewById(R.id.image);
button.setOnClickListener(new View.OnClickListener() {
@Override
asyncTask.execute("https://www.tutorialspoint.com/images/tp-logo-diamond.png");
}
});
@Override
super.onPreExecute();
p = new ProgressDialog(MainActivity.this);
p.setIndeterminate(false);
p.setCancelable(false);
p.show();
@Override
try {
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream();
options.inPreferredConfig = Bitmap.Config.RGB_565;
} catch (IOException e) {
e.printStackTrace();
return bmImg;
@Override
super.onPostExecute(bitmap);
if(imageView!=null) {
p.hide();
imageView.setImageBitmap(bitmap);
}else {
p.show();
}
}
In the above code we are downloading image using asyncTask and appending image to imageview.
Step 4 − Add the following code to manifest.xml
package = "com.example.andy.myapplication">
<application
android:allowBackup = "true"
android:icon = "@mipmap/ic_launcher"
android:label = "@string/app_name"
android:roundIcon = "@mipmap/ic_launcher_round"
android:supportsRtl = "true"
android:theme = "@style/AppTheme">
<intent-filter>
</intent-filter>
</activity>
</application>
</manifest>
In the above AndroidManifest.xml file we have added internet permission to access internet to download image.
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 Eclipse
Run Icon icon from the toolbar. Select your mobile device as an option and then check your mobile device
which will display your default screen.
Now click on download button it will show progress on UI and download image at background as shown below
Now you will set the source , output and encoding format and output file. Their syntax is given below.
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(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.
myAudioRecorder.prepare();
myAudioRecorder.start();
Apart from these methods , there are other methods listed in the MediaRecorder class that allows you more
control over audio and video recording.
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.
Here is the content of src/MainActivity.java
package com.example.sairamkrishna.myapplication;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.IOException;
import java.util.Random;
import android.support.v4.app.ActivityCompat;
import android.content.pm.PackageManager;
import android.support.v4.content.ContextCompat;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonStop.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(false);
buttonStopPlayingRecording.setEnabled(false);
buttonStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(checkPermission()) {
AudioSavePathInDevice =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +
CreateRandomAudioFileName(5) + "AudioRecording.3gp";
MediaRecorderReady();
try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
buttonStart.setEnabled(false);
buttonStop.setEnabled(true);
}
});
buttonStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mediaRecorder.stop();
buttonStop.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(true);
buttonStart.setEnabled(true);
buttonStopPlayingRecording.setEnabled(false);
buttonPlayLastRecordAudio.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) throws IllegalArgumentException,
SecurityException, IllegalStateException {
buttonStop.setEnabled(false);
buttonStart.setEnabled(false);
buttonStopPlayingRecording.setEnabled(true);
mediaPlayer.start();
Toast.makeText(MainActivity.this, "Recording Playing",
Toast.LENGTH_LONG).show();
}
});
buttonStopPlayingRecording.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
buttonStop.setEnabled(false);
buttonStart.setEnabled(true);
buttonStopPlayingRecording.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(true);
if(mediaPlayer != null){
mediaPlayer.stop();
mediaPlayer.release();
MediaRecorderReady();
}
}
});
i++ ;
}
return stringBuilder.toString();
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case RequestPermissionCode:
if (grantResults.length> 0) {
boolean StoragePermission = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
boolean RecordPermission = grantResults[1] ==
PackageManager.PERMISSION_GRANTED;
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:src="@drawable/abc"/>
<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_marginTop="37dp"
/>
<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_alignParentRight="true"
android:layout_alignParentEnd="true"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="STOP PLAYING RECORDING "
android:id="@+id/button4"
android:layout_below="@+id/button2"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
/>
</RelativeLayout>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.STORAGE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.sairamkrishna.myapplication.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
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 images.
Now by default you will see stop and play button disable. Just press the Record button and your application
will start recording the audio. It will display the following screen.
Now just press stop button and it will save the recorded audio to external sd card. When you click on stop
button , the following screen would appear.
Now just press the play button and and recorded audio will just start playing on the device. The following
message appears when you click on play button.
5.9 Camera:
In Android, Camera is a hardware device that allows capturing pictures and videos in your applications. Follow
this tutorial to easily understand how to use a camera in your own Android App.
The Android framework provides the facility of working with Camera in two ways:
<uses-permission android:name="android.permission.CAMERA"/>
requestPermissions(newString[]{Manifest.permission.CAMERA},MY_CAMERA_PERMISSION_CODE)
startActivityForResult(cameraIntent, CAMERA_REQUEST);
When you start an activity for the result, it request Camera to take a photo then return it to your calling activity,
you pass it a unique integer value or anything you have not used already in that class. The requestCode helps
you to identify from which Intent you came back.
So, that CAMERA_REQUEST could be any value you define in your class like this:
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK)
{
theImage = (Bitmap) data.getExtras().get("data");
photo=getEncodedString(theImage);
setDataToDataBase();
}
}
getEncodedString(Bitmap bitmap) Method:
Since now I am able to click an image from the camera but that image is in the form of Bitmap but I want to
store it as a string in the database, so I am going to encode it using ByteArrayOutputStream Class. This Class
holds a copy of data and forwards it to multiple streams.
bitmap.compress(Bitmap.CompressFormat.JPEG,100, os);
setDataToDataBase() Method:
Now I am storing data(Image) to a database(here I have used SQLite). Here the ContentValue class helps to put
information inside an object in the form of Key-Value pairs for columns. To Insert or Update your
WritableDatabase The object can then be passed to an instance of the SQLiteDatabase class.
Create a new android application using android studio and give names as CameraExample. In case if you are
not aware of creating an app in android studio check this article Android Hello World App.
Once we create an application, open activity_main.xml file from \res\layout folder path and write the code like
as shown below.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<Button
android:id="@+id/btnTakePicture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Take a Photo"
android:textStyle="bold"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true" />
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/capturedImage"
android:layout_above="@+id/btnTakePicture"/>
</RelativeLayout>
Now open your main activity file MainActivity.java from \java\com.tutlane.cameraexample path and write
the code like as shown below
MainActivity.java
package com.tutlane.cameraexample;
import android.content.Intent;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
When we click on Take a Photo button, the camera will start and we can take the picture of whatever we want,
the captured image will be shown in defined imageview.
BLUETOOT We need this permission to perform any Bluetooth communication, such as requesting a
H connection, accepting a connection, and transferring data.
LOCATION We need this permission because the Bluetooth scans can be used to gather the
information about the location of user.
In case, if we want to discover the available Bluetooth devices or manipulate Bluetooth settings from our app,
we need to define BLUETOOTH_ADMIN permission.
Following is the example of defining the Bluetooth permissions in android manifest file.
<manifest ... >
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
...
</manifest>
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 = BluetoothAdapter.getDefaultAdapter();
Following is the code snippet to enable the system’s discoverable mode to make sure that the device
discoverable to other devices.
Intent dIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
dIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(dIntent);
If you observe above code snippet, we are making sure our device discoverable to other devices
using ACTION_REQUEST_DISCOVERABLE. By default, the device becomes discoverable for 120
seconds. We can extend the device discoverable duration up to 3600 seconds (1 hour), by adding
the EXTRA_DISCOVERABLE_DURATION extra.
4. Android List Paired Devices
By using the BluetoothAdapter method getBondedDevices(), we can get the Bluetooth paired devices list.
Following is the code snippet to get all paired devices with name and MAC address of each device.
// Get paired devices.
Set<BluetoothDevice> pairedDevices = bAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
// There are paired devices. Get the name and address of each paired device.
for (BluetoothDevice device : pairedDevices) {
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
}
}
Apart from this constant, there are other constants provided the API , that supports different tasks. They are
listed below.
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
ACTION_FOUND
3
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 = BA.getBondedDevices();
Apart form the parried Devices , there are other methods in the API that gives more control over Blueetooth.
They are listed below.
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.
Here is the content of src/MainActivity.java
package com.example.sairamkrishna.myapplication;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Set;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button);
b2=(Button)findViewById(R.id.button2);
b3=(Button)findViewById(R.id.button3);
b4=(Button)findViewById(R.id.button4);
BA = BluetoothAdapter.getDefaultAdapter();
lv = (ListView)findViewById(R.id.listView);
}
lv.setAdapter(adapter);
}
}
<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/Base.TextAppearance.AppCompat" />
<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>
<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="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</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.If your Bluetooth will not be turned on then, it will ask your permission to enable the
Bluetooth.
Now just select the Get Visible button to turn on your visibility. The following screen would appear asking your
permission to turn on discovery for 120 seconds.
Now just select the List Devices option. It will list down the paired devices in the list view. In my case , I have
only one paired device. It is shown below.
Now just select the Turn off button to switch off the Bluetooth. Following message would appear when you
switch off the bluetooth indicating the successful switching off of Bluetooth.
5.11 Animation:
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 perform 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 = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.myanimation);
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 −
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(R.id.imageView1);
image.startAnimation(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.
Here is the modified code of MainActivity.java.
package com.example.sairamkrishna.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.Toast;
<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/abc"
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>
<scale xmlns:android="http://schemas.android.com/apk/res/android"
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="http://schemas.android.com/apk/res/android"
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>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:duration="5000" >
</rotate>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:startOffset="5000"
android:fromDegrees="360"
android:toDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:duration="5000" >
</rotate>
</set>
<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>
<translate
android:fromXDelta="0%p"
android:toXDelta="75%p"
android:duration="800" />
</set>
Here is the code of res/anim/slide.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
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>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.animation.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
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. Android studio will display following images
Select zoom button, it will display following screen −
1. Necessity of SQLite:
Creation and Connection of databases:
SQLite is an open source relational database i.e. used to perform database operations on android devices such
as storing, manipulating or retrieving persistent data from the database.
It is embedded in Android by default. So, there is no need to perform any database setup or administration task
like JDBC, ODBC, etc.
SQLiteOpenHandler class provides functionality to use SQLite database.
SQLite stores data to a text file on the device.
SQLite supports all the relational database features.
2. Database - Package
The main package is android.database.sqlite 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
object.Its syntax is given below
SQLiteDatabase 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
1
openDatabase(String path, SQLiteDatabase.CursorFactory 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, SQLiteDatabase.CursorFactory 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, SQLiteDatabase.CursorFactory factory)
It not only opens but create the database if it not exists. This method is equivalent to openDatabase
method.
4
openOrCreateDatabase(File file, SQLiteDatabase.CursorFactory 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 file.getPath()
Database - Insertion
we can create table or insert data into table using execSQL method defined in SQLiteDatabase class. Its syntax
is given below
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS TutorialsPoint(Username
VARCHAR,Password VARCHAR);");
mydatabase.execSQL("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
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 = mydatbase.rawQuery("Select * from TutorialsPoint",null);
resultSet.moveToFirst();
String username = resultSet.getString(0);
String password = resultSet.getString(1);
There are other functions available in the Cursor class that allows us to effectively retrieve the data. That
includes
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
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.
Following is the content of the modified MainActivity.java.
package com.example.sairamkrishna.myapplication;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
obj.setOnItemClickListener(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;
intent.putExtras(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(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
super.onOptionsItemSelected(item);
switch(item.getItemId()) {
case R.id.item1:Bundle dataBundle = new Bundle();
dataBundle.putInt("id", 0);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
TextView name ;
TextView phone;
TextView email;
TextView street;
TextView place;
int id_To_Update = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_contact);
name = (TextView) findViewById(R.id.editTextName);
phone = (TextView) findViewById(R.id.editTextPhone);
email = (TextView) findViewById(R.id.editTextStreet);
street = (TextView) findViewById(R.id.editTextEmail);
place = (TextView) findViewById(R.id.editTextCity);
if(Value>0){
//means this is the view part not the add contact part.
Cursor rs = mydb.getData(Value);
id_To_Update = Value;
rs.moveToFirst();
String nam =
rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NAME));
String phon =
rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_PHONE));
String emai =
rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_EMAIL));
String stree =
rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STREET));
String plac =
rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_CITY));
if (!rs.isClosed()) {
rs.close();
}
Button b = (Button)findViewById(R.id.button1);
b.setVisibility(View.INVISIBLE);
name.setText((CharSequence)nam);
name.setFocusable(false);
name.setClickable(false);
phone.setText((CharSequence)phon);
phone.setFocusable(false);
phone.setClickable(false);
email.setText((CharSequence)emai);
email.setFocusable(false);
email.setClickable(false);
street.setText((CharSequence)stree);
street.setFocusable(false);
street.setClickable(false);
place.setText((CharSequence)plac);
place.setFocusable(false);
place.setClickable(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 = extras.getInt("id");
if(Value>0){
getMenuInflater().inflate(R.menu.display_contact, menu);
} else{
getMenuInflater().inflate(R.menu.menu_main menu);
}
}
return true;
}
phone.setEnabled(true);
phone.setFocusableInTouchMode(true);
phone.setClickable(true);
email.setEnabled(true);
email.setFocusableInTouchMode(true);
email.setClickable(true);
street.setEnabled(true);
street.setFocusableInTouchMode(true);
street.setClickable(true);
place.setEnabled(true);
place.setFocusableInTouchMode(true);
place.setClickable(true);
return true;
case R.id.Delete_Contact:
AlertDialog d = builder.create();
d.setTitle("Are you sure");
d.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"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
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
public boolean insertContact (String name, String phone, String email, String
street,String place) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("email", email);
contentValues.put("street", street);
contentValues.put("place", place);
db.insert("contacts", null, contentValues);
return true;
}
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));
res.moveToNext();
}
return array_list;
}
}
<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>
<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>
<item android:id="@+id/item1"
android:icon="@drawable/add"
android:title="@string/Add_New" >
</item>
</menu>
<item
android:id="@+id/Delete_Contact"
android:orderInCategory="100"
android:title="@string/delete"/>
</menu>
<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="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</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.
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 sai has been added.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/<your.package.name>/databases<database-name>.
3. Transactions:
A transaction is a unit of work that is performed against a database. Transactions are units or sequences of
work accomplished in a logical order, whether in a manual fashion by a user or automatically by some sort of a
database program.
A transaction is the propagation of one or more changes to the database. For example, if you are creating a
record or updating a record or deleting a record from the table, then you are performing a transaction on that
table. It is important to control these transactions to ensure the data integrity and to handle database errors.
Practically, you will club many SQL queries into a group and you will execute all of them together as a part of
a transaction.