[go: up one dir, main page]

0% found this document useful (0 votes)
38 views76 pages

Chapter 5 Activity and Multimedia With Databases

Uploaded by

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

Chapter 5 Activity and Multimedia With Databases

Uploaded by

Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

Mobile Android Development Chp.

5 Ali Karim Sir

Chapter 5. Activity and Multimedia with databases


5.1 Intent, Intent_Filter
5.2 Activity Lifecycle; Broadcast Lifecycle
5.3 Content Provider; Fragments
5.4 Service: Features Of service, Android platform service, Defining new service, Service
Lifecycle, Permission, example of service
5.5 Android System Architecture, Multimedia framework, Play Audio and Video, Text to
speech, Sensors, Async tasks
5.6 Audio Capture, Camera
5.7 Bluetooth, Animation
5.8 SQLite Database, necessity of SQLite, Creation and connection of the database,
extracting value from cursors, Transactions.
-----
5a. Apply the given Intents and service in Application development.
5b. Use Fragment to generate the given multiple activities.
5e. Develop programs to play the given multimedia.
5d. Write the query to perform the given database management operation.

Q. Describe Intent.
Ans:
Intents are the message passing mechanisms to communicate an action. Intent provides a
description of the actions that you want to done. For example, view a message, send an
email,display a photograph, play a video, etc. Intent is very closely related to an activity. For
example, you are accessing you Facebook homepage in your mobile phone and want to view
a recent photograph posted by one of your friends in your homepage. To do so, you must
click on photograph, which results in firing the intent associated with the click activity. This
will lead to a new screen displaying the photograph along with its associated information. In
this example, two activities are involved, your Facebook homepage and the screen displaying
the photograph after the click along with the intent, view photo. A class will describe what a
caller wants to do. He will send this intent to Android’s intent resolver, which finds the most
appropriate activity for the intent. For Example opening a MS-Word document is an intent,
and the ms-word apps will be the perfect activity for that intent (class). An intent is an
abstract description of an operation to be performed. We can be used with startActivity to
begin an Activity, broadcastlntent to send it to any interested startService(Intent) and
BroadcastReceiver components or bindService(Intent, ServiceConnection, int) to
communicate with a background Service.
Pending Intent:
The Pending Intent class provides a mechanism for creating intents that can be called by
another application at a later on time. A Pending Intent is commonly used to package an
Intent that will be fired in response to a future event. Pending Intents can be created in three
types:
a. getActivity(Context,int,Intent,int)
b. getBroadcast(Context, ¡ nt,lntent, int),
e. getService(Contextint,Intent,int);

The Pendinglntent class offers static methods to construct Pending Intents used to
start an Activity,start a Service,or broadcast an Intent. The below code shows the code for
creation of Pendinglntents.
Intent startActivityLrtent=new Intent(this,MyOtherActivity. class):
Pendinglnient.getAciivity(this,O,siariAciivitylntutO);

Ali Karim Sir from Mumbra Page 1


Mobile Android Development Chp. 5 Ali Karim Sir

Intent structure:
In Android intents are the message passing mechanisms to communicate an action.
action :- The general action to be performed. such as ACTION_VIEV, ACTION_
EDIT, ACTION_MAE’, etc.
data :- The data to operate on, such as a person record in the contacts database, expressed as
a Uri.

Q. Write the syntax for Intent-Filter tag. (Sample Paper)


Ans:
Intent filter
Intent_fIlters is a very powerful way to connect different applications together hence
allowing better user experience, They take care of intent resolution to match activities,
services and broadcast receiver. Intent filter are declared in the AndroidMariifest.xml. An
intent filters is an instance of the IntentFilter class.
An intent filter declares the capability of its parent component.
SYNTAX
<intent-filter android: icon=‖drawable resource‖
android: label=‖string resource‖
android:priority=‖integer‖ >
</intent-filter>

Example:
Q. Program to create a text field and a button “Navigate”. When you enter
www.google.com” and press navigate button it should open google page.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">

<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:ems="10" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_marginTop="40dp"

Ali Karim Sir from Mumbra Page 2


Mobile Android Development Chp. 5 Ali Karim Sir

android:layout_gravity="center"
android:text="Navigate" />

</LinearLayout>

MainActivity.java
package com.example.implicit_intent;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {


EditText editText ;
Button button ;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

editText = (EditText)findViewById(R.id.editText1);
button = (Button)findViewById(R.id.button1);

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String url = editText.getText().toString();
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
});
}
}

Ali Karim Sir from Mumbra Page 3


Mobile Android Development Chp. 5 Ali Karim Sir

Output (On Android Emulator):

2) Write a program to create button “Start Dialer”. When you click on this button it
should open the phone dialer.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">

<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:hint="Phone No."
android:inputType="phone"
android:ems="10" />

Ali Karim Sir from Mumbra Page 4


Mobile Android Development Chp. 5 Ali Karim Sir

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_marginTop="40dp"
android:layout_gravity="center"
android:onClick="Call"
android:text="Start Dialer" />

</LinearLayout>

MainActivity.java
package com.example.implicit_intent;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText editText ;
Button button ;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void Call(View view) {editText = (EditText)findViewById(R.id.editText1);

Toast.makeText(this, "clicked", Toast.LENGTH_LONG).show();


Uri u = Uri.parse("tel:" + editText.getText().toString());
Intent i = new Intent(Intent.ACTION_DIAL, u);

try
{
startActivity(i);
}
catch (SecurityException s)
{
Toast.makeText(this, "Error", Toast.LENGTH_LONG).show();
}
}
}

Ali Karim Sir from Mumbra Page 5


Mobile Android Development Chp. 5 Ali Karim Sir

Output (On Android Emulator):

3) Write a program to create two screens. First screen will take one number input from
user. After click on Factorial button, second screen will open and it should display
factorial of the same number. Also specify which type of intent you will use in this case.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">

<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:ems="10"
android:hint="Enter number:"/>

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_marginTop="40dp"

Ali Karim Sir from Mumbra Page 6


Mobile Android Development Chp. 5 Ali Karim Sir

android:layout_gravity="center"
android:text="Factorial" />
</LinearLayout>

activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Main2Activity"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/resultView"
android:layout_marginLeft="100dp"
android:layout_marginTop="150dp"/>
</LinearLayout>

MainActivity.java
package com.example.explicit_intent;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {


EditText editText;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

editText=(EditText)findViewById(R.id.editText1);
button=(Button)findViewById(R.id.button1);

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int num = Integer.parseInt(editText.getText().toString());
int fact = 1;
for (int i=1;i<=num;i++){

Ali Karim Sir from Mumbra Page 7


Mobile Android Development Chp. 5 Ali Karim Sir

fact=fact*i;
}
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
intent.putExtra("FACTORIAL","Factorial of "+num+" is "+fact);
startActivity(intent);
}
});
}
}

Main2Activity.java
package com.example.explicit_intent;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class Main2Activity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
TextView result = (TextView)findViewById(R.id.resultView);
Intent intent = getIntent();
String factorial = (String)intent.getSerializableExtra("FACTORIAL");
result.setText(factorial+"\nIntent used : Explicit Intent");
}
}

Output (On Android Emulator):

Ali Karim Sir from Mumbra Page 8


Mobile Android Development Chp. 5 Ali Karim Sir

Q. Draw the life cycle of an activity. (Sample QP) 4m


Q. Describe Activity life cycle.
Ans:
Activities in the system are managed as an activity stack.
> When a new activity is happening, it is placed on the top of thc stack and becomes the
finning
activity
> The activity always remains below it in the stack, and will not come to the foreground
again until the new activity exits.

1. Another foregrounds comes to the foreground


2. The activity is no longer.
3. The activity is finishing or being destroyed by the system
4. APPs with higher priority need money
5. User navigates to the activity
6. User returns to the activity
7. User navigates to the activity

Ali Karim Sir from Mumbra Page 9


Mobile Android Development Chp. 5 Ali Karim Sir

A program to create a HelloWorld Activity using all lifecycles methods to display


messages using Log.d
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java
package com.example.activity_lifecycle;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("lifecycle","onCreate invoked");
}
@Override
protected void onStart() {
super.onStart();
Log.d("lifecycle","onStart invoked");
}
@Override
protected void onResume() {
super.onResume();
Log.d("lifecycle","onResume invoked");
}

Ali Karim Sir from Mumbra Page 10


Mobile Android Development Chp. 5 Ali Karim Sir

@Override
protected void onPause() {
super.onPause();
Log.d("lifecycle","onPause invoked");
}
@Override
protected void onStop() {
super.onStop();
Log.d("lifecycle","onStop invoked");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d("lifecycle","onRestart invoked");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("lifecycle","onDestroy invoked");
}
}
Output (On Android Emulator):

Ali Karim Sir from Mumbra Page 11


Mobile Android Development Chp. 5 Ali Karim Sir

Q. Describe Service.
Q. Define services in Android operating system. (Sample Question Paper) 2m
Ans:
Service
A service is an application component which runs without direct interaction with the user in
the background. The Android platform provides and runs predefined system services such as
updating ContentProviders,firing Intents, and triggering Notifications etc to which all
Android applications can use them permissions. Each service should have a matching
<service> declaration in its package’s AndroidMani fest.xml.
Services are started with two methods:
a. Context.startService()
b. Context.bindService()

 Features of Service:
. A feature for the application where the user is not directly interacting with the application
corresponds to calls to Context.startService() method, which ask the system to agenda work
for the service, to be run until the service or someone stops it forcefully.

 Android Platform Service:


The Android platform provides pre-defined services, generally showing by a particular
Manager
class. The getSystemService() method is used to access them.

 Permission
Global access to a service can be required when it is declared in its manifest’s <service> tag.
By doing
so, other applications will require to declare a corresponding <uses-permission> element in
their own manifest to be capable to start, stop, or bind to the service.
In addition, a service can guard individual IPC calls into it with permissions, by calling the
checkCallingPermission(String) before executing the implementation of that call.
Services which nm in the procedure of the application are occasionally called local services.

Ali Karim Sir from Mumbra Page 12


Mobile Android Development Chp. 5 Ali Karim Sir

 Service Lifecycle:

Q. Describe Android System Architecture


Ans: Already Explained in previous chapter

Q. Describe Multimedia Framework


Ans:
The android multimedia system includes multimedia applications, multimedia framework,
OpenCore engine and hardware abstract for audio/video input/output devices. And the goal of
the android multimedia framework is to provide a reliable inferface for Java services. The
multimedia framework consists of several core dynamic libraries such as libmediajni,
libmedia, libmediaplayservice and so on . A general multimedia framework architecture is
shown in the below figure. From the figure, Java classes call the Native C library Libmedia
through Java iNI (Java Native Interface). Libmedia library communicates with Media Server
guard process through Android’s Binder ]PC (inter process communication) mechanism.

Ali Karim Sir from Mumbra Page 13


Mobile Android Development Chp. 5 Ali Karim Sir

Q. Describe Play Audio and Video


Ans: Play Audio
There are two types of classes which are used to play audio and video in Android.
1. MediaPlayer: This class is the primary API for playing sound and video.
2. AudioManager: This class manages audio sources and audio output on a device.
Android offers a lot of options in terms of playing audio. Most devices come with speaker,
headphone ports. and some might have Bluetooth connectivity and an additional support for
A2DP audio. The Android multimedia framework supports playing variety of common media
types, so that we can easily integrate audio, video and images into our applications. We can
play audio or video from media flies using MediaPlayerAPls.

Q. Describe Text to Speech


Ans:
Generates speech from instant playback or to produce a sound file. A TextToSpeech case can
only be used to make text once it has completed its initialization. At the end of the
initialization, the implementation of the TextToSpeech.OnlnitListener to be informed. When
we are completed using the TextToSpeech instance, call the shutdown() method to free the
native resources used by the TextToSpeech mechanism.

Q. Describe Sensor.
Ans:
Sensors:
A Sensors is a piece of hardware wired into the device feeding data from the physical world
to applications. Android devices come with built-in sensors and provide a framework for
working with sensors. Working with sensors is real fun in Android. Applications use the
sensor data to inform the user about the physical world, to control game play, to do

Ali Karim Sir from Mumbra Page 14


Mobile Android Development Chp. 5 Ali Karim Sir

augmented reality, or to provide useful tools for working in the real world. Sensors are easy
to use. Sensors can operate in one direction only and are read-only. You set up a listener to
receive sensor data, and then you can process the data as it comes in GPS hardware is an
example of a sensor.
Sonic of the sensor types:
+ Light sensor
+ Proximity sensor
+ Temperature sensor
+ Pressure sensor
+ Gyroscope sensor
+ Accelerometer
+ Magnetic field sensor
+ Orientation sensor
+ Gravity sensor(as of Android 2.3)
+ Linear acceleration sensor(as of Android 2.3)
+NFC

Q How Sensors Work?


Ans
Android supports three categories of sensors:
1. Motion sensors: These sensors measure acceleration forces and rotational forces along
three axes. This category includes gravity sensors, accelerometers, gyroscopes, and rotational
vector sensors.
2. Environmental sensors: These sensors measure various environmental parameters, such
as pressure and, ambient air temperature illumination, and humidity. This category includes
photometers, barometers, and thermometers.
3. Position sensors: These sensors measure the physical position of a device. This category
includes orientation sensors and magnetometers.
Sensors capture raw sensor data with the help of sensors framework. It is a part of
android hardware and includes the following classes and interfaces:
SensorManager
> Sensor
> SensorEvent
> SensorEventListener

Q. Describe Android AsyncTask


Ans:
Android AsyncTask going to do background operation on background thread and
update on main thread. In android we cant directly touch background thread to main thread in
android development. asynctask help us to make communication between background thread
to main thread.
Methods of AsyncTask
 onPreExecute() − Before doing background operation we should show something on
screen like progressbar or any animation to user. we can directly comminicate
background operation using on doInBackground() but for the best practice, we should
call all asyncTask methods .

Ali Karim Sir from Mumbra Page 15


Mobile Android Development Chp. 5 Ali Karim Sir

 doInBackground(Params) − In this method we have to do background operation on


background thread. Operations in this method should not touch on any mainthread
activities or fragments.
 onProgressUpdate(Progress…) − While doing background operation, if you want to
update some information on UI, we can use this method.
 onPostExecute(Result) − In this method we can update ui of background operation
result.
Generic Types in Async Task
 TypeOfVarArgParams − It contains information about what type of params used for
execution.
 ProgressValue − It contains information about progress units. While doing
background operation we can update information on ui using onProgressUpdate().
 ResultValue −It contains information about result type.
This example demonstrate about how to use asyncTask in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all
required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.

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


<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:id = "@+id/rootview"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:orientation = "vertical"
android:background = "#c1c1c1"
android:gravity = "center_horizontal"
tools:context = ".MainActivity">
<Button
android:id = "@+id/asyncTask"
android:text = "Download"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content" />
<ImageView
android:id = "@+id/image"
android:layout_width = "300dp"
android:layout_height = "300dp" />
</LinearLayout>
In the above xml we have created a button, when user click on the button it going to
download image and append image to imageview.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.app.ProgressDialog;

Ali Karim Sir from Mumbra Page 16


Mobile Android Development Chp. 5 Ali Karim Sir

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
URL ImageUrl = null;
InputStream is = null;
Bitmap bmImg = null;
ImageView imageView= null;
ProgressDialog p;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button=findViewById(R.id.asyncTask);
imageView=findViewById(R.id.image);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AsyncTaskExample asyncTask=new AsyncTaskExample();
asyncTask.execute("https://www.tutorialspoint.com/images/tp-logo-diamond.png");
}
});
}
private class AsyncTaskExample extends AsyncTask<String, String, Bitmap> {
@Override
protected void onPreExecute() {
super.onPreExecute();
p = new ProgressDialog(MainActivity.this);
p.setMessage("Please wait...It is downloading");
p.setIndeterminate(false);
p.setCancelable(false);
p.show();
}
@Override
protected Bitmap doInBackground(String... strings) {
try {
ImageUrl = new URL(strings[0]);
HttpURLConnection conn = (HttpURLConnection) ImageUrl.openConnection();
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream();

Ali Karim Sir from Mumbra Page 17


Mobile Android Development Chp. 5 Ali Karim Sir

BitmapFactory.Options options = new BitmapFactory.Options();


options.inPreferredConfig = Bitmap.Config.RGB_565;
bmImg = BitmapFactory.decodeStream(is, null, options);
} catch (IOException e) {
e.printStackTrace();
}
return bmImg;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if(imageView!=null) {
p.hide();
imageView.setImageBitmap(bitmap);
}else {
p.show();
}
}
}
}

In the above code we are downloading image using asyncTask and appending image to
imageview.
Step 4 − Add the following code to manifest.xml

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


<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
package = "com.example.andy.myapplication">
<uses-permission android:name = "android.permission.INTERNET"/>
<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>
</application>
</manifest>

In the above AndroidManifest.xml file we have added internet permission to access internet
to download image.
Let's try to run your application. I assume you have connected your actual Android Mobile
device with your computer. To run the app from android studio, open one of your project's

Ali Karim Sir from Mumbra Page 18


Mobile Android Development Chp. 5 Ali Karim Sir

activity files and click Run Eclipse Run Icon icon from the toolbar. Select your mobile device
as an option and then check your mobile device which will display your default screen.

Now click on download button it will show progress on UI and download image at
background as shown below

After downloading image, it will update on UI as shown below

Ali Karim Sir from Mumbra Page 19


Mobile Android Development Chp. 5 Ali Karim Sir

Q. Describe Android Audio Capture.


Ans:
Android has a built in microphone through which you can capture audio and store it ,
or play it in your phone. There are many ways to do that but the most common way is
through MediaRecorder class.
Android provides MediaRecorder class to record audio or video. In order to use
MediaRecorder class ,you will first create an instance of MediaRecorder class. Its syntax is
given below.
MediaRecorder myAudioRecorder = new MediaRecorder();
Now you will set the source , output and encoding format and output file. Their syntax is
given below.
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
After specifying the audio source and format and its output file, we can then call the two
basic methods prepare and start to start recording the audio.
myAudioRecorder.prepare();
myAudioRecorder.start();
Apart from these methods , there are other methods listed in the MediaRecorder class that
allows you more control over audio and video recording.

Sr.No Method & description

Ali Karim Sir from Mumbra Page 20


Mobile Android Development Chp. 5 Ali Karim Sir

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

Ali Karim Sir from Mumbra Page 21


Mobile Android Development Chp. 5 Ali Karim Sir

package com.example.sairamkrishna.myapplication;

import android.media.MediaPlayer;
import android.media.MediaRecorder;

import android.os.Environment;
import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;

import android.widget.Button;
import android.widget.Toast;

import java.io.IOException;
import java.util.Random;

import static android.Manifest.permission.RECORD_AUDIO;


import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;

import android.support.v4.app.ActivityCompat;
import android.content.pm.PackageManager;
import android.support.v4.content.ContextCompat;

public class MainActivity extends AppCompatActivity {

Button buttonStart, buttonStop, buttonPlayLastRecordAudio,


buttonStopPlayingRecording ;
String AudioSavePathInDevice = null;
MediaRecorder mediaRecorder ;
Random random ;
String RandomAudioFileName = "ABCDEFGHIJKLMNOP";
public static final int RequestPermissionCode = 1;
MediaPlayer mediaPlayer ;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

buttonStart = (Button) findViewById(R.id.button);


buttonStop = (Button) findViewById(R.id.button2);
buttonPlayLastRecordAudio = (Button) findViewById(R.id.button3);
buttonStopPlayingRecording = (Button)findViewById(R.id.button4);

buttonStop.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(false);
buttonStopPlayingRecording.setEnabled(false);

random = new Random();

Ali Karim Sir from Mumbra Page 22


Mobile Android Development Chp. 5 Ali Karim Sir

buttonStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

if(checkPermission()) {

AudioSavePathInDevice =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +
CreateRandomAudioFileName(5) + "AudioRecording.3gp";

MediaRecorderReady();

try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

buttonStart.setEnabled(false);
buttonStop.setEnabled(true);

Toast.makeText(MainActivity.this, "Recording started",


Toast.LENGTH_LONG).show();
} else {
requestPermission();
}

}
});

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);

Toast.makeText(MainActivity.this, "Recording Completed",


Toast.LENGTH_LONG).show();
}
});

Ali Karim Sir from Mumbra Page 23


Mobile Android Development Chp. 5 Ali Karim Sir

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 = new MediaPlayer();


try {
mediaPlayer.setDataSource(AudioSavePathInDevice);
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}

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();
}
}
});

public void MediaRecorderReady(){


mediaRecorder=new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(AudioSavePathInDevice);
}

public String CreateRandomAudioFileName(int string){

Ali Karim Sir from Mumbra Page 24


Mobile Android Development Chp. 5 Ali Karim Sir

StringBuilder stringBuilder = new StringBuilder( string );


int i = 0 ;
while(i < string ) {
stringBuilder.append(RandomAudioFileName.
charAt(random.nextInt(RandomAudioFileName.length())));

i++ ;
}
return stringBuilder.toString();
}

private void requestPermission() {


ActivityCompat.requestPermissions(MainActivity.this, new
String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO},
RequestPermissionCode);
}

@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;

if (StoragePermission && RecordPermission) {


Toast.makeText(MainActivity.this, "Permission Granted",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this,"Permission
Denied",Toast.LENGTH_LONG).show();
}
}
break;
}
}

public boolean checkPermission() {


int result = ContextCompat.checkSelfPermission(getApplicationContext(),
WRITE_EXTERNAL_STORAGE);
int result1 = ContextCompat.checkSelfPermission(getApplicationContext(),
RECORD_AUDIO);
return result == PackageManager.PERMISSION_GRANTED &&
result1 == PackageManager.PERMISSION_GRANTED;
}
}

Ali Karim Sir from Mumbra Page 25


Mobile Android Development Chp. 5 Ali Karim Sir

Here is the content of activity_main.xml


In the below code abc indicates the logo of tutorialspoint

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">

<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"
/>

Ali Karim Sir from Mumbra Page 26


Mobile Android Development Chp. 5 Ali Karim Sir

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="STOP PLAYING RECORDING "
android:id="@+id/button4"
android:layout_below="@+id/button2"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
/>
</RelativeLayout>
Here is the content of Strings.xml
<resources>
<string name="app_name">My Application</string>
</resources>
Here is the content of AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >

<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

Ali Karim Sir from Mumbra Page 27


Mobile Android Development Chp. 5 Ali Karim Sir

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.

Ali Karim Sir from Mumbra Page 28


Mobile Android Development Chp. 5 Ali Karim Sir

Q. Describe Bluetooth.
Ans:
Bluetooth is a way to send or receive data between two different devices. Android platform
includes support for the Bluetooth framework that allows a device to wirelessly exchange
data with other Bluetooth devices.
Android provides Bluetooth API to perform these different operations.
 Scan for other Bluetooth devices
 Get a list of paired devices
 Connect to other devices through service discovery
Android provides BluetoothAdapter class to communicate with Bluetooth. Create an object
of this calling by calling the static method getDefaultAdapter(). Its syntax is given below.
private BluetoothAdapter BA;
BA = BluetoothAdapter.getDefaultAdapter();
In order to enable the Bluetooth of your device, call the intent with the following Bluetooth
constant ACTION_REQUEST_ENABLE. Its syntax is.
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
Apart from this constant, there are other constants provided the API , that supports different
tasks. They are listed below.

Sr.No Constant & description

1 ACTION_REQUEST_DISCOVERABLE

Ali Karim Sir from Mumbra Page 29


Mobile Android Development Chp. 5 Ali Karim Sir

This constant is used for turn on discovering of bluetooth

ACTION_STATE_CHANGED
2
This constant will notify that Bluetooth state has been changed

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

Once you enable the Bluetooth , you can get a list of paired devices by calling
getBondedDevices() method. It returns a set of bluetooth devices. Its syntax is.
private Set<BluetoothDevice>pairedDevices;
pairedDevices = BA.getBondedDevices();
Apart form the parried Devices , there are other methods in the API that gives more control
over Blueetooth. They are listed below.
Sr.No Method & description

enable()
1
This method enables the adapter if not enabled

isEnabled()
2
This method returns true if adapter is enabled

disable()
3
This method disables the adapter

getName()
4
This method returns the name of the Bluetooth adapter

setName(String name)
5
This method changes the Bluetooth name

getState()
6
This method returns the current state of the Bluetooth Adapter.

startDiscovery()
7
This method starts the discovery process of the Bluetooth for 120 seconds.

Example

Ali Karim Sir from Mumbra Page 30


Mobile Android Development Chp. 5 Ali Karim Sir

This example provides demonstration of BluetoothAdapter class to manipulate Bluetooth


and show list of paired devices by the Bluetooth.
To experiment with this example , you need to run this on an actual device.

Steps Description

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


com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add the 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.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import android.widget.Toast;
import java.util.ArrayList;
import java.util.Set;

public class MainActivity extends Activity {


Button b1,b2,b3,b4;
private BluetoothAdapter BA;
private Set<BluetoothDevice>pairedDevices;
ListView lv;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Ali Karim Sir from Mumbra Page 31


Mobile Android Development Chp. 5 Ali Karim Sir

b1 = (Button) findViewById(R.id.button);
b2=(Button)findViewById(R.id.button2);
b3=(Button)findViewById(R.id.button3);
b4=(Button)findViewById(R.id.button4);

BA = BluetoothAdapter.getDefaultAdapter();
lv = (ListView)findViewById(R.id.listView);
}

public void on(View v){


if (!BA.isEnabled()) {
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
Toast.makeText(getApplicationContext(), "Turned
on",Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Already on",
Toast.LENGTH_LONG).show();
}
}

public void off(View v){


BA.disable();
Toast.makeText(getApplicationContext(), "Turned off" ,Toast.LENGTH_LONG).show();
}

public void visible(View v){


Intent getVisible = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(getVisible, 0);
}

public void list(View v){


pairedDevices = BA.getBondedDevices();

ArrayList list = new ArrayList();

for(BluetoothDevice bt : pairedDevices) list.add(bt.getName());


Toast.makeText(getApplicationContext(), "Showing Paired
Devices",Toast.LENGTH_SHORT).show();

final ArrayAdapter adapter = new


ArrayAdapter(this,android.R.layout.simple_list_item_1, list);

lv.setAdapter(adapter);
}
}

Ali Karim Sir from Mumbra Page 32


Mobile Android Development Chp. 5 Ali Karim Sir

Here is the content of activity_main.xml


Here abc indicates about logo of tutorialspoint.

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


<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:transitionGroup="true">

<TextView android:text="Bluetooth Example"


android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:theme="@style/Base.TextAppearance.AppCompat" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Turn On"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_toStartOf="@+id/imageView"

Ali Karim Sir from Mumbra Page 33


Mobile Android Development Chp. 5 Ali Karim Sir

android:layout_toLeftOf="@+id/imageView"
android:clickable="true"
android:onClick="on" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get visible"
android:onClick="visible"
android:id="@+id/button2"
android:layout_alignBottom="@+id/button"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="List devices"
android:onClick="list"
android:id="@+id/button3"
android:layout_below="@+id/imageView"
android:layout_toRightOf="@+id/imageView"
android:layout_toEndOf="@+id/imageView" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="turn off"
android:onClick="off"
android:id="@+id/button4"
android:layout_below="@+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/listView"
android:layout_alignParentBottom="true"
android:layout_alignLeft="@+id/button"
android:layout_alignStart="@+id/button"
android:layout_below="@+id/textView2" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Paired devices:"
android:id="@+id/textView2"
android:textColor="#ff34ff06"
android:textSize="25dp"
android:layout_below="@+id/button4"

Ali Karim Sir from Mumbra Page 34


Mobile Android Development Chp. 5 Ali Karim Sir

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

</RelativeLayout>
Here is the content of Strings.xml
<resources>
<string name="app_name">My Application</string>
</resources>
Here is the content of AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name=".MainActivity"
android:label="@string/app_name" >

<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

</activity>

</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile
device with your computer. To run the app from Android studio, open one of your project's
activity files and click Run icon from the tool bar.If your Bluetooth will not be turned on
then, it will ask your permission to enable the Bluetooth.

Ali Karim Sir from Mumbra Page 35


Mobile Android Development Chp. 5 Ali Karim Sir

Now just select the Get Visible button to turn on your visibility. The following screen would
appear asking your permission to turn on discovery for 120 seconds.

Now just select the List Devices option. It will list down the paired devices in the list view.
In my case , I have only one paired device. It is shown below.

Ali Karim Sir from Mumbra Page 36


Mobile Android Development Chp. 5 Ali Karim Sir

Now just select the Turn off button to switch off the Bluetooth. Following message would
appear when you switch off the bluetooth indicating the successful switching off of
Bluetooth.

Ali Karim Sir from Mumbra Page 37


Mobile Android Development Chp. 5 Ali Karim Sir

Q. Describe Camera.
Ans:
These are the following two ways, in which you can use camera in your application
 Using existing android camera application in our application
 Directly using Camera API provided by android in our application

Using existing android camera application in our application

You will use MediaStore.ACTION_IMAGE_CAPTURE to launch an existing camera


application installed on your phone. Its syntax is given below
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
Apart from the above, there are other available Intents provided by MediaStore. They are
listed as follows

Sr.No Intent type and description

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

ACTION_VIDEO_CAPTURE
2
It calls the existing video application in android to capture video

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

EXTRA_FULL_SCREEN
4
It is used to control the user interface of the ViewImage

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

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

Now you will use the function startActivityForResult() to launch this activity and wait for its
result. Its syntax is given below
startActivityForResult(intent,0)
This method has been defined in the activity class. We are calling it from main activity.
There are methods defined in the activity class that does the same job , but used when you
are not calling from the activity but from somewhere else. They are listed below

Ali Karim Sir from Mumbra Page 38


Mobile Android Development Chp. 5 Ali Karim Sir

Sr.No Activity function description

startActivityForResult(Intent intent, int requestCode, Bundle options)


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

startActivityFromChild(Activity child, Intent intent, int requestCode)


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

startActivityFromChild(Activity child, Intent intent, int requestCode, Bundle options)


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

startActivityFromFragment(Fragment fragment, Intent intent, int requestCode)


4
It launches activity from the fragment you are currently inside

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


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

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

Example

Here is an example that shows how to launch the existing camera application to capture an
image and display the result in the form of bitmap.
To experiment with this example , you need to run this on an actual device on which camera
is supported.

Steps Description

1 You will use Android studio IDE to create an Android application and name it as Camera under a
com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add intent code to launch the Camera.

3 Modify layout XML file res/layout/activity_main.xml

4 Add the Camera permission and run the application and choose a running android device and install
the application on it and verify the results.

Following is the content of the modified main activity file src/MainActivity.java.


package com.example.sairamkrishna.myapplication;

import android.Manifest;
import android.app.Activity;

Ali Karim Sir from Mumbra Page 39


Mobile Android Development Chp. 5 Ali Karim Sir

import android.app.AlertDialog;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;

import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;

import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

public class MainActivity extends AppCompatActivity {


public static final int MY_PERMISSIONS_REQUEST_CAMERA = 100;
public static final String ALLOW_KEY = "ALLOWED";
public static final String CAMERA_PREF = "camera_pref";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) !=
PackageManager.PERMISSION_GRANTED) {
if (getFromPref(this, ALLOW_KEY)) {
showSettingsAlert();
} else if (ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA)

!= PackageManager.PERMISSION_GRANTED) {

// Should we show an explanation?


if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {
showAlert();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA},
MY_PERMISSIONS_REQUEST_CAMERA);
}
}
} else {
openCamera();
}

Ali Karim Sir from Mumbra Page 40


Mobile Android Development Chp. 5 Ali Karim Sir

}
public static void saveToPreferences(Context context, String key, Boolean allowed) {
SharedPreferences myPrefs = context.getSharedPreferences(CAMERA_PREF,
Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putBoolean(key, allowed);
prefsEditor.commit();
}

public static Boolean getFromPref(Context context, String key) {


SharedPreferences myPrefs = context.getSharedPreferences(CAMERA_PREF,
Context.MODE_PRIVATE);
return (myPrefs.getBoolean(key, false));
}

private void showAlert() {


AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("App needs to access the Camera.");

alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "DONT ALLOW",


new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});

alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "ALLOW",
new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {


dialog.dismiss();
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA},
MY_PERMISSIONS_REQUEST_CAMERA);
}
});
alertDialog.show();
}

private void showSettingsAlert() {


AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("App needs to access the Camera.");

alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "DONT ALLOW",


new DialogInterface.OnClickListener() {

Ali Karim Sir from Mumbra Page 41


Mobile Android Development Chp. 5 Ali Karim Sir

public void onClick(DialogInterface dialog, int which) {


dialog.dismiss();
//finish();
}
});

alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "SETTINGS",
new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {


dialog.dismiss();
startInstalledAppDetailsActivity(MainActivity.this);
}
});

alertDialog.show();
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[]
grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_CAMERA: {
for (int i = 0, len = permissions.length; i < len; i++) {
String permission = permissions[i];

if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
boolean
showRationale =
ActivityCompat.shouldShowRequestPermissionRationale(
this, permission);

if (showRationale) {
showAlert();
} else if (!showRationale) {
// user denied flagging NEVER ASK AGAIN
// you can either enable some fall back,
// disable features of your app
// or open another dialog explaining
// again the permission and directing to
// the app setting
saveToPreferences(MainActivity.this, ALLOW_KEY, true);
}
}
}
}

// other 'case' lines to check for other


// permissions this app might request
}

Ali Karim Sir from Mumbra Page 42


Mobile Android Development Chp. 5 Ali Karim Sir

@Override
protected void onResume() {
super.onResume();
}

public static void startInstalledAppDetailsActivity(final Activity context) {


if (context == null) {
return;
}

final Intent i = new Intent();


i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
i.addCategory(Intent.CATEGORY_DEFAULT);
i.setData(Uri.parse("package:" + context.getPackageName()));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
context.startActivity(i);
}

private void openCamera() {


Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivity(intent);
}
}
Following will be the content of res/layout/activity_main.xml file−
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
</RelativeLayout>
Following will be the content of res/values/strings.xml to define one new constants
<resources>
<string name="app_name">My Application</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"

Ali Karim Sir from Mumbra Page 43


Mobile Android Development Chp. 5 Ali Karim Sir

package="com.example.sairamkrishna.myapplication" >
<uses-permission android:name="android.permission.CAMERA" />
<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 tool bar. Before starting your application,
Android studio will display following window to select an option where you want to run
your Android application.

Select your mobile device as an option and then check your mobile device which will open
the camera and display following screen −

Ali Karim Sir from Mumbra Page 44


Mobile Android Development Chp. 5 Ali Karim Sir

Q. Describe Animation.
Ans:
Animation is the process of creating motion and shape change
Animation in android is possible from many ways. In this chapter we will discuss one easy
and widely used way of making animation called tweened animation.

Tween Animation

Tween Animation takes some parameters such as start value , end value, size , time duration
, rotation angle e.t.c and perform the required animation on that object. It can be applied to
any type of object. So in order to use this , android has provided us a class called Animation.
In order to perform animation in android , we are going to call a static function
loadAnimation() of the class AnimationUtils. We are going to receive the result in an
instance of Animation Object. Its syntax is as follows −
Animation animation = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.myanimation);
Note the second parameter. It is the name of the our animation xml file. You have to create a
new folder called anim under res directory and make an xml file under anim folder.
This animation class has many useful functions which are listed below −

Sr.No Method & Description

1 start()
This method starts the animation.

2 setDuration(long duration)
This method sets the duration of an animation.

Ali Karim Sir from Mumbra Page 45


Mobile Android Development Chp. 5 Ali Karim Sir

3 getDuration()
This method gets the duration which is set by above method

4 end()
This method ends the animation.

5 cancel()
This method cancels the animation.

In order to apply this animation to an object , we will just call the startAnimation() method
of the object. Its syntax is −
ImageView image1 = (ImageView)findViewById(R.id.imageView1);
image.startAnimation(animation);

Example

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

Steps Description

1 You will use Android studio IDE to create an Android application and name it as My Application
under a package com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add animation code

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

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

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

6 Create files myanimation.xml,clockwise.xml,fade.xml,move.xml,blink.xml,slide.xml and add the


XML code.

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

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

Ali Karim Sir from Mumbra Page 46


Mobile Android Development Chp. 5 Ali Karim Sir

Here is the modified code of MainActivity.java.


package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void clockwise(View view){


ImageView image = (ImageView)findViewById(R.id.imageView);
Animation animation = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.myanimation);
image.startAnimation(animation);
}

public void zoom(View view){


ImageView image = (ImageView)findViewById(R.id.imageView);
Animation animation1 = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.clockwise);
image.startAnimation(animation1);
}

public void fade(View view){


ImageView image = (ImageView)findViewById(R.id.imageView);
Animation animation1 =
AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.fade);
image.startAnimation(animation1);
}

public void blink(View view){


ImageView image = (ImageView)findViewById(R.id.imageView);
Animation animation1 =
AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.blink);
image.startAnimation(animation1);
}

public void move(View view){

Ali Karim Sir from Mumbra Page 47


Mobile Android Development Chp. 5 Ali Karim Sir

ImageView image = (ImageView)findViewById(R.id.imageView);


Animation animation1 =
AnimationUtils.loadAnimation(getApplicationContext(), R.anim.move);
image.startAnimation(animation1);
}

public void slide(View view){


ImageView image = (ImageView)findViewById(R.id.imageView);
Animation animation1 =
AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide);
image.startAnimation(animation1);
}
}
Here is the modified code of res/layout/activity_main.xml.
Here abc indicates about logo of tutorialspoint

<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:text="Alert Dialog"
android:id="@+id/textView"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorialspoint"
android:id="@+id/textView2"
android:textColor="#ff3eff0f"
android:textSize="35dp"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"

Ali Karim Sir from Mumbra Page 48


Mobile Android Development Chp. 5 Ali Karim Sir

android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2"
android:layout_alignLeft="@+id/textView"
android:layout_alignStart="@+id/textView"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="zoom"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="40dp"
android:onClick="clockwise"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="clockwise"
android:id="@+id/button2"
android:layout_alignTop="@+id/button"
android:layout_centerHorizontal="true"
android:onClick="zoom"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="fade"
android:id="@+id/button3"
android:layout_alignTop="@+id/button2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:onClick="fade"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="blink"
android:onClick="blink"
android:id="@+id/button4"
android:layout_below="@+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<Button
android:layout_width="wrap_content"

Ali Karim Sir from Mumbra Page 49


Mobile Android Development Chp. 5 Ali Karim Sir

android:layout_height="wrap_content"
android:text="move"
android:onClick="move"
android:id="@+id/button5"
android:layout_below="@+id/button2"
android:layout_alignRight="@+id/button2"
android:layout_alignEnd="@+id/button2"
android:layout_alignLeft="@+id/button2"
android:layout_alignStart="@+id/button2" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="slide"
android:onClick="slide"
android:id="@+id/button6"
android:layout_below="@+id/button3"
android:layout_toRightOf="@+id/textView"
android:layout_toEndOf="@+id/textView" />

</RelativeLayout>
Here is the code of res/anim/myanimation.xml.
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

<scale xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXScale="0.5"
android:toXScale="3.0"
android:fromYScale="0.5"
android:toYScale="3.0"
android:duration="5000"
android:pivotX="50%"
android:pivotY="50%" >
</scale>

<scale xmlns:android="http://schemas.android.com/apk/res/android"
android:startOffset="5000"
android:fromXScale="3.0"
android:toXScale="0.5"
android:fromYScale="3.0"
android:toYScale="0.5"
android:duration="5000"
android:pivotX="50%"
android:pivotY="50%" >
</scale>

</set>
Here is the code of res/anim/clockwise.xml.

Ali Karim Sir from Mumbra Page 50


Mobile Android Development Chp. 5 Ali Karim Sir

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


<set xmlns:android="http://schemas.android.com/apk/res/android">

<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:duration="5000" >
</rotate>

<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:startOffset="5000"
android:fromDegrees="360"
android:toDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:duration="5000" >
</rotate>

</set>
Here is the code of res/anim/fade.xml.
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_interpolator" >

<alpha
android:fromAlpha="0"
android:toAlpha="1"
android:duration="2000" >
</alpha>

<alpha
android:startOffset="2000"
android:fromAlpha="1"
android:toAlpha="0"
android:duration="2000" >
</alpha>

</set>
Here is the code of res/anim/blink.xml.
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha android:fromAlpha="0.0"
android:toAlpha="1.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:duration="600"

Ali Karim Sir from Mumbra Page 51


Mobile Android Development Chp. 5 Ali Karim Sir

android:repeatMode="reverse"
android:repeatCount="infinite"/>
</set>
Here is the code of res/anim/move.xml.
<?xml version="1.0" encoding="utf-8"?>
<set
xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator"
android:fillAfter="true">

<translate
android:fromXDelta="0%p"
android:toXDelta="75%p"
android:duration="800" />
</set>
Here is the code of res/anim/slide.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true" >

<scale
android:duration="500"
android:fromXScale="1.0"
android:fromYScale="1.0"
android:interpolator="@android:anim/linear_interpolator"
android:toXScale="1.0"
android:toYScale="0.0" />
</set>
Here is the modified code of res/values/string.xml.
<resources>
<string name="app_name">My Application</string>
</resources>
Here is the default code of AndroidManifest.xml.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity

Ali Karim Sir from Mumbra Page 52


Mobile Android Development Chp. 5 Ali Karim Sir

android:name="com.example.animation.MainActivity"
android:label="@string/app_name" >

<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

</activity>

</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile
device with your computer. To run the app from Android studio, open one of your project's
activity files and click Run icon from the toolbar. Android studio will display following
images

Select zoom button, it will display following screen −

Now select slide button, it will display following screen

Ali Karim Sir from Mumbra Page 53


Mobile Android Development Chp. 5 Ali Karim Sir

Now select move button, it will display following screen

Now the clockwise button, it will display following screen

Now Fade button, it will display following screen

Ali Karim Sir from Mumbra Page 54


Mobile Android Development Chp. 5 Ali Karim Sir

Note − If you run it in emulator , you may not experience smooth animation effect. You
have to run it in your android mobile in order to experience the smooth animation.

Q. What is SQLite Database?


Ans:
SQLite is an open source database engine which implements a self-contained, serverless,
zero- configuration, transactions. SQLite stores potent data storage to mobile and embedded
applications without a track. SQLite can read and write to general disk files openly in which a
single disk file contains multiple tables, indices, triggers, and views. Normally the database
file layout is cross-platform —in which we can liberally copy a database between 32-bit and
64-bit systems or between big-endian and little-endian architectures. Thus the characters of
SQLite make it as an Application File Format. So we cannot say that the SQLite is the
replacement of Oracle, but it is the replacement of fopen(). The code of SQLite is open to use
for any purpose i.e. commercial or private, because of it is in the public domain.

Q. Why SQLite?
Q. Describe the significance of SQLite database in Android. (Sample QP)
Ans:
 Serverless: SQLite is serverless which does not need a detach server process or
system to operate.
 Zero Configurations: SQLite does not require any setup or administration.
 Cross-platform: A complete SQLite database is stored in a single cross-platform disk
file.
 Less Memory: SQLite is very small and light weight, less than 400KiB completely
configured or less than 250K1B with optional features omitted.
 Self Contained: SQLite has no external dependencies.
 Transaction: SQLite transactions arc supported ACID properties to allow safe access
from multiple processes or threads.
 Languages and Operating System: SQLite supports most of the query language
features found in the SQL92 (SQL2) stanard. SQLite is written in ANSI-C and
provides simple and easy to use API. SQLite is accessible on Unix (Linux, Mac OS-
X, Android, iOS) and Windows (W1n32, WinCE, W1nRT).

Q. Describe Creation and connection of the database


Ans:

Ali Karim Sir from Mumbra Page 55


Mobile Android Development Chp. 5 Ali Karim Sir

Database - Package
The main package is android.database.sqlite that contains the classes to manage your own
databases

Database - Creation
In order to create a database you just need to call this method openOrCreateDatabase with
your database name and mode as a parameter. It returns an instance of SQLite database which
you have to receive in your own object.Its syntax is given below

SQLiteDatabase mydatabase = openOrCreateDatabase("your database


name",MODE_PRIVATE,null);

Sr.No Method & Description

1
openDatabase(String path, SQLiteDatabase.CursorFactory factory, int
flags, DatabaseErrorHandler errorHandler)
This method only opens the existing database with the appropriate flag mode.
The common flags mode could be OPEN_READWRITE OPEN_READONLY

2
openDatabase(String path, SQLiteDatabase.CursorFactory factory, int
flags)
It is similar to the above method as it also opens the existing database but it does
not define any handler to handle the errors of databases

3
openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory
factory)
It not only opens but create the database if it not exists. This method is equivalent
to openDatabase method.

4
openOrCreateDatabase(File file, SQLiteDatabase.CursorFactory factory)
This method is similar to above method but it takes the File object as a path
rather then a string. It is equivalent to file.getPath()

Database - Insertion
we can create table or insert data into table using execSQL method defined in
SQLiteDatabase class. Its syntax is given below
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS TutorialsPoint(Username
VARCHAR,Password VARCHAR);");
mydatabase.execSQL("INSERT INTO TutorialsPoint VALUES('admin','admin');");

Sr.No Method & Description


Ali Karim Sir from Mumbra Page 56
Mobile Android Development Chp. 5 Ali Karim Sir

1
execSQL(String sql, Object[] bindArgs)
This method not only insert data , but also used to update or modify already existing
data in database using bind arguments

This will insert some values into our table in our database. Another method that also does
the same job but take some additional parameter is given below

Database - Fetching
We can retrieve anything from database using an object of the Cursor class. We will call a
method of this class called rawQuery and it will return a resultset with the cursor pointing to
the table. We can move the cursor forward and retrieve the data.
Cursor resultSet = mydatbase.rawQuery("Select * from TutorialsPoint",null);
resultSet.moveToFirst();
String username = resultSet.getString(0);
String password = resultSet.getString(1);

Sr.No Method & Description

1
getColumnCount()
This method return the total number of columns of the table.

2
getColumnIndex(String columnName)
This method returns the index number of a column by specifying the name of the
column

3
getColumnName(int columnIndex)
This method returns the name of the column by specifying the index of the column

4
getColumnNames()
This method returns the array of all the column names of the table.

5
getCount()
This method returns the total number of rows in the cursor

6
getPosition()
This method returns the current position of the cursor in the table

7
isClosed()

Ali Karim Sir from Mumbra Page 57


Mobile Android Development Chp. 5 Ali Karim Sir

This method returns true if the cursor is closed and return false otherwise

There are other functions available in the Cursor class that allows us to effectively retrieve
the data. That includes

Database - Helper class

For managing all the operations related to the database , an helper class has been given and
is called SQLiteOpenHelper. It automatically manages the creation and update of the
database. Its syntax is given below
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(){
super(context,DATABASE_NAME,null,1);
}
public void onCreate(SQLiteDatabase db) {}
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {}
}

Steps Description

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 get references of all the XML components and
populate the contacts on listView.

3 Create new src/DBHelper.java that will manage the database work

4 Create a new Activity as DisplayContact.java that will display the contact on the
screen

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

6 Modify the res/layout/activity_display_contact.xml to add respective XML


components

7 Modify the res/values/string.xml to add necessary string components

8 Modify the res/menu/display_contact.xml to add necessary menu components

9 Create a new menu as res/menu/mainmenu.xml to add the insert contact option

Ali Karim Sir from Mumbra Page 58


Mobile Android Development Chp. 5 Ali Karim Sir

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

Here is an example demonstrating the use of SQLite Database. It creates a basic contacts
applications that allows insertion, deletion and modification of contacts.
To experiment with this example, you need to run this on an actual device on which camera
is supported.

Steps Description

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 get references of all the XML components and
populate the contacts on listView.

3 Create new src/DBHelper.java that will manage the database work

4 Create a new Activity as DisplayContact.java that will display the contact on the
screen

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

6 Modify the res/layout/activity_display_contact.xml to add respective XML


components

7 Modify the res/values/string.xml to add necessary string components

8 Modify the res/menu/display_contact.xml to add necessary menu components

9 Create a new menu as res/menu/mainmenu.xml to add the insert contact option

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

Following is the content of the modified MainActivity.java.


package com.example.sairamkrishna.myapplication;

import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;

Ali Karim Sir from Mumbra Page 59


Mobile Android Development Chp. 5 Ali Karim Sir

import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends ActionBarActivity {


public final static String EXTRA_MESSAGE = "MESSAGE";
private ListView obj;
DBHelper mydb;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mydb = new DBHelper(this);


ArrayList array_list = mydb.getAllCotacts();
ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,
array_list);

obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
obj.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
// TODO Auto-generated method stub
int id_To_Search = arg2 + 1;

Bundle dataBundle = new Bundle();


dataBundle.putInt("id", id_To_Search);

Intent intent = new Intent(getApplicationContext(),DisplayContact.class);

intent.putExtras(dataBundle);
startActivity(intent);
}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

Ali Karim Sir from Mumbra Page 60


Mobile Android Development Chp. 5 Ali Karim Sir

// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item){
super.onOptionsItemSelected(item);

switch(item.getItemId()) {
case R.id.item1:Bundle dataBundle = new Bundle();
dataBundle.putInt("id", 0);

Intent intent = new Intent(getApplicationContext(),DisplayContact.class);


intent.putExtras(dataBundle);

startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}

public boolean onKeyDown(int keycode, KeyEvent event) {


if (keycode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keycode, event);
}
}

Following is the modified content of display contact activity DisplayContact.java


package com.example.sairamkrishna.myapplication;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import android.widget.Button;
import android.widget.TextView;

Ali Karim Sir from Mumbra Page 61


Mobile Android Development Chp. 5 Ali Karim Sir

import android.widget.Toast;

public class DisplayContact extends Activity {


int from_Where_I_Am_Coming = 0;
private DBHelper mydb ;

TextView name ;
TextView phone;
TextView email;
TextView street;
TextView place;
int id_To_Update = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_contact);
name = (TextView) findViewById(R.id.editTextName);
phone = (TextView) findViewById(R.id.editTextPhone);
email = (TextView) findViewById(R.id.editTextStreet);
street = (TextView) findViewById(R.id.editTextEmail);
place = (TextView) findViewById(R.id.editTextCity);

mydb = new DBHelper(this);

Bundle extras = getIntent().getExtras();


if(extras !=null) {
int Value = extras.getInt("id");

if(Value>0){
//means this is the view part not the add contact part.
Cursor rs = mydb.getData(Value);
id_To_Update = Value;
rs.moveToFirst();

String nam =
rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NAME));
String phon =
rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_PHONE));
String emai =
rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_EMAIL));
String stree =
rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STREET));
String plac =
rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_CITY));

if (!rs.isClosed()) {
rs.close();
}
Button b = (Button)findViewById(R.id.button1);

Ali Karim Sir from Mumbra Page 62


Mobile Android Development Chp. 5 Ali Karim Sir

b.setVisibility(View.INVISIBLE);

name.setText((CharSequence)nam);
name.setFocusable(false);
name.setClickable(false);

phone.setText((CharSequence)phon);
phone.setFocusable(false);
phone.setClickable(false);

email.setText((CharSequence)emai);
email.setFocusable(false);
email.setClickable(false);

street.setText((CharSequence)stree);
street.setFocusable(false);
street.setClickable(false);

place.setText((CharSequence)plac);
place.setFocusable(false);
place.setClickable(false);
}
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
Bundle extras = getIntent().getExtras();

if(extras !=null) {
int Value = extras.getInt("id");
if(Value>0){
getMenuInflater().inflate(R.menu.display_contact, menu);
} else{
getMenuInflater().inflate(R.menu.menu_main menu);
}
}
return true;
}

public boolean onOptionsItemSelected(MenuItem item) {


super.onOptionsItemSelected(item);
switch(item.getItemId()) {
case R.id.Edit_Contact:
Button b = (Button)findViewById(R.id.button1);
b.setVisibility(View.VISIBLE);
name.setEnabled(true);
name.setFocusableInTouchMode(true);
name.setClickable(true);

Ali Karim Sir from Mumbra Page 63


Mobile Android Development Chp. 5 Ali Karim Sir

phone.setEnabled(true);
phone.setFocusableInTouchMode(true);
phone.setClickable(true);

email.setEnabled(true);
email.setFocusableInTouchMode(true);
email.setClickable(true);

street.setEnabled(true);
street.setFocusableInTouchMode(true);
street.setClickable(true);

place.setEnabled(true);
place.setFocusableInTouchMode(true);
place.setClickable(true);

return true;
case R.id.Delete_Contact:

AlertDialog.Builder builder = new AlertDialog.Builder(this);


builder.setMessage(R.string.deleteContact)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mydb.deleteContact(id_To_Update);
Toast.makeText(getApplicationContext(), "Deleted Successfully",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});

AlertDialog d = builder.create();
d.setTitle("Are you sure");
d.show();

return true;
default:
return super.onOptionsItemSelected(item);

}
}

public void run(View view) {


Bundle extras = getIntent().getExtras();

Ali Karim Sir from Mumbra Page 64


Mobile Android Development Chp. 5 Ali Karim Sir

if(extras !=null) {
int Value = extras.getInt("id");
if(Value>0){
if(mydb.updateContact(id_To_Update,name.getText().toString(),
phone.getText().toString(), email.getText().toString(),
street.getText().toString(),
place.getText().toString())){
Toast.makeText(getApplicationContext(), "Updated",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
} else{
Toast.makeText(getApplicationContext(), "not Updated",
Toast.LENGTH_SHORT).show();
}
} else{
if(mydb.insertContact(name.getText().toString(), phone.getText().toString(),
email.getText().toString(), street.getText().toString(),
place.getText().toString())){
Toast.makeText(getApplicationContext(), "done",
Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(getApplicationContext(), "not done",
Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
}
}
}
}
Following is the content of Database class DBHelper.java
package com.example.sairamkrishna.myapplication;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;

public class DBHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "MyDBName.db";


public static final String CONTACTS_TABLE_NAME = "contacts";
public static final String CONTACTS_COLUMN_ID = "id";

Ali Karim Sir from Mumbra Page 65


Mobile Android Development Chp. 5 Ali Karim Sir

public static final String CONTACTS_COLUMN_NAME = "name";


public static final String CONTACTS_COLUMN_EMAIL = "email";
public static final String CONTACTS_COLUMN_STREET = "street";
public static final String CONTACTS_COLUMN_CITY = "place";
public static final String CONTACTS_COLUMN_PHONE = "phone";
private HashMap hp;

public DBHelper(Context context) {


super(context, DATABASE_NAME , null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table contacts " +
"(id integer primary key, name text,phone text,email text, street text,place text)"
);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}

public boolean insertContact (String name, String phone, String email, String street,String
place) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("email", email);
contentValues.put("street", street);
contentValues.put("place", place);
db.insert("contacts", null, contentValues);
return true;
}

public Cursor getData(int id) {


SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts where id="+id+"", null );
return res;
}

public int numberOfRows(){


SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db,
CONTACTS_TABLE_NAME);

Ali Karim Sir from Mumbra Page 66


Mobile Android Development Chp. 5 Ali Karim Sir

return numRows;
}

public boolean updateContact (Integer id, String name, String phone, String email, String
street,String place) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("email", email);
contentValues.put("street", street);
contentValues.put("place", place);
db.update("contacts", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}

public Integer deleteContact (Integer id) {


SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contacts",
"id = ? ",
new String[] { Integer.toString(id) });
}

public ArrayList<String> getAllCotacts() {


ArrayList<String> array_list = new ArrayList<String>();

//hp = new HashMap();


SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts", null );
res.moveToFirst();

while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));
res.moveToNext();
}
return array_list;
}
}
Following is the content of the res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

Ali Karim Sir from Mumbra Page 67


Mobile Android Development Chp. 5 Ali Karim Sir

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp"
android:text="Data Base" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials Point"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="35dp"
android:textColor="#ff16ff01" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true"
android:src="@drawable/logo"/>

<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/scrollView"
android:layout_below="@+id/imageView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true">

<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" >
</ListView>

</ScrollView>

</RelativeLayout>

Ali Karim Sir from Mumbra Page 68


Mobile Android Development Chp. 5 Ali Karim Sir

Following is the content of the res/layout/activity_display_contact.xml


<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".DisplayContact" >

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="370dp"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">

<EditText
android:id="@+id/editTextName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginTop="5dp"
android:layout_marginLeft="82dp"
android:ems="10"
android:inputType="text" >
</EditText>

<EditText
android:id="@+id/editTextEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextStreet"
android:layout_below="@+id/editTextStreet"
android:layout_marginTop="22dp"
android:ems="10"
android:inputType="textEmailAddress" />

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editTextName"
android:layout_alignParentLeft="true"
android:text="@string/name"
android:textAppearance="?android:attr/textAppearanceMedium" />

<Button
android:id="@+id/button1"

Ali Karim Sir from Mumbra Page 69


Mobile Android Development Chp. 5 Ali Karim Sir

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextCity"
android:layout_alignParentBottom="true"
android:layout_marginBottom="28dp"
android:onClick="run"
android:text="@string/save" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editTextEmail"
android:layout_alignLeft="@+id/textView1"
android:text="@string/email"
android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editTextPhone"
android:layout_alignLeft="@+id/textView1"
android:text="@string/phone"
android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/editTextEmail"
android:layout_alignLeft="@+id/textView5"
android:text="@string/street"
android:textAppearance="?android:attr/textAppearanceMedium" />

<EditText
android:id="@+id/editTextCity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/editTextName"
android:layout_below="@+id/editTextEmail"
android:layout_marginTop="30dp"
android:ems="10"
android:inputType="text" />

<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editTextCity"

Ali Karim Sir from Mumbra Page 70


Mobile Android Development Chp. 5 Ali Karim Sir

android:layout_alignBottom="@+id/editTextCity"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/editTextEmail"
android:text="@string/country"
android:textAppearance="?android:attr/textAppearanceMedium" />

<EditText
android:id="@+id/editTextStreet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextName"
android:layout_below="@+id/editTextPhone"
android:ems="10"
android:inputType="text" >

<requestFocus />
</EditText>

<EditText
android:id="@+id/editTextPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextStreet"
android:layout_below="@+id/editTextName"
android:ems="10"
android:inputType="phone|text" />

</RelativeLayout>
</ScrollView>
Following is the content of the res/value/string.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Address Book</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="Add_New">Add New</string>
<string name="edit">Edit Contact</string>
<string name="delete">Delete Contact</string>
<string name="title_activity_display_contact">DisplayContact</string>
<string name="name">Name</string>
<string name="phone">Phone</string>
<string name="email">Email</string>
<string name="street">Street</string>
<string name="country">City/State/Zip</string>
<string name="save">Save Contact</string>
<string name="deleteContact">Are you sure, you want to delete it.</string>
<string name="yes">Yes</string>
<string name="no">No</string>

Ali Karim Sir from Mumbra Page 71


Mobile Android Development Chp. 5 Ali Karim Sir

</resources>
Following is the content of the res/menu/main_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

<item android:id="@+id/item1"
android:icon="@drawable/add"
android:title="@string/Add_New" >
</item>

</menu>

Following is the content of the res/menu/display_contact.xml


<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/Edit_Contact"
android:orderInCategory="100"
android:title="@string/edit"/>

<item
android:id="@+id/Delete_Contact"
android:orderInCategory="100"
android:title="@string/delete"/>

</menu>

This is the defualt AndroidManifest.xml of this project


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >

<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>

Ali Karim Sir from Mumbra Page 72


Mobile Android Development Chp. 5 Ali Karim Sir

<action android:name="android.intent.action.MAIN" />


<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

</activity>

<activity android:name=".DisplayContact"/>

</application>
</manifest>

Let's try to run your application.


I assume you have connected your actual Android Mobile device with your computer.
To run the app from Android studio , open one of your project's activity files and click
Run icon from the tool bar. Before starting your application,Android studio will display
following window to select an option where you want to run your Android application.

Select your mobile device as an option and then check your mobile device which will
display following screen –

Ali Karim Sir from Mumbra Page 73


Mobile Android Development Chp. 5 Ali Karim Sir

Now open your optional menu, it will show as below image: Optional menu appears
different places on different versions

Click on the add button of the menu screen to add a new contact. It will display the
following screen −

Ali Karim Sir from Mumbra Page 74


Mobile Android Development Chp. 5 Ali Karim Sir

It will display the following fields. Please enter the required information and click on save
contact. It will bring you back to main screen.

Now our contact sai has been added.In order to see that where is your database is created.
Open your android studio, connect your mobile.
Go tools/android/android device monitor. Now browse the file explorer tab. Now browse
this folder /data/data/<your.package.name>/databases<database-name>.

Ali Karim Sir from Mumbra Page 75


Mobile Android Development Chp. 5 Ali Karim Sir

Q. Describe Transactions
Ans:
• When we want to execute a series of queries that either all complete or all fail, at that
situation we use transactions which is supported by SQLite.
• When a SQLite transaction fails an exception will be thrown.
There are 3 methods available in transaction for all part of the database object.

a. beginTransactionO: Start a transaction


b. setTransactionSuccessful() : Execute the queries and call we want to commit the
transaction
c. endTransaction() : Once complete the transaction

Program:
sdb.beginTransaction ();
Cursor cur — null;
try
{
cur = sdb.query(‖tbl_countries‖, null, null, null, null, null, null);
cur.moveToPosition (0);
ContentValues values = new ContentValues();
values.put(‖state_name‖, ―Georgia‖);
values.put(‖country_id‖, cur.getString(0));
long stateld = db.insert(‖tbl_states‖, null, values);
db.setTransactionSuccessful();
view.append(‖n‖ + Long. toString (stateld));
}

catch (Exception e)
{
Log.e(‖Error in transaction‖, e.toString();
}

finally
{
db.endTransaction();
cur. close () ;
}

• Start with a call to beginTransaction() to inform SQLite to execute the queries in transaction
mode.
• Begin a try/catch block to handle exceptions thrown by a transaction failure. Perform the
queries and then call setTransactionSuccessful() to inform SQLite that our transaction is
complete.
• If an error isn’t thrown, then endTransactionO can be called to perform the transaction.
Finally close the cursor when we are finished.

Ali Karim Sir from Mumbra Page 76

You might also like