Unit-5 Activity and Multimedia With Databases
Unit-5 Activity and Multimedia With Databases
with Databases
Unit-V Activity and Multimedia with Databases
Course Outcome:
Unit Outcomes:
---------------------------------------------------------------------------------------------------------------
Contents:
In the above example, foreground activity is getting redirected to another activity i.e.
SecondActivity.java. getApplicationContext() returns the context for your foreground
activity.
Department of Computer Engineering 1 Mrs. Kapadnis N.Y.
Mobile Application Development Unit-V Activity and Multimedia
with Databases
Types of Intents:
Intent are of two types: Explicit Intent and Implicit Intent
Explicit Intent:
Explicit Intent work internally within an application to perform navigation and data
transfer. The below given code snippet will help you understand the concept of Explicit
Intents
Here SecondActivity is the JAVA class name where the activity will now be navigated.
Example with code in the end of this post will make it more clear.
Implicit Intent:
Let’s take an example to understand Implicit Intents more clearly. We have to open a
website using intent in your application. See the code snippet given below
Unlike Explicit Intent you do not use any class name to pass through Intent(). In this
example we has just specified an action. Now when we will run this code then Android
will automatically start your web browser and it will open AbhiAndroid home page.
Intent Example
In Android:
Let’s implement Intent for a very basic use. In the below example we will Navigate from
one Activity to another and open a web homepage of AbhiAndroid using Intent. The
example will show you both implicit and explicit Intent together. Below is the final
output:
Create a project in Android Studio and named it “Intents”. Make an activity, which would
consists Java file; MainActivity.java and an xml file for User interface which would be
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>
<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
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;
explicit_btn = (Button)findViewById(R.id.explicit_Intent);
implicit_btn = (Button) findViewById(R.id.implicit_Intent);
explicit_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(intent);
}
});
implicit_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
}
package com.example.android.intents;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
<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>
<activity android:name=".SecondActivity" >
</activity>
</application>
</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):
<!--Here Name of Activity is .MainActivity, image of icon name stored in drawable folder,
label present inside string name is label-->
<!--If anything is different please customize the code according to your app-->
<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" />
</intent-filter>
</activity>
Important Note: If you are using above code make sure below things are correct:
icon: This is displayed as icon for activity. You can check or save png image of name icon
in drawable folder. If icon image of any other name is stored please replace
@drawable/icon with that image name i.e. @drawable/image_name.
label: The label / title that appears at top in Toolbar of that particular Activity. You can
check or edit label name by opening String XML file present inside Values folder (Values -
> Strings). Replace @string/label to @string/yourlabel.
priority: This is another important attribute in Intent filter used in broadcasting. We will
explain it in future topics of broadcasting.
android:icon="@drawable/icon"
Important Note: If you have not declared any icon for your activity then android sets the
icon of parent component by default. And if no icon is defined by parent component then
icon is set as the default icon by <application> element (declared in Manifest file).
2. android:label
A label represents the title of an activity on the toolbar. You can have different Labels for
different Activities as per your requirement or choice. The label should be set as a
reference to a string resource. However, you can also use a raw string to set a label as
declared in the below given code snippet
android:label = "@string/label"
or
Step 4: Now run the App and you will see your custom name in Toolbar. Below you can
see AbhiAndroid printed.
Important Note: Just like icon attribute, if you have not declared any label for your
activity then it will be same as your parent activity. However if you haven’t declared any
label to parent activity then label is set by <application> element’ label attribute.
Below is sample code of Intent filter for an App having two activity:
<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>
</intent-filter>
</activity>
<activity android:name=".Main2Activity">
<intent-filter>
<!--Add code here for second activity-->
</intent-filter>
</activity>
</application>
1. Action
2. Data
3. Category
Important Note: Every intent filter must contain action element in it. Data and category
element is optional for it.
1. Action:
It represent an activities action, what an activity is going to do. It is declared with the
name attribute as given below
An Intent Filter element must contain one or more action element. Action is a string that
specifies the action to perform. You can declare your own action as given below. But we
usually use action constants defined by Intent class.
<intent-filter>
<action android:name="com.example.android.intentfilters.Main2Activity"/>
</intent-filter>
There are few common actions for starting an activity like ACTION_VIEW
ACTION_VIEW: This is used in an Intent with startActivity(). This helps when you
redirect to see any website, photos in gallery app or an address to view in a map app.
<data android:scheme="string"
android:host="string"
android:port="string"
android:path="string"
android:pathPattern="string"
android:pathPrefix="string"
android:mimeType="string" />
This specifies the format of data associated with an Intent which you use with
component. As explained in above code snippet, data passed through Intent is a type of
URI. Check the below given table for better clarification
ACTION DATA MEANING
Opens phone application
Intent.ACTION_CALL tel:phone_number
and calls phone number
Opens phone application
Intent.ACTION_DIAL tel:phone_number and dials (but doesn’t call)
phone_number
Opens phone application
Intent.ACTION_DIAL voicemail: and dials (but doesn’t call)
the voice mail number.
Opens the maps
Intent.ACTION_VIEW geo:lat,long Application centered on
(lat, long).
Opens the maps
Intent.ACTION_VIEW geo:0,0?q=address application centered on the
specified address.
Intent.ACTION_VIEW http://url Opens the browser
<intent-filter>
<!--Code here-->
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<!--Code here-->
<category android:name="android.intent.category.BROWSABLE" />
</intent-filter>
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>
<activity android:name=".Main2Activity">
<intent-filter>
<action android:name="com.example.android.intentfilters.Main2Activity"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
</application>
</manifest>
Important Note: In above mentioned code snippet we are using two activities which you
have to declare it in the Manifest that which activity has to launch first when your
application starts. In above code we have made MainActivity as a Launcher Activity by
declaring Intent Filter:
Now we will create a new method which will print message in Logcat.
Log.d(HOME_ACTIVITY_TAG, text);
Now we will override all activity lifecycle method in Android and use showLog() method
which we creating for printing message in Logcat.
Complete JAVA code of HomeActivity.java:
package com.abhiandroid.activitylifecycleexample;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
Log.d(HOME_ACTIVITY_TAG, text);
@Override
super.onCreate(savedInstanceState);
showLog("Activity Created");
@Override
showLog("Activity restarted");
@Override
super.onStart();//soon be visible
showLog("Activity started");
@Override
super.onResume();//visible
showLog("Activity resumed");
@Override
super.onPause();//invisible
showLog("Activity paused");
@Override
super.onStop();
showLog("Activity stopped");
@Override
super.onDestroy();
}
When creating an Activity we need to register this in AndroidManifest.xml file. Now
question is why need to register? Its actually because manifest file has the
information which Android OS read very first. When registering an activity other
information can also be defined within manifest like Launcher Activity (An activity that
should start when user click on app icon).
Here is declaration example in AndroidManifest.xml file
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".HomeActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Now go to Logcat present inside Android Monitor: Scroll up and you will notice three
methods which were called: Activity Created, Activity started and Activity resumed.
So this clears:
Now press the back button on the Emulator and exit the App:
Go to Logcat again and scroll down to bottom. You will see 3 more methods were called:
Activity paused, Activity stopped and Activity is being destroyed.
So this clears:
Important Note: In the above example onRestart() won’t be called because there was no
situation when we can resume the onStart() method again. In future example we will
show you onRestart() in action as well.
Importance Of Activity Life Cycle:
Activity is the main component of Android Application, as every screen is an activity
so to create any simple app first we have to start with Activities. Every lifecycle
method is quite important to implement according to requirements, However
onCreate(Bundle state) is always needed to implement to show or display some
content on screen.
BroadcastReceivers
In android, Broadcast Receiver is a component which will allow android system or other
apps to deliver events to the app like sending a low battery message or screen turned off
message to the app. The apps can also initiate broadcasts to let other apps know that
required data available in a device to use it.
Generally, we use Intents to deliver broadcast events to other apps and Broadcast
Receivers use status bar notifications to let user know that broadcast event occurs.
Receiving Broadcasts
In android, we can receive broadcasts by registering in two ways.
One way is by registering a broadcasts using android application manifest file
(AndroidManifest.xml). We need to specify <receiver> element in apps manifest file
like as shown below.
<receiver android:name=".SampleBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
The above statement will fire the defined system broadcast event whenever the boot
process is completed.
Another way is to register a receiver dynamically
via Context.registerReceiver() method. To register broadcast receiver we need to
extend our class using BroadcastReceiver and need to implement a onReceive(Context,
Intent) method like as shown below.
public class MainActivity extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, log, Toast.LENGTH_LONG).show();
}
}
Suppose if we register for ACTION_BOOT_COMPLETED event, whenever the boot
process is completed the broadcast receiver’s method onReceive() method will be
invoked.
Sending Broadcasts
In android, we can send a broadcasts in apps using three different ways, those are
Method Description
Method Description
System Broadcasts
In android, several system events are defined as final static fields in the Intent class.
Following are the some of system events available in android applications.
Event Description
Event Description
Create a BroadcastReceiver
Register a BroadcastReceiver
Create a new android application using android studio and give names
as BroadcastReceiver. 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 broadcast content file MyBroadcastReceiver.java in \
src\main\java\com.tutlane.broadcastreceiver 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 MyBroadcastReceiver.java.
Once we create a new file MyBroadcastReceiver.java, open it and write the code like as
shown below
MyBroadcastReceiver.java
package com.tutlane.broadcastreceiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
/**
* Created by Tutlane on 01-08-2017.
*/
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent){
CharSequence iData = intent.getCharSequenceExtra("msg");
Toast.makeText(context,"Tutlane Received Message:
"+iData,Toast.LENGTH_LONG).show();
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">
<EditText
android:id="@+id/txtMsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="180dp"
android:ems="10"/>
<Button
android:id="@+id/btnShow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickShowBroadcast"
android:layout_marginLeft="130dp"
android:text="Show Broadcast"/>
</LinearLayout>
Now open MainActivity.java file from \java\com.tutlane.broadcastreceiver path and
write following to implement custom broadcast intents.
MainActivity.java
package com.tutlane.broadcastreceiver;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClickShowBroadcast(View view){
EditText st = (EditText)findViewById(R.id.txtMsg);
Intent intent = new Intent();
intent.putExtra("msg",(CharSequence)st.getText().toString());
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutlane.broadcastreceiver">
<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>
<receiver android:name="MyBroadcastReceiver">
<intent-filter>
<action android:name="com.tutlane.CUSTOM_INTENT">
</action>
</intent-filter>
</receiver>
</application>
</manifest>
Content Providers
In android, Content Provider will act as a central repository to store the applications
data in one place and make that data available for different applications to access
whenever it’s required.
In android, we can configure Content Providers to allow other applications securely
access and modify our app data based on our requirements.
Generally, the Content Provider is a part of an android application and it will act as more
like relational database to store the app data. We can perform a multiple operations like
insert, update, delete and edit on the data stored in content provider
using insert(), update(), delete() and query() methods.
In android, we can use content provider whenever we want to share our app data with
other apps and it allow us to make a modifications to our application data without
effecting other applications which depends on our app.
In android, content provider is having different ways to store app data. The app data can
be stored in a SQLite database or in files or even over a network based on our
requirements. By using content providers we can manage data such as audio, video,
images and personal contact information.
We have a different type of access permissions available in content provider to share the
data. We can set a restrict access permissions in content provider to restrict data access
limited to only our application and we can configure different permissions to read or
write a data.
This is how the interaction will happen between android application UI and content
providers to perform required actions to get a data.
Content URIs
In android, Content URI is an URI which is used to query a content provider to get the
required data. The Content URIs will contain the name of entire provider (authority) and
the name that points to a table (path).
Generally the format of URI in android applications will be like as shown below
content://authority/path
Following are the details about various parts of an URI in android application.
content:// - The string content:// is always present in the URI and it is used to
represent the given URI is a content URI.
authority - It represents the name of content provider, for example phone, contacts, etc.
and we need to use fully qualified name for third party content providers like
com.tutlane.contactprovider
path - It represents the table’s path.
We need to create a content provider class that extends the ContentProvider base
class.
We need to define our content provider URI to access the content.
The ContentProvider class defines a six abstract methods (insert(), update(),
delete(), query(), getType()) which we need to implement all these methods as a
part of our subclass.
We need to register our content provider in AndroidManifest.xml
using <provider> tag.
query() - It receives a request from the client. By using arguments it will get a data from
requested table and return the data as a Cursor object.
UserProvider.java
package com.tutlane.contentprovider;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import java.util.HashMap;
/**
public class UsersProvider extends ContentProvider {
static final String PROVIDER_NAME = "com.tutlane.contentprovider.UserProvider";
static final String URL = "content://" + PROVIDER_NAME + "/users";
static final Uri CONTENT_URI = Uri.parse(URL);
static final String id = "id";
static final String name = "name";
static final int uriCode = 1;
static final UriMatcher uriMatcher;
private static HashMap<String, String> values;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(PROVIDER_NAME, "users", uriCode);
uriMatcher.addURI(PROVIDER_NAME, "users/*", uriCode);
}
@Override
public String getType(Uri uri) {
switch (uriMatcher.match(uri)) {
case uriCode:
return "vnd.android.cursor.dir/users";
default:
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
}
@Override
public boolean onCreate() {
Context context = getContext();
DatabaseHelper dbHelper = new DatabaseHelper(context);
db = dbHelper.getWritableDatabase();
if (db != null) {
return true;
}
return false;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(TABLE_NAME);
switch (uriMatcher.match(uri)) {
case uriCode:
qb.setProjectionMap(values);
break;
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_DB_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}
Now open an activity_main.xml file from \src\main\res\layout 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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:layout_marginLeft="100dp"
android:layout_marginTop="100dp"/>
<EditText
android:id="@+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10"/>
<Button
android:id="@+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickAddDetails"
<Button
android:id="@+id/btnRetrieve"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickShowDetails"
android:layout_marginLeft="100dp"
android:text="Show Users"/>
<TextView
android:id="@+id/res"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:clickable="false"
android:ems="10"/>
</LinearLayout>
Now open MainActivity.java file and write the code like as shown below
MainActivity.java
package com.tutlane.contentprovider;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
InputMethodManager imm =
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="co
m.tutlane.contentprovider">
<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>
While performing Fragment Transaction we can add a Fragment into back stack that’s
managed by the Activity. back stack allow us to reverse a Fragment transaction on
pressing Back button of device. For Example if we replace a Fragment and add it in back
stack then on pressing the Back button on device it display the previous Fragment.
Some Important Points about Fragment in Android:
1. Fragments were added in Honeycomb version of Android i.e API version 11.
2. We can add, replace or remove Fragment’s in an Activity while the activity is running.
For performing these operations we need a Layout(Relative Layout, FrameLayout or any
other layout) in xml file and then replace that layout with the required Fragment.
3. Fragments has its own layout and its own behaviour with its own life cycle callbacks.
4. Fragment can be used in multiple activities.
5. We can also combine multiple Fragments in a single activity to build a multi-plane UI.
Need of Fragments in Android:
Before the introduction of Fragment’s we can only show a single Activity on the screen at
one given point of time so we were not able to divide the screen and control different
parts separately. With the help of Fragment’s we can divide the screens in different parts
and controls different parts separately.
By using Fragments we can comprise multiple Fragments in a single Activity. Fragments
have their own events, layouts and complete life cycle. It provide flexibility and also
removed the limitation of single Activity on the screen at a time.
<fragment
android:id="@+id/fragments"
android:layout_width="match_parent"
android:layout_height="match_parent" />
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.ViewGroup;
<LinearLayout 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:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<!-- display two Button's and a FrameLayout to replace the Fragment's -->
<Button
android:id="@+id/firstFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/button_background_color"
android:text="First Fragment"
android:textColor="@color/white"
android:textSize="20sp" />
<Button
android:id="@+id/secondFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="@color/button_background_color"
android:text="Second Fragment"
android:textColor="@color/white"
android:textSize="20sp" />
<FrameLayout
android:id="@+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp" />
</LinearLayout>
package com.abhiandroid.fragmentexample;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
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);
// get the reference of Button's
firstFragment = (Button) findViewById(R.id.firstFragment);
secondFragment = (Button) findViewById(R.id.secondFragment);
firstFragment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// load First Fragment
loadFragment(new FirstFragment());
}
});
// perform setOnClickListener event on Second Button
secondFragment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// load Second Fragment
loadFragment(new SecondFragment());
}
});
Step 4: Now we need 2 fragments and 2 xml layouts. So create two fragments by right
click on your package folder and create classes and name them as FirstFragment and
SecondFragment and add the following code respectively.
FirstFragment.class
package com.abhiandroid.fragmentexample;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
View view;
Button firstButton;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_first, container, false);
// get the reference of Button
firstButton = (Button) view.findViewById(R.id.firstButton);
// perform setOnClickListener on first Button
firstButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// display a message by using a Toast
Toast.makeText(getActivity(), "First Fragment", Toast.LENGTH_LONG).show();
}
});
return view;
}
}
SecondFragment.class
In this Fragment firstly we inflate the layout and get the reference of Button. After that we
perform setOnClickListener event on Button so whenever a user click on the button a
message “Second Fragment“ is displayed on the screen by using a Toast.
package com.abhiandroid.fragmentexample;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_second, container, false);
// get the reference of Button
secondButton = (Button) view.findViewById(R.id.secondButton);
// perform setOnClickListener on second Button
secondButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Step 5: Now create 2 xml layouts by right clicking on res/layout -> New -> Layout
Resource File and name them as fragment_first and fragment_second and add the
following code in respective files.
Here we will design the basic simple UI by using TextView and Button in both xml’s.
fragment_first.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"
tools:context="com.abhiandroid.fragmentexample.FirstFragment">
<Button
android:id="@+id/firstButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="@color/green"
android:text="First Fragment"
android:textColor="@color/white"
android:textSize="20sp"
android:textStyle="bold" />
</RelativeLayout>
fragment_second.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"
tools:context="com.abhiandroid.fragmentexample.SecondFragment">
<Button
android:id="@+id/secondButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="@color/green"
android:text="Second Fragment"
android:textColor="@color/white"
android:textSize="20sp"
android:textStyle="bold" />
</RelativeLayout>
Step 7: Open AndroidManifest.xml
In this step we show the Android Manifest file in which do nothing because we need only
one Activitty i.e MainActivity which is already defined in it. In our project we create two
Fragment’s but we don’t need to define the Fragment’s in manifest because Fragment is a
part of an Activity.
<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" />
Step 8: Now run the App and you will two button. Clicking on first button shows First
Fragment and on click of Second Button shows the Second Fragment which is actually
replacing layout (FrameLayout).
Android Service
Features of Service
The Android platform provides and runs predefined system services and every Android
application can use them, given the right permissions. These system services are usually
Permission
The purpose of a permission is to protect the privacy of an Android user. Android apps
must request permission to access sensitive user data (such as contacts and SMS), as well
as certain system features (such as camera and internet). Depending on the feature, the
system might grant the permission automatically or might prompt the user to approve
the request.
On all versions of Android, to declare that your app needs a permission, put a <uses-
permission> element in your app manifest, as a child of the top-level <manifest> element.
For example, an app that needs to access the internet would have this line in the manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.snazzyapp">
<uses-permission android:name="android.permission.INTERNET"/>
<!-- other permissions go here -->
<application ...>
...
</application>
</manifest>
There can be two forms of a service.The lifecycle of service can follow two different paths:
started or bound.
1. Started
2. Bound
1) Started Service
2) Bound Service
Like any other components service also has callback methods. These will be invoked
while the service is running to inform the application of its state. Implementing these in
your custom service would help you in performing the right operation in the right state.
onCreate()
This is the first callback which will be invoked when any component starts the service. If
the same service is called again while it is still running this method wont be invoked.
Ideally one time setup and intializing should be done in this callback.
onStartCommand()
onBind()
onUnbind()
This is invoked when all the clients are disconnected from the service.
onRebind()
This is invoked when new clients are connected to the service. It is called after onUnbind
onDestroy()
This is a final clean up call from the system. This is invoked just before the service is being
destroyed. Could be very useful to cleanup any resources such as threads, registered
listeners, or receivers.
Let's see the example of service in android that plays an audio in the background. Audio
will not be stopped even if you switch to another activity. To stop the audio, you need to
stop the service.
activity_main.xml
Drag the 3 buttons from the pallete, now the activity_main.xml will look like this:
File: activity_main.xml
<Button
android:id="@+id/buttonStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="74dp"
android:text="Start Service" />
<Button
android:id="@+id/buttonNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="63dp"
android:text="Next Page" />
</RelativeLayout>
activity_next.xml
File: activity_next.xml
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="200dp"
android:text="Next Page"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
Service class
Now create the service implemenation class by inheriting the Service class and
overridding its callback methods.
File: MyService.java
package example.javatpoint.com.androidservice;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;
Activity class
Now create the MainActivity class to perform event handling. Here, we are writing the
code to start and stop service. Additionally, calling the second activity on buttonNext.
package example.javatpoint.com.androidservice;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
buttonStart = findViewById(R.id.buttonStart);
buttonStop = findViewById(R.id.buttonStop);
buttonNext = findViewById(R.id.buttonNext);
buttonStart.setOnClickListener(this);
buttonStop.setOnClickListener(this);
buttonNext.setOnClickListener(this);
}
public void onClick(View src) {
switch (src.getId()) {
case R.id.buttonStart:
NextPage class
File: NextPage.java
package example.javatpoint.com.androidservice;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
}
}
File: AndroidManifest.xml
<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" />
Output:
The android system consists of five layers and each layer consists of some core
components. Figure 1 shows the architecture of android. From top to down, the core
components are: Applications, Application Framework, Native C libraries, Android
Runtime Environment (JVM), HAL (Hardware Abstract Layer), Linux Kernel.
1) Applications. Application layer consists of many core Java-based applications,
such as calendar, web browser, SMS application, E-mail, etc.
2) Application Framework. Application framework consists of many components and Java
classes to allow android application developers to develop various kinds of applications.
By using Java language, it hides the internal implementation of system core functions and
provides the developers an easy-use API. Basically, it includes Java core class and some
special components of android. Some typical components are as follows: View (List,
Grids), Content Provider, Resource Manager, Activity Manager.
3) Native C Libraries. In Native C library layer, it consists of many C/C++ libraries. And
the core functions of android are implemented by those libraries. Some typical core
libraries are as follows: Bionic C lib, OpenCore, SQLite, Surface Manager, WebKit, 3D
library.
4) Android Runtime Environment. Runtime environment consists of Dalvik Java virtual
machine and some implementations of Java core libraries.
5) HAL. This layer abstracts different kinds of hardwares and provides an unified
program interface to Native C libraries. HAL can make Android port on different
platforms more easily.
6) Linux Kernel. Android’s core system functions (e.g., safety management, RAM
management, process management, network stack) depend on Linux kernels.
Java classes call the Native C library Libmedia through Java JNI (Java Native Interface).
Libmedia library communicates with Media Server guard process through Android’s
Binder IPC (inter process communication) mechanism. Media Server process creates the
corresponding multimedia service according to the Java multimedia applications. The
whole communication between Libmedia and Media Server forms a Client/Server model.
In Media Server guard process, it calls OpenCore multimedia engine to realize the specific
multimedia processing functions. And the OpenCore engine refers to the PVPlayer and
PVAuthor.
We can play and control the audio files in android by the help of MediaPlayer class.
Here, we are going to see a simple example to play the audio file. In the next page, we will
see the example to control the audio playback like start, stop, pause etc.
MediaPlayer class
There are many methods of MediaPlayer class. Some of them are as follows:
Method Description
public void setDataSource(String path) Sets the data source (file path or http url) to use.
public void prepare() Prepares the player for playback synchronously.
Activity class
Let's write the code of to play the audio file. Here, we are going to play maine.mp3 file
located inside the sdcard/Music directory.
File: MainActivity.java
package com.example.audiomediaplayer1;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.MediaController;
import android.widget.VideoView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}catch(Exception e){e.printStackTrace();}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Let's see a simple example to start, stop and pause the audio play.
activity_main.xml
Drag three buttons from pallete to start, stop and pause the audio play. Now the xml file
will look like this:
File: MainActivity.java
<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="30dp"
android:text="Audio Controller" />
<Button
android:id="@+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="48dp"
android:text="start" />
Activity class
Let's write the code to start, pause and stop the audio player.
File: MainActivity.java
package com.example.audioplay;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
Button start,pause,stop;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MediaController class
VideoView class
Method Description
public void setMediaController(MediaController Sets the media controller to the video
controller) view.
public void setVideoURI (Uri uri) Sets the URI of the video file.
public void start() Starts the video view.
public void stopPlayback() Stops the playback.
public void pause() Pauses the playback.
public void suspend() Suspends the playback.
public void resume() Resumes the playback.
public void seekTo(int millis) Seeks to specified time in miliseconds.
Drag the VideoView from the pallete, now the activity_main.xml file will like this:
File: activity_main.xml
<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<VideoView
android:id="@+id/videoView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true" />
</RelativeLayout>
Activity class
Let's write the code of to play the video file. Here, we are going to play 1.mp4 file located
inside the sdcard/media directory.
File: MainActivity.java
package com.example.video1;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.MediaController;
import android.widget.VideoView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
VideoView videoView =(VideoView)findViewById(R.id.videoView1);
Text To Speech
Android allows you convert your text into voice. Not only you can convert it but it also
allows you to speak text in variety of different languages.
Android provides TextToSpeech class for this purpose. In order to use this class, you
need to instantiate an object of this class and also specify the initListener. Its syntax is
given below −
Sr.No Locale
.
1 US
2 CANADA_FRENCH
3 GERMANY
4 ITALY
5 JAPAN
6 CHINA
Once you have set the language, you can call speak method of the class to speak the text.
Its syntax is given below −
Example
The below example demonstrates the use of TextToSpeech class. It crates a basic
application that allows you to set write text and speak it.
To experiment with this example , you need to run this on an actual device.
Step Description
s
1 You will use Android studio to create an Android application under a package
com.example.sairamkrishna.myapplication.
2 Modify src/MainActivity.java file to add TextToSpeech code.
3 Modify layout XML file res/layout/activity_main.xml add any GUI component if
required.
4 Run the application and choose a running android device and install the
application on it and verify the results.
Here is the content of src/MainActivity.java.
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.Locale;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed1=(EditText)findViewById(R.id.editText);
b1=(Button)findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String toSpeak = ed1.getText().toString();
Toast.makeText(getApplicationContext(), toSpeak,Toast.LENGTH_SHORT).show();
t1.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
}
});
}
<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" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_below="@+id/imageView"
android:layout_marginTop="46dp"
android:hint="Enter Text"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text to Speech"
android:id="@+id/button"
android:layout_below="@+id/editText"
android:layout_centerHorizontal="true"
android:layout_marginTop="46dp" />
</RelativeLayout>
Here is the content of Strings.xml.
<resources>
<string name="app_name">My Application</string>
</resources>
Here is the content of AndroidManifest.xml
<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 toolbar. Before starting your
application, android studio will display following window to select an option where you
want to run your Android application.
Select your mobile device as an option and then check your mobile device which will
display following screen.
Now just type some text in the field and click on the text to speech button below. A
notification would appear and text will be spoken. It is shown in the image below −
Now type something else and repeat the step again with different locale. You will again
hear sound. This is shown below −
Android Sensor
Types of Sensors
1) Motion Sensors
These are used to measure acceleration forces and rotational forces along with three
axes.
2) Position Sensors
3) Environmental Sensors
These are used to measure the environmental changes such as temperature, humidity etc.
Android sensor api provides many classes and interface. The important classes and
interfaces of sensor api are as follows:
1) SensorManager class
You can get the instance of SensorManager by calling the method getSystemService() and
passing the SENSOR_SERVICE constant in it.
SensorManager sm = (SensorManager)getSystemService(SENSOR_SERVICE);
2) Sensor class
3) SensorEvent class
Its instance is created by the system. It provides information about the sensor.
4) SensorEventListener interface
It provides two call back methods to get information when sensor values (x,y and z)
change or sensor accuracy changes.
1. A sensor example that prints x, y and z axis values. Here, we are going to see that.
2. A sensor example that changes the background color when device is shuffled. Click
for changing background color of activity sensor example
activity_main.xml
File: activity_main.xml
<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
Activity class
Let's write the code that prints values of x axis, y axis and z axis.
File: MainActivity.java
package com.example.sensorsimple;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import android.hardware.SensorManager;
import android.hardware.SensorEventListener;
import android.hardware.SensorEvent;
import android.hardware.Sensor;
import java.util.List;
public class MainActivity extends Activity {
SensorManager sm = null;
TextView textView1 = null;
List list;
SensorEventListener sel = new SensorEventListener(){
public void onAccuracyChanged(Sensor sensor, int accuracy) {}
public void onSensorChanged(SensorEvent event) {
float[] values = event.values;
textView1.setText("x: "+values[0]+"\ny: "+values[1]+"\nz: "+values[2]);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Output:
In this example, we are going to create a sensor application that changes the background
color of activity when device is shaked.
For understanding about sensor basics, visit the previous page that provides details about
sensor api.
activity_main.xml
File: 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"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Shake to switch color" />
</RelativeLayout>
Activity class
File: MainActivity.java
package com.example.sensor;
import android.app.Activity;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity implements SensorEventListener{
private SensorManager sensorManager;
private boolean isColor = false;
AsyncTask
Android AsyncTask is an abstract class provided by Android which gives us the liberty to
perform heavy tasks in the background and keep the UI thread light thus making the
application more responsive.
Android application runs on a single thread when launched. Due to this single thread
model tasks that take longer time to fetch the response can make the application non-
responsive. To avoid this we use android AsyncTask to perform the heavy tasks in
background on a dedicated thread and passing the results back to the UI thread. Hence
use of AsyncTask in android application keeps the UI thread responsive at all times.
The basic methods used in an android AsyncTask class are defined below :
The three generic types used in an android AsyncTask class are given below :
Params : The type of the parameters sent to the task upon execution
Progress : The type of the progress units published during the background computation
Result : The type of the result of the background computation
To start an AsyncTask the following snippet must be present in the MainActivity class :
In the above snippet we’ve used a sample classname that extends AsyncTask and execute
method is used to start the background thread.
Note:
In this tutorial we’ll implement an AsyncTask that makes a process to go to sleep for a
given period of time as set by the user.
The xml layout is defined in the activity_main.xml and its given below:
activity_main.xml
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="@+id/tv_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="10pt"
android:textColor="#444444"
android:layout_alignParentLeft="true"
android:layout_marginRight="9dip"
android:layout_marginTop="20dip"
android:layout_marginLeft="10dip"
android:text="Sleep time in Seconds:"/>
<EditText
android:id="@+id/in_time"
android:layout_width="150dip"
android:layout_height="wrap_content"
android:background="@android:drawable/editbox_background"
android:layout_toRightOf="@id/tv_time"
android:layout_alignTop="@id/tv_time"
android:inputType="number"
/>
<Button
android:id="@+id/btn_run"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Run Async task"
android:layout_below="@+id/in_time"
android:layout_centerHorizontal="true"
android:layout_marginTop="64dp" />
<TextView
android:id="@+id/tv_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="7pt"
android:layout_below="@+id/btn_run"
android:layout_centerHorizontal="true" />
</RelativeLayout>
In the above layout we’ve used a predefined drawable as the border of the EditText.
package com.journaldev.asynctask;
import android.app.ProgressDialog;
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.EditText;
import android.widget.TextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
time = (EditText) findViewById(R.id.in_time);
button = (Button) findViewById(R.id.btn_run);
finalResult = (TextView) findViewById(R.id.tv_result);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AsyncTaskRunner runner = new AsyncTaskRunner();
String sleepTime = time.getText().toString();
runner.execute(sleepTime);
}
});
}
@Override
protected String doInBackground(String... params) {
publishProgress("Sleeping..."); // Calls onProgressUpdate()
try {
int time = Integer.parseInt(params[0])*1000;
Thread.sleep(time);
resp = "Slept for " + params[0] + " seconds";
} catch (InterruptedException e) {
@Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
progressDialog.dismiss();
finalResult.setText(result);
}
@Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MainActivity.this,
"ProgressDialog",
"Wait for "+time.getText().toString()+ " seconds");
}
@Override
protected void onProgressUpdate(String... text) {
finalResult.setText(text[0]);
}
}
}
The images given below are the outputs produced by the project where the time set by
the user is 5 seconds.
Audio Capture
Android has a built in microphone through which you can capture audio and store it , or
play it in your phone. There are many ways to do that but the most common way is
through MediaRecorder class.
Android provides MediaRecorder class to record audio or video. In order to use
MediaRecorder class ,you will first create an instance of MediaRecorder class. Its syntax
is given below.
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
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.
Sr.No Method & description
1 setAudioSource()
This method specifies the source of audio to be recorded
2 setVideoSource()
This method specifies the source of video to be recorded
3 setOutputFormat()
This method specifies the audio format in which audio to be stored
4 setAudioEncoder()
This method specifies the audio encoder to be used
5 setOutputFile()
This method configures the path to the file into which the recorded audio is
to be stored
6 stop()
This method stops the recording process.
7 release()
This method should be called when the recorder instance is needed.
Example
This example provides demonstration of MediaRecorder class to capture audio and then
MediaPlayer class to play that recorded audio.
To experiment with this example , you need to run this on an actual device.
Steps Description
1 You will use Android studio IDE to create an Android application and name it
as AudioCapture under a package com.example.sairamkrishna.myapplication.
2 Modify src/MainActivity.java file to add AudioCapture code
3 Modify layout XML file res/layout/activity_main.xml add any GUI component
if required.
4 Modify AndroidManifest.xml to add necessary permissions.
5 Run the application and choose a running android device and install the
application on it and verify the results.
Here is the content of src/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.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 =
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++ ;
}
@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"
/>
<resources>
<string name="app_name">My Application</string>
</resources>
Here is the content of AndroidManifest.xml
<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.
Camera In Android
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.
1. By Camera Intent
2. By Camera API
1.Camera Manager: This is used to get all the cameras available in the device like front
camera back camera each having the camera id.
3.CaptureRequest: You can create a capture request from camera device to capture
images.
Before you start development on your application you have to make sure that your
Manifest has appropriate declarations in it that will allow you to use Camera feature in
your Application.
<uses-permission android:name="android.permission.CAMERA"/>
activity_main.xml
Drag one imageview and one button from the pallete, now the xml file will look like this:
File: activity_main.xml
<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Take a Photo" >
</Button>
<ImageView
android:id="@+id/imageView1"
Activity class
Let's write the code to capture image using camera and displaying it on the image view.
File: MainActivity.java
package com.example.simplecamera;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
private static final int CAMERA_REQUEST = 1888;
ImageView imageView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
photoButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAP
TURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
}
Output:
Bluetooth is a way to exchange data with other devices wirelessly. Android provides
Bluetooth API to perform several tasks such as:
The android.bluetooth package provides a lot of interfaces classes to work with bluetooth
such as:
o BluetoothAdapter
o BluetoothDevice
o BluetoothSocket
o BluetoothServerSocket
o BluetoothClass
o BluetoothProfile
o BluetoothProfile.ServiceListener
o BluetoothHeadset
o BluetoothA2dp
o BluetoothHealth
o BluetoothHealthCallback
o BluetoothHealthAppConfiguration
android-preferences-example
BluetoothAdapter class
By the help of BluetoothAdapter class, we can perform fundamental tasks such as initiate
device discovery, query a list of paired (bonded) devices, create a BluetoothServerSocket
instance to listen for connection requests etc.
o String ACTION_REQUEST_ENABLE
o String ACTION_REQUEST_DISCOVERABLE
o String ACTION_DISCOVERY_STARTED
o String ACTION_DISCOVERY_FINISHED
You need to write few lines of code only, to enable or disable the bluetooth.
activity_main.xml
Drag one textview and three buttons from the pallete, now the activity_main.xml file will
like this:
File: activity_main.xml
<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView android:text=""
android:id="@+id/out"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="30dp"
android:layout_marginTop="49dp"
android:text="TURN_ON" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
Department of Computer Engineering 104 Mrs. Kapadnis N.Y.
Mobile Application Development Unit-V Activity and Multimedia
with Databases
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_below="@+id/button1"
android:layout_marginTop="27dp"
android:text="DISCOVERABLE" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button2"
android:layout_below="@+id/button2"
android:layout_marginTop="28dp"
android:text="TURN_OFF" />
</RelativeLayout>
Provide Permission
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
File: AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:androclass="http://schemas.android.com/apk/res/android"
package="com.example.bluetooth"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
Department of Computer Engineering 105 Mrs. Kapadnis N.Y.
Mobile Application Development Unit-V Activity and Multimedia
with Databases
android:theme="@style/AppTheme" >
<activity
android:name="com.example.bluetooth.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>
Activity class
Let's write the code to enable, disable and make bluetooth discoverable.
File: MainActivity.java
package com.example.bluetooth;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final int REQUEST_ENABLE_BT = 0;
private static final int REQUEST_DISCOVERABLE_BT = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView out=(TextView)findViewById(R.id.out);
final Button button1 = (Button) findViewById(R.id.button1);
Android Animation
Animation in android apps is the process of creating motion and shape change.
We create a resource directory under the res folder names anim to keep all the xml files
containing the animation logic. Following is a sample xml file showing an android
animation code logic.
sample_animation.xml
<scale xmlns:android="https://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_decelerate_interpolator"
android:duration="300"
android:fillAfter="true"
android:fromXScale="0.0"
android:fromYScale="0.0"
android:toXScale="1.0"
android:toYScale="1.0" />
android:toTRANSFORMATION
Our aim is to show an animation when any widget(lets say TextView) is clicked. For that
we need to use the Animation Class. The xml file that contains the animation logic is
loaded using AnimationUtils class by calling the loadAnimation() function. The below
snippet shows this implementation.
Animation animation;
animation = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.sample_animation);
sampleTextView.startAnimation(animation);
This is only needed if we wish to listen to events like start, end or repeat. For this the
activity must implement AnimationListener and the following methods need to
overridden.
As you can see, we’ve included the xml of all the major types of animations covered above.
Here I am providing sample code for most of the common android animations.
Fade In Animation
fade_in.xml
<set xmlns:android="https://schemas.android.com/apk/res/android"
android:fillAfter="true" >
<alpha
android:duration="1000"
android:interpolator="@android:anim/accelerate_interpolator"
android:toAlpha="1.0" />
</set>
Here alpha references the opacity of an object. An object with lower alpha values is more
transparent, while an object with higher alpha values is less transparent, more opaque.
Fade in animation is nothing but increasing alpha value from 0 to 1.
fade_out.xml
<set xmlns:android="https://schemas.android.com/apk/res/android"
android:fillAfter="true" >
<alpha
android:duration="1000"
android:fromAlpha="1.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:toAlpha="0.0" />
</set>
Fade out android animation is exactly opposite to fade in, where we need to decrease the
alpha value from 1 to 0.
Cross fading is performing fade in animation on one TextView while other TextView is
fading out. This can be done by using fade_in.xml and fade_out.xml on the two TextViews.
The code will be discussed in the MainActivity.java
blink.xml
<set xmlns:android="https://schemas.android.com/apk/res/android">
<alpha android:fromAlpha="0.0"
android:toAlpha="1.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:duration="600"
android:repeatMode="reverse"
android:repeatCount="infinite"/>
</set>
Here fade in and fade out are performed infinitely in reverse mode each time.
Zoom In Animation
zoom_in.xml
<set xmlns:android="https://schemas.android.com/apk/res/android"
android:fillAfter="true" >
<scale
xmlns:android="https://schemas.android.com/apk/res/android"
android:duration="1000"
android:fromXScale="1"
android:fromYScale="1"
android:pivotX="50%"
android:pivotY="50%"
android:toXScale="3"
</scale>
</set>
zoom_out.xml
<set xmlns:android="https://schemas.android.com/apk/res/android"
android:fillAfter="true" >
<scale
xmlns:android="https://schemas.android.com/apk/res/android"
android:duration="1000"
android:fromXScale="1.0"
android:fromYScale="1.0"
android:pivotX="50%"
android:pivotY="50%"
android:toXScale="0.5"
android:toYScale="0.5" >
</scale>
</set>
rotate.xml
<set xmlns:android="https://schemas.android.com/apk/res/android">
<rotate android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:duration="600"
android:repeatMode="restart"
android:repeatCount="infinite"
android:interpolator="@android:anim/cycle_interpolator"/>
</set>
Move Animation
move.xml
<set
xmlns:android="https://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator"
android:fillAfter="true">
<translate
android:fromXDelta="0%p"
android:toXDelta="75%p"
</set>
Slide Up Animation
slide_up.xml
<set xmlns:android="https://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>
slide_down.xml
<set xmlns:android="https://schemas.android.com/apk/res/android"
android:fillAfter="true">
<scale
android:fromXScale="1.0"
android:fromYScale="0.0"
android:toXScale="1.0"
android:toYScale="1.0" />
</set>
Bounce Animation
bounce.xml
<set xmlns:android="https://schemas.android.com/apk/res/android"
android:fillAfter="true"
android:interpolator="@android:anim/bounce_interpolator">
<scale
android:duration="500"
android:fromXScale="1.0"
android:fromYScale="0.0"
android:toXScale="1.0"
android:toYScale="1.0" />
</set>
Sequential Animation
sequential.xml
<set xmlns:android="https://schemas.android.com/apk/res/android"
android:fillAfter="true"
android:interpolator="@android:anim/linear_interpolator" >
<translate
android:duration="800"
android:fillAfter="true"
android:fromXDelta="0%p"
android:startOffset="300"
android:toXDelta="75%p" />
<translate
android:duration="800"
android:fillAfter="true"
android:fromYDelta="0%p"
android:startOffset="1100"
android:toYDelta="70%p" />
<translate
android:duration="800"
android:fillAfter="true"
android:fromXDelta="0%p"
android:startOffset="1900"
android:toXDelta="-75%p" />
<translate
android:duration="800"
android:fromYDelta="0%p"
android:startOffset="2700"
android:toYDelta="-70%p" />
<rotate
android:duration="1000"
android:fromDegrees="0"
android:interpolator="@android:anim/cycle_interpolator"
android:pivotX="50%"
android:pivotY="50%"
android:startOffset="3800"
android:repeatCount="infinite"
android:repeatMode="restart"
android:toDegrees="360" />
</set>
Together Animation
together.xml
<set xmlns:android="https://schemas.android.com/apk/res/android"
android:fillAfter="true"
android:interpolator="@android:anim/linear_interpolator" >
<scale
xmlns:android="https://schemas.android.com/apk/res/android"
android:duration="4000"
android:fromXScale="1"
android:fromYScale="1"
android:pivotX="50%"
android:pivotY="50%"
android:toXScale="4"
android:toYScale="4" >
</scale>
<rotate
android:duration="500"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:repeatCount="infinite"
android:repeatMode="restart"
android:toDegrees="360" />
</set>
Android Animation is used to give the UI a rich look and feel. Animations in android apps
can be performed through XML or android code. In this android animation tutorial we’ll
go with XML codes for adding animations into our application.
Animation in android apps is the process of creating motion and shape change. The basic
ways of animation that we’ll look upon in this tutorial are:
1. Fade In Animation
2. Fade Out Animation
3. Cross Fading Animation
4. Blink Animation
5. Zoom In Animation
6. Zoom Out Animation
7. Rotate Animation
8. Move Animation
9. Slide Up Animation
10. Slide Down Animation
11. Bounce Animation
12. Sequential Animation
13. Together Animation
We create a resource directory under the res folder names anim to keep all the xml files
containing the animation logic. Following is a sample xml file showing an android
animation code logic.
sample_animation.xml
<scale xmlns:android="https://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_decelerate_interpolator"
android:duration="300"
android:fillAfter="true"
android:fromXScale="0.0"
android:fromYScale="0.0"
android:toXScale="1.0"
android:toYScale="1.0" />
android:fromTRANSFORMATION
android:toTRANSFORMATION
Our aim is to show an animation when any widget(lets say TextView) is clicked. For that
we need to use the Animation Class. The xml file that contains the animation logic is
loaded using AnimationUtils class by calling the loadAnimation() function. The below
snippet shows this implementation.
Animation animation;
animation = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.sample_animation);
sampleTextView.startAnimation(animation);
This is only needed if we wish to listen to events like start, end or repeat. For this the
activity must implement AnimationListener and the following methods need to
overridden.
As you can see, we’ve included the xml of all the major types of animations covered above.
Here I am providing sample code for most of the common android animations.
Fade In Animation
fade_in.xml
<set xmlns:android="https://schemas.android.com/apk/res/android"
android:fillAfter="true" >
<alpha
android:duration="1000"
android:fromAlpha="0.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:toAlpha="1.0" />
</set>
Here alpha references the opacity of an object. An object with lower alpha values is more
transparent, while an object with higher alpha values is less transparent, more opaque.
Fade in animation is nothing but increasing alpha value from 0 to 1.
fade_out.xml
<set xmlns:android="https://schemas.android.com/apk/res/android"
android:fillAfter="true" >
<alpha
android:duration="1000"
android:fromAlpha="1.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:toAlpha="0.0" />
</set>
Cross fading is performing fade in animation on one TextView while other TextView is
fading out. This can be done by using fade_in.xml and fade_out.xml on the two TextViews.
The code will be discussed in the MainActivity.java
Blink Animation
blink.xml
<set xmlns:android="https://schemas.android.com/apk/res/android">
<alpha android:fromAlpha="0.0"
android:toAlpha="1.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:duration="600"
android:repeatMode="reverse"
android:repeatCount="infinite"/>
</set>
Here fade in and fade out are performed infinitely in reverse mode each time.
Zoom In Animation
zoom_in.xml
<set xmlns:android="https://schemas.android.com/apk/res/android"
android:fillAfter="true" >
<scale
xmlns:android="https://schemas.android.com/apk/res/android"
android:fromXScale="1"
android:fromYScale="1"
android:pivotX="50%"
android:pivotY="50%"
android:toXScale="3"
android:toYScale="3" >
</scale>
</set>
zoom_out.xml
<set xmlns:android="https://schemas.android.com/apk/res/android"
android:fillAfter="true" >
<scale
xmlns:android="https://schemas.android.com/apk/res/android"
android:duration="1000"
android:fromXScale="1.0"
android:fromYScale="1.0"
android:pivotX="50%"
android:pivotY="50%"
android:toXScale="0.5"
android:toYScale="0.5" >
</set>
Rotate Animation
rotate.xml
<set xmlns:android="https://schemas.android.com/apk/res/android">
<rotate android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:duration="600"
android:repeatMode="restart"
android:repeatCount="infinite"
android:interpolator="@android:anim/cycle_interpolator"/>
</set>
Move Animation
move.xml
<set
xmlns:android="https://schemas.android.com/apk/res/android"
android:fillAfter="true">
<translate
android:fromXDelta="0%p"
android:toXDelta="75%p"
android:duration="800" />
</set>
Slide Up Animation
slide_up.xml
<set xmlns:android="https://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>
slide_down.xml
<set xmlns:android="https://schemas.android.com/apk/res/android"
android:fillAfter="true">
<scale
android:duration="500"
android:fromXScale="1.0"
android:fromYScale="0.0"
android:toXScale="1.0"
android:toYScale="1.0" />
</set>
Bounce Animation
bounce.xml
<set xmlns:android="https://schemas.android.com/apk/res/android"
android:fillAfter="true"
android:interpolator="@android:anim/bounce_interpolator">
<scale
android:duration="500"
android:fromXScale="1.0"
android:fromYScale="0.0"
android:toYScale="1.0" />
</set>
Sequential Animation
sequential.xml
<set xmlns:android="https://schemas.android.com/apk/res/android"
android:fillAfter="true"
android:interpolator="@android:anim/linear_interpolator" >
<translate
android:duration="800"
android:fillAfter="true"
android:fromXDelta="0%p"
android:startOffset="300"
android:toXDelta="75%p" />
<translate
android:duration="800"
android:fillAfter="true"
android:fromYDelta="0%p"
android:startOffset="1100"
android:toYDelta="70%p" />
<translate
Department of Computer Engineering 129 Mrs. Kapadnis N.Y.
Mobile Application Development Unit-V Activity and Multimedia
with Databases
android:duration="800"
android:fillAfter="true"
android:fromXDelta="0%p"
android:startOffset="1900"
android:toXDelta="-75%p" />
<translate
android:duration="800"
android:fillAfter="true"
android:fromYDelta="0%p"
android:startOffset="2700"
android:toYDelta="-70%p" />
<rotate
android:duration="1000"
android:fromDegrees="0"
android:interpolator="@android:anim/cycle_interpolator"
android:pivotX="50%"
android:pivotY="50%"
android:startOffset="3800"
android:repeatCount="infinite"
android:repeatMode="restart"
android:toDegrees="360" />
</set>
together.xml
<set xmlns:android="https://schemas.android.com/apk/res/android"
android:fillAfter="true"
android:interpolator="@android:anim/linear_interpolator" >
<scale
xmlns:android="https://schemas.android.com/apk/res/android"
android:duration="4000"
android:fromXScale="1"
android:fromYScale="1"
android:pivotX="50%"
android:pivotY="50%"
android:toXScale="4"
android:toYScale="4" >
</scale>
<rotate
android:duration="500"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:repeatCount="infinite"
android:toDegrees="360" />
</set>
Code
activity_main.xml
<ScrollView xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btnFadeIn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Fade In"
android:id="@+id/txt_fade_in"
android:layout_alignBottom="@+id/btnFadeIn"
android:layout_alignLeft="@+id/txt_fade_out"
android:layout_alignStart="@+id/txt_fade_out" />
<Button
android:id="@+id/btnFadeOut"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_below="@id/btnFadeIn"
<Button
android:id="@+id/btnCrossFade"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_below="@id/btnFadeOut"
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="@+id/txt_out"
android:visibility="gone"
android:layout_gravity="center_horizontal"
android:layout_alignTop="@+id/txt_in"
android:layout_alignLeft="@+id/txt_in"
android:layout_alignStart="@+id/txt_in" />
<Button
android:id="@+id/btnBlink"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_below="@id/btnCrossFade"
android:text="Blink" />
<Button
android:id="@+id/btnZoomIn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_below="@id/btnBlink"
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Blink"
android:id="@+id/txt_blink"
android:layout_gravity="center_horizontal"
android:layout_alignBottom="@+id/btnBlink"
android:layout_alignLeft="@+id/txt_zoom_in"
android:layout_alignStart="@+id/txt_zoom_in" />
<Button
android:id="@+id/btnZoomOut"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_below="@id/btnZoomIn"
<Button
android:id="@+id/btnRotate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_below="@id/btnZoomOut"
<Button
android:id="@+id/btnMove"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_below="@id/btnRotate"
android:text="Move" />
<Button
android:id="@+id/btnSlideUp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_below="@id/btnMove"
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Fade Out"
android:id="@+id/txt_fade_out"
android:layout_gravity="center_horizontal"
android:layout_alignBottom="@+id/btnFadeOut"
android:layout_alignLeft="@+id/txt_in"
<Button
android:id="@+id/btnSlideDown"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_below="@id/btnSlideUp"
<Button
android:id="@+id/btnBounce"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_below="@id/btnSlideDown"
android:text="Bounce" />
<Button
android:id="@+id/btnSequential"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_below="@id/btnBounce"
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/btnSequential"
android:layout_margin="5dp"
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="@+id/txt_in"
android:layout_gravity="center_horizontal"
android:layout_alignBottom="@+id/btnCrossFade"
android:layout_alignLeft="@+id/txt_blink"
android:layout_alignStart="@+id/txt_blink" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Zoom In"
android:id="@+id/txt_zoom_in"
android:layout_alignBottom="@+id/btnZoomIn"
android:layout_alignLeft="@+id/txt_zoom_out"
android:layout_alignStart="@+id/txt_zoom_out" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Zoom Out"
android:id="@+id/txt_zoom_out"
android:layout_alignBottom="@+id/btnZoomOut"
android:layout_toRightOf="@+id/btnSequential"
android:layout_toEndOf="@+id/btnSequential" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Rotate"
android:id="@+id/txt_rotate"
android:layout_above="@+id/btnMove"
android:layout_toRightOf="@+id/btnSequential"
android:layout_toEndOf="@+id/btnSequential" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Move"
android:id="@+id/txt_move"
android:layout_alignLeft="@+id/txt_slide_up"
android:layout_alignStart="@+id/txt_slide_up" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Slide Up"
android:id="@+id/txt_slide_up"
android:layout_alignBottom="@+id/btnSlideUp"
android:layout_toRightOf="@+id/btnSequential"
android:layout_toEndOf="@+id/btnSequential" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Slide Down"
android:id="@+id/txt_slide_down"
android:layout_alignBottom="@+id/btnSlideDown"
android:layout_alignLeft="@+id/txt_slide_up"
android:layout_alignStart="@+id/txt_slide_up" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bounce"
android:id="@+id/txt_bounce"
android:layout_alignBottom="@+id/btnBounce"
android:layout_alignLeft="@+id/txt_slide_down"
android:layout_alignStart="@+id/txt_slide_down" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Sequential"
android:id="@+id/txt_seq"
android:layout_alignBottom="@+id/btnSequential"
android:layout_alignLeft="@+id/txt_bounce"
android:layout_alignStart="@+id/txt_bounce" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Together"
android:id="@+id/txt_tog"
android:layout_alignBottom="@+id/btnTogether"
android:layout_toRightOf="@+id/btnSequential"
android:layout_toEndOf="@+id/btnSequential" />
</ScrollView>
package com.journaldev.animations;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.TextView;
Animation
animFadeIn,animFadeOut,animBlink,animZoomIn,animZoomOut,animRotate
,animMove,animSlideUp,animSlideDown,animBounce,animSequential,animTogethe
r,animCrossFadeIn,animCrossFadeOut;
TextView
txtFadeIn,txtFadeOut,txtBlink,txtZoomIn,txtZoomOut,txtRotate,txtMove,txtSlideUp,
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtFadeIn=(TextView)findViewById(R.id.txt_fade_in);
txtFadeOut=(TextView)findViewById(R.id.txt_fade_out);
txtBlink=(TextView)findViewById(R.id.txt_blink);
txtZoomIn=(TextView)findViewById(R.id.txt_zoom_in);
txtZoomOut=(TextView)findViewById(R.id.txt_zoom_out);
txtRotate=(TextView)findViewById(R.id.txt_rotate);
txtMove=(TextView)findViewById(R.id.txt_move);
txtSlideDown=(TextView)findViewById(R.id.txt_slide_down);
txtBounce=(TextView)findViewById(R.id.txt_bounce);
txtSeq=(TextView)findViewById(R.id.txt_seq);
txtTog=(TextView)findViewById(R.id.txt_tog);
txtIn=(TextView)findViewById(R.id.txt_in);
txtOut=(TextView)findViewById(R.id.txt_out);
animFadeIn = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.fade_in);
animFadeIn = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.fade_in);
// fade in
btnFadeIn.setOnClickListener(new View.OnClickListener() {
@Override
txtFadeIn.setVisibility(View.VISIBLE);
txtFadeIn.startAnimation(animFadeIn);
});
animFadeOut = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.fade_out);
// fade out
btnFadeOut.setOnClickListener(new View.OnClickListener() {
txtFadeOut.setVisibility(View.VISIBLE);
txtFadeOut.startAnimation(animFadeOut);
});
animCrossFadeIn = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.fade_in);
animCrossFadeOut = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.fade_out);
// cross fade
btnCrossFade.setOnClickListener(new View.OnClickListener() {
@Override
txtOut.setVisibility(View.VISIBLE);
txtOut.startAnimation(animCrossFadeIn);
txtIn.startAnimation(animCrossFadeOut);
});
animBlink = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.blink);
// blink
btnBlink.setOnClickListener(new View.OnClickListener() {
@Override
txtBlink.setVisibility(View.VISIBLE);
txtBlink.startAnimation(animBlink);
});
animZoomIn = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.zoom_in);
// Zoom In
btnZoomIn.setOnClickListener(new View.OnClickListener() {
@Override
txtZoomIn.setVisibility(View.VISIBLE);
txtZoomIn.startAnimation(animZoomIn);
});
animZoomOut = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.zoom_out);
// Zoom Out
btnZoomOut.setOnClickListener(new View.OnClickListener() {
@Override
txtZoomOut.setVisibility(View.VISIBLE);
txtZoomOut.startAnimation(animZoomOut);
});
animRotate = AnimationUtils.loadAnimation(getApplicationContext(),
// Rotate
btnRotate.setOnClickListener(new View.OnClickListener() {
@Override
txtRotate.startAnimation(animRotate);
});
animMove = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.move);
// Move
btnMove.setOnClickListener(new View.OnClickListener() {
@Override
txtMove.startAnimation(animMove);
});
animSlideUp = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.slide_up);
// Slide Up
btnSlideUp.setOnClickListener(new View.OnClickListener() {
@Override
txtSlideUp.startAnimation(animSlideUp);
});
R.anim.slide_down);
// Slide Down
btnSlideDown.setOnClickListener(new View.OnClickListener() {
@Override
txtSlideDown.startAnimation(animSlideDown);
});
animBounce = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.bounce);
// Slide Down
btnBounce.setOnClickListener(new View.OnClickListener() {
@Override
txtBounce.startAnimation(animBounce);
});
animSequential = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.sequential);
// Sequential
btnSequential.setOnClickListener(new View.OnClickListener() {
@Override
txtSeq.startAnimation(animSequential);
animTogether = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.together);
// Together
btnTogether.setOnClickListener(new View.OnClickListener() {
@Override
txtTog.startAnimation(animTogether);
});
The together animation is seen in the image above. Note that these animation when run
on an emulator wont be smooth, so it’s recommended to run the application on a normal
device.
Android SQLite is the mostly preferred way to store data for android applications. For
many applications, SQLite is the apps backbone whether it’s used directly or via some
third-party wrapper. Below is the final app we will create today using Android SQLite
database.
Android SQLite is a very lightweight database which comes with Android OS. Android
SQLite combines a clean SQL interface with a very small memory footprint and decent
speed. For Android, SQLite is “baked into” the Android runtime, so every Android
application can create its own SQLite databases.
Android SQLite native API is not JDBC, as JDBC might be too much overhead for a
memory-limited smartphone. Once a database is created successfully its located
in data/data//databases/ accessible from Android Device Monitor.
Android has features available to handle changing database schemas, which mostly
depend on using the SQLiteOpenHelper class.
1. When the application runs the first time – At this point, we do not yet have a database. So
we will have to create the tables, indexes, starter data, and so on.
2. When the application is upgraded to a newer schema – Our database will still be on the
old schema from the older edition of the app. We will have option to alter the database
schema to match the needs of the rest of the app.
1. Constructor : This takes the Context (e.g., an Activity), the name of the database, an
optional cursor factory (we’ll discuss this later), and an integer representing the version
of the database schema you are using (typically starting from 1 and increment later).
2.
public DatabaseHelper(Context context) {
3. onCreate(SQLiteDatabase db) : It’s called when there is no database and the app needs
one. It passes us a SQLiteDatabase object, pointing to a newly-created database, that we
can populate with tables and initial data.
4. onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) : It’s called when the
schema version we need does not match the schema version of the database, It passes us
Before performing any database operations like insert, update, delete records in a table,
first open the database connection by calling getWritableDatabase() method as shown
below:
database = dbHelper.getWritableDatabase();
return this;
dbHelper.close();
The following code snippet shows how to insert a new record in the android SQLite
database.
contentValue.put(DatabaseHelper.SUBJECT, name);
contentValue.put(DatabaseHelper.DESC, desc);
Content Values creates an empty set of values using the given initial size. We’ll discuss
the other instance values when we jump into the coding part.
contentValues.put(DatabaseHelper.SUBJECT, name);
contentValues.put(DatabaseHelper.DESC, desc);
return i;
A Cursor represents the entire result set of the query. Once the query is fetched a call
to cursor.moveToFirst() is made. Calling moveToFirst() does two things:
It allows us to test whether the query returned an empty set (by testing the return value)
It moves the cursor to the first result (when the set is not empty)
if (cursor != null) {
cursor.moveToFirst();
return cursor;
Let’s jump to our project that uses SQLite to store some meaningful data.
package com.journaldev.sqlite;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
// Table Name
// Table columns
// Database Information
// database version
private static final String CREATE_TABLE = "create table " + TABLE_NAME + "(" + _ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + SUBJECT + " TEXT NOT NULL, "
+ DESC + " TEXT);";
@Override
db.execSQL(CREATE_TABLE);
@Override
onCreate(db);
The DBManager classes is where the DatabaseHelper is initialized and the CRUD
Operations are defined. Below is the code for this class:
package com.journaldev.sqlite;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public DBManager(Context c) {
context = c;
database = dbHelper.getWritableDatabase();
return this;
dbHelper.close();
contentValue.put(DatabaseHelper.SUBJECT, name);
contentValue.put(DatabaseHelper.DESC, desc);
if (cursor != null) {
cursor.moveToFirst();
return cursor;
contentValues.put(DatabaseHelper.SUBJECT, name);
contentValues.put(DatabaseHelper.DESC, desc);
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:dividerHeight="1dp"
android:padding="10dp" >
</ListView>
<TextView
android:id="@+id/empty"
android:layout_width="wrap_content"
android:layout_centerInParent="true"
android:text="@string/empty_list_text" />
</RelativeLayout>
Here a ListView component is defined to included the records stored in the database.
Initially the ListView would be empty hence a TextView is used to display the same.
CountryListActivity.java
package com.journaldev.sqlite;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
DatabaseHelper.SUBJECT, DatabaseHelper.DESC };
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_emp_list);
dbManager.open();
listView.setEmptyView(findViewById(R.id.empty));
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
@Override
String id = idTextView.getText().toString();
modify_intent.putExtra("title", title);
modify_intent.putExtra("desc", desc);
modify_intent.putExtra("id", id);
startActivity(modify_intent);
});
@Override
getMenuInflater().inflate(R.menu.main, menu);
return true;
@Override
int id = item.getItemId();
if (id == R.id.add_record) {
startActivity(add_mem);
return super.onOptionsItemSelected(item);
In this activity the DBManager object is invoked to perform the CRUD Operations.
A SimpleCursorAdapter is defined to add elements to the list from the query results that
are returned in an Cursor Object.
On list item click an intent is performed to open the ModifyCountryActivity class.
The menu contains an item to add a new record from the ActionBar. Here again an intent
is performed to open the AddCountryActivity class. Below is menu.xml code.
menu.xml
<menu xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
tools:context="com.example.sqlitesample.MainActivity" >
<item
android:icon="@android:drawable/ic_menu_add"
android:orderInCategory="100"
android:title="@string/add_record"
app:showAsAction="always"/>
</menu>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp" >
<EditText
android:id="@+id/subject_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/enter_title" >
<requestFocus />
</EditText>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/enter_desc"
android:inputType="textMultiLine"
android:minLines="5" >
</EditText>
<Button
android:id="@+id/add_record"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="@string/add_record" />
</LinearLayout>
Two EditText components that take the inputs for country and currency along with a
button to add the values to the database and display it in the ListView are defined.
AddCountryActivity.java
package com.journaldev.sqlite;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
@Override
super.onCreate(savedInstanceState);
setTitle("Add Record");
setContentView(R.layout.activity_add_record);
dbManager.open();
addTodoBtn.setOnClickListener(this);
@Override
switch (v.getId()) {
case R.id.add_record:
dbManager.insert(name, desc);
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(main);
break;
The CRUD operation performed here is adding a new record to the database.
The xml layout and code of ModifyCountryActivity.java file are defined below:
activity_modify_record.xml
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp" >
<EditText
android:id="@+id/subject_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:ems="10"
android:hint="@string/enter_title" />
<EditText
android:id="@+id/description_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/enter_desc"
android:inputType="textMultiLine"
android:minLines="5" >
</EditText>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<Button
android:id="@+id/btn_update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/btn_update" />
<Button
android:id="@+id/btn_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/btn_delete" />
</LinearLayout>
</LinearLayout>
It’s similar to the previous layout except that modify and delete buttons are added.
ModifyCountryActivity.java
package com.journaldev.sqlite;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
@Override
super.onCreate(savedInstanceState);
setTitle("Modify Record");
setContentView(R.layout.activity_modify_record);
dbManager.open();
String id = intent.getStringExtra("id");
_id = Long.parseLong(id);
titleText.setText(name);
descText.setText(desc);
updateBtn.setOnClickListener(this);
deleteBtn.setOnClickListener(this);
@Override
switch (v.getId()) {
case R.id.btn_update:
this.returnHome();
break;
case R.id.btn_delete:
dbManager.delete(_id);
this.returnHome();
break;
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(home_intent);
The CRUD operations performed here are updating and deleting a record.
The below images are the screenshots of the final output of our project.
As we’ve discussed earlier in this tutorial, the database file is stored in the internal
storage that is accessible from the Android Device Monitor as visible in the pic below.
To view this database we need to pull this file from the device to our desktop. This is done
by clicking the menu option in the top right as seen in the image below :
The snippets below show the schema and tables in the browser.
To view the table go to the Browse Data tab on top. The following image is seen:
SQLiteDatabase
Following tutorial helps you to create a database and insert records in it.
Step 1: Instantiate "SQLiteDatabase" object
SQLiteDatabase db;
Before you can use the above object, you must import
the android.database.sqlite.SQLiteDatabase namespace in your application.
This method is used to create/open database. As the name suggests, it will open a
database connection if it is already there, otherwise, it will create a new one.
Example,
db=openOrCreateDatabase("XYZ_Database",SQLiteDatabase.CREATE_IF_NECESSARY,
null);
Arguments:
String path Name of the database
operating mode. Use 0 or "MODE_PRIVATE" for the default operation, or
Int mode "CREATE_IF_NECESSARY" if you like to give an option that "if a
database is not there, create it"
CursorFactory An optional factory class that is called to instantiate a cursor when a
factory query is called
Step 2: Execute DDL command
db.execSQL(String sql) throws SQLException
This command is used to execute a single SQL statement that doesn't return any data
means other than SELECT or any other.
db.execSQL("Create Table Temp (id Integer, name Text)");
In the above example, it takes "CREATE TABLE" statement of SQL. This will create a table
of "Integer" & "Text" fields.
Try and Catch block is required while performing this operation. An exception that
indicates there was an error with SQL parsing or execution.
Step 3: Create an object of "ContentValues" and Initiate it.
ContentValues values=new ContentValues();
This class is used to store a set of values. We can also say, it will map ColumnName and
relevant ColumnValue.
values.put("id", eid.getText().toString());
values.put("name", ename.getText().toString());
insert(String table, String nullColumnHack, ContentValues values)
db.insert("temp", null, values);
Cursor c=db.rawQuery(String sql, String[] selectionArgs)
Cursor c=db.rawQuery("SELECT * FROM temp",null);
Methods
moveToFirst Moves cursor pointer at a first position of a result set
moveToNext Moves cursor pointer next to the current position.
isAfterLast Returns false, if the cursor pointer is not atlast position of a result set.
Example,
c.moveToFirst();
{
//statementâ €¦
c.moveToNext();
}
Note:
If you want to see where your database stored? Follow below instruction.
SQLite Transaction
SQLite is a transactional database that all changes and queries are atomic, consistent,
isolated, and durable (ACID).
SQLite guarantees all the transactions are ACID compliant even if the transaction is
interrupted by a program crash, operation system dump, or power failure to the
computer.
By default, SQLite operates in auto-commit mode. It means that for each command, SQLite
starts, processes, and commits the transaction automatically.
BEGIN TRANSACTION;
COMMIT;
If you do not want to save the changes, you can roll back using
the ROLLBACK or ROLLBACK TRANSACTION statement:
ROLLBACK;
Fourth, transfer 1000 from account 100 to 200, and log the changes to the
table account_changes in a single transaction.
BEGIN TRANSACTION;
UPDATE accounts
SET balance = balance - 1000
WHERE account_no = 100;
UPDATE accounts
SET balance = balance + 1000
WHERE account_no = 200;
UPDATE accounts
SET balance = balance - 20000
WHERE account_no = 100;
ROLLBACK;
Finally, query data from the account_changes table, you will see that the change no #3 is
not there anymore: