Android
Android
2. Editor : In this window, the users can create, write, and modify their
code.
3.Tool Window Bar: The tool window bar operates around the outside
of the IDE window and includes the buttons that allow users to
expand or collapse individual tool windows.
Android Studio Main Window
4. Navigation Bar : The navigation bar helps the users to navigate
throughout the project and open files for editing. It helps us to navigate and
modify the required file easily.
5. Status Bar : The status bar displays the current status of the project and
the IDE itself, as well as any warnings or messages during the execution of
the project.
6.Tool Windows: The tool windows give access to specific tasks like project
management, search, version control, and more.
It provides a lot of powerful things. For example, at the second last (From right) of the
Toolbar section, the user can find a search icon where the users can search anything inside
android studio such as searches for:
Classes
Files
Tool Windows
Actions
Settings, etc
Android Studio Tool window
We can use keyboard shortcuts to open tool windows. The below table
provides the list of shortcuts for the most common windows.
<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" />
</android.support.constraint.ConstraintLayout>
MainActivity.java
package com.example.prabu.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Applications
This is where all applications get reside.
Content Providers: They are used to exchange the data between the
apps based on the requests.
Layouts These are used to define the user interface (UI) for an activity or app
These are used to build user interface for an app using UI elements
Views
like buttons, lists, etc.
The onRestart() method will restore the state of activity from the
time that is being stopped.
onDestroy()
The system will invoke onDestroy() method before an activity is
destroyed and this is the final callback method which received
by the android activity.
activity_main.xml
<android.support.constraint.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_constraintHorizontal_bias="0.529"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.136" />
</android.support.constraint.ConstraintLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("ActivityLifeCycle","onCreate is called");
}
@Override
protected void onStart()
{
super.onStart();
Log.i("ActivityLifeCycle","onStart is called");
}
@Override
protected void onResume()
{
super.onResume();
Log.i("ActivityLifeCycle","onResume is called");
}
@Override
protected void onPause()
{
super.onPause();
Log.i("ActivityLifeCycle","onPause is called");
}
@Override
protected void onStop()
{
super.onStop();
Log.i("ActivityLifeCycle","onStop is called");
}
@Override
protected void onDestroy()
{
super.onDestroy();
Log.i("ActivityLifeCycle","onDestroy is called");
}
}
Output in Logcat
Intents
Intent is the message that is passed between components such
as activities, content providers, broadcast receivers, services etc.
Launch an activity
Broadcast a message
Component Description
}
}
Implicit Intents
Explicit Intents
Explicit Intent specifies the component, it helps to invoke
external class.
<TextView
android:id="@+id/resultView"/>
android:textStyle="bold"
android:textSize=“30dp"
</android.support.constraint.ConstraintLayout>
Explicit Intents
ResultActivity.java
package com.example.prabu.explicitintent;
import ……
public class ResultActivity extends AppCompatActivity
{
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
TextView sum = (TextView)findViewById(R.id.resultView);
Intent intent = getIntent();
String addition = (String)intent.getSerializableExtra("SUM");
sum.setText(addition);
}
}
Explicit Intents
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.prabu.explicitintent">
<application
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ResultActivity"
android:label="Explicit Intent - Activity2">
</activity>
</application>
</manifest>
Explicit Intents
Intent Filters
Intent Filter is an expression in app’s manifest file
(ActivityMainfest.xml) and it is used to specify the type of
intents that the component would like to receive.
<category>
It defines the name of an intent category to be accepted and it
must be the literal string value of an action, not the class
constant.
<data>
It defines the type of data to be accepted and by using one or
more attributes we can specify various aspects of the data URI
(scheme, host, port, path) and MIME type.
Intent Filters
activity_main.xml
<android.support.constraint.ConstraintLayout
tools:context=".MainActivity">
<Button
android:id="@+id/sendMail"
android:text="Send Mail"
/>
</android.support.constraint.ConstraintLayout>
Intent Filters
MainActivity.java
package com.example.prabu.intentfilters;
import…..
public class MainActivity extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnSend = (Button)findViewById(R.id.sendMail);
Intent Filters
btnSend.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_EMAIL,new String[]{“[email protected]"});
intent.putExtra(Intent.EXTRA_SUBJECT, "Newsletter");
intent.putExtra(Intent.EXTRA_TEXT, "Sir, I have read this month's newsletter of KL
University. I would like to subscribe to the newsletter");
startActivity(Intent.createChooser(intent,"Choose Mail App"));
}
});
}
}
Intent Filters
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.prabu.intentfilters">
<application
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="message/rfc822"/>
</intent-filter>
</activity>
</application>
</manifest>
Intent Filters
Android Architecture
Linux Kernel
Android is based on Linux 2.6 kernel.
Surface Manager:
It is responsible for composing different drawing surfaces onto the
screen.
Open GL/ES:
Open GL/ES is a 3D library.
We have a software implementation that accelerates hardware if the
device has 3D chip on it.
SGL:
SGL are for 2D Graphics and that is what most of our application
drawing is based on.
In android 2D and 3D can be combined in the same application.
Native Libraries
Media Framework:
It is provided with Packet Video, one of the members of the Open
Handset Alliance and that contains all of the CODECs that make up
the core of media experience.
MPEG4, H.264, MP3, AAC, all the audio and video CODEC’s are
found which are needed to build rich media experience.
These are byte codes that are the results of converting at build time(.class
and .jar files).
These files when they are converted to .dex become a much efficient byte
code that can run well on small processors.
They use memory very efficiently, the data structures are designed to be
shared across processes whenever possible and uses a highly CPU
optimized interpreter.
These applications use the one that come with the phone like the
home application and phone application includes application
written by Google and us.
Application Framework
Activity Manager:
It manages the lifecycle of application.
It also maintains the common back stack so that applications
running in different processes have a smoothly integrated
navigation experience.
Package Manager:
It keeps track of which applications are installed in the device.
It is responsible for the what are the applications installed and
capabilities of each application.
Application Framework
Window Manager:
It manages windows, it’s mostly a JAVA programming language
abstraction on top of lower level services that are provided by
surface manager.
Telephony Manager:
It contains the API’s that we use to build the phone application that’s
central to the phone application.
Application Framework
Content Providers:
It is a unique piece of the android platform.
It is the framework that the application shares the data with other
application.
Resource Manager:
It is used to store localized strings, Bitmaps, layout file descriptions,
all of the external parts of an application that are hard-coded.
Application Framework
View System:
It contains buttons, lists, all the building blocks of User Interfaces
(UI) and also can handle things like event dispatch, layout, drawing.
Horizontal Vertical
Linear Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:id="@+id/To"
android:hint="To" />
<EditText
android:id="@+id/Subject"
android:hint="Subject" />
<EditText
android:id="@+id/Message"
android:hint="Message" />
<Button
android:id="@+id/Send"
android:layout_gravity="right"
android:text="Send" />
</LinearLayout >
Linear Layout
Relative Layout
Relative Layout is a ViewGroup which is used to specify the
position of child View instances relative to each other (Child A
to the left of Child B) or relative to the parent (Aligned to the
top of parent).
Relative Layout
Following is the pictorial representation of relative layout
Relative Layout
<RelativeLayout xmlns:android=http://schemas.android.com/apk/res/android
tools:context=".MainActivity">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:text="Button1" />
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="Button2" />
Relative Layout
<Button
android:id="@+id/btn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Button3" />
<Button
android:id="@+id/btn4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Button4" />
Relative Layout
<Button
android:id="@+id/btn5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/btn2"
android:layout_centerHorizontal="true"
android:text="Button5" />
<Button
android:id="@+id/btn6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/btn4"
android:layout_centerHorizontal="true"
android:text="Button6" />
Relative Layout
<Button
android:id="@+id/btn7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_toEndOf="@+id/btn1"
android:layout_toRightOf="@+id/btn1"
android:text="Button7" />
</RelativeLayout>
Relative Layout
Frame Layout
Frame layout is a ViewGroup subclass which is used to specify
the position of View instances it contains on the top of each
other to display only single View inside the Frame Layout.
<ImageView
android:id="@+id/imgvw1"
android:layout_width="match_parent"
android:layout_height="505dp"
android:scaleType="fitEnd"
android:src="@drawable/paris" />
<TextView
android:id="@+id/txtvw1"
android:background="#4C374A"
android:padding="10dp"
android:text="Eiffel Tower"
android:textColor="#FFFFFF"
android:textSize="20sp" />
Frame Layout
<TextView
android:id="@+id/txtvw2"
android:layout_gravity="right|bottom"
android:background="#AA000000"
android:padding="10dp"
android:text="25/Aug/2018"
android:textColor="#FFFFFF"
android:textSize="18sp" />
</FrameLayout>
Frame Layout
Table Layout
Table Layout is a ViewGroup subclass which is used to display
the child View elements in rows and columns.
Following is the pictorial representation of table layout
Table Layout
<TableLayout xmlns:android=http://schemas.android.com/apk/res/android
tools:context=".MainActivity">
<TableRow
android:background="#0079D6"
android:padding="5dp">
<TextView
android:layout_weight="1"
android:text="User ID" />
<TextView
android:layout_weight="1"
android:text="User Name" />
<TextView
android:layout_weight="1"
android:text="Location" />
</TableRow>
Table Layout
<TableRow android:background="#DAE8FC" android:padding="5dp">
<TextView
android:layout_weight="1"
android:text="1" />
<TextView
android:layout_weight="1"
android:text="ARU N" />
<TextView
android:layout_weight="1"
android:text="Hyderabad" />
</TableRow>
Table Layout
<TableRow android:background="#DAE8FC" android:padding="5dp">
<TextView
android:layout_weight="1"
android:text="3" />
<TextView
android:layout_weight="1"
android:text="CHANDRU" />
<TextView
android:layout_weight="1"
android:text="GUNTUR" />
</TableRow>
</TableLayout>
Table Layout
Constraint Layout
Constraint Layout allows you to create large and complex
layouts with a flat view hierarchy (no nested view groups).
It's similar to Relative Layout in that all views are laid out
according to relationships between sibling views and the parent
layout, but it's more flexible than Relative Layout.
Constraint Layout
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
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" />
</android.support.constraint.ConstraintLayout>
Constraint Layout
Android Menus
Menus are a common user interface component in many types
of applications.
We can simply define the menu and all its items in XML menu resource
instead of building the menu in the code and also load menu resource as menu
object in the activity or fragment used in our android application.
Unit IV Chapter 2
Data Storage 1
Storage Options
• Android provides several options to save persistent application data depends on your
specific needs, such as whether data should be private to your application or
accessible to other applications (and user) and how much space your data requires.
• Android provides a way to expose even your private data to other applications — with
a content provider. A content provider is an optional component that exposes
read/write access to your application data, subject to whatever restrictions you want to
impose.
1. Shared Preferences
• Store private primitive data in key-value pairs.
• The SharedPreferences class provides a general framework that allows you to save
and retrieve persistent key-value pairs of primitive data types. You can use
SharedPreferences to save any primitive data: booleans, floats, ints, longs, and
strings. This data will persist across user sessions (even if your application is killed).
2. Internal Storage
• Store private data on the device memory.
• You can save files directly on the device's internal storage. By default, files saved to
the internal storage are private to your application and other applications cannot
access them (nor can the user). When the user uninstalls your application, these files
are removed.
• Saving cache files
• These are temporary files which may be deleted by system when internal storage
is low.
Storage Options
• These are removed when application is uninstalled.
• However, you should not rely on the system to clean up these files for you. You
should always maintain the cache files yourself and stay within a reasonable limit of
space consumed, such as 1MB. When the user uninstalls your application, these
files are removed.
3. External Storage
• Store public data on the shared external storage.
• Every Android-compatible device supports a shared "external storage" that you can use
to save files. This can be a removable storage media (such as an SD card) or an
internal (non-removable) storage. Files saved to the external storage are world-
readable and can be modified by the user when they enable USB mass storage to
transfer files on a computer.
• CAUTION! External storage can become unavailable without warning, if it is removed.
4. SQLite Databases
• Store structured data in a private database.
5. Network Connection
• Store data on the web with your own network server.
• To do network operations, use classes in the following packages:
• java.net.* • android.net.*
Data Base Management using SQLite
• SQLite is an open-source SQL database that stores data to a text file on a
device.
• SQLite is a software library that implements a self-contained, server-less, zero-
configuration, transactional SQL database engine. SQLite is the most widely
deployed SQL database engine in the world. It was designed in year 2000.
• SQLite supports all the relational database features. In order to access this
database, you don't need to establish any kind of connections for it like
JDBC,ODBC etc.
• SQLite transactions are fully ACID-compliant.
• ACID(Atomicity, Consistency, Isolation, Durability)
• SQLite is case insensitive.
SQLite Database
• Android applications can have application databases
powered by SQLite
– It is a open source relational SQL database that stores data to a
text file on a device.
– Lightweight and file-based, ideal for mobile devices
– Databases are private for the application that creates them
– Databases should not be used to store files
– It performs database operations on android device such as storing,
manipulating or retrieving persistent data from the database.
• SQLite is a light weight database
– Atomic
– Stable
– Independent
– Enduring
– Only several kilobytes
– Only partly support some SQL commands such as ALTER, TABLE.
• SQLite is included as part of Android’s soIware stack
• More info about SQLite at http://www.sqlite.org
5
Contd.
• It is embedded in android by default. So there is no
need to perform any database setup or administration
task.
• Here, we are going to see the example of SQLite to
store and fetch data.
• Steps involved for using SQLite databases:
1. Create a database
2. Open the database
3. Create a table
4. Create and insert interface for datasets
5. Create a query interface for datasets
6. Close the database
• Good practice to create a Database Adapter class to
simplify your database interactions
Data Storage 6
Data Base Management using SQLite
Examining the Database Files
• Databases are stored in the /data/data/<package-name>/databases
directory.
• Run your app in emulator and click on Tools > Android > Android Device
Monitor from Android Studio.
• All steps are given in next slide.
• This database is saved on mobile. If you want to see its contents in your
local PC, you can export it by clicking the button Pull a file from the Device.
Save it wherever you want.
• If you have SQLite installed on your computer, you can use its terminal to
view this database.
• Another way is to use FireFox plugin. Open FireFox, go to settings. Click on
AddOns. Search for AddOns called SQLite.
• If you don’t see it, go to following link;
• https://addons.mozilla.org/en-US/firefox/addon/sqlite-manager/
• Install the SQLite Manager from there. Restart your browser now.
• Go to Settings, and click on Customize. Drag and drop SQLite Manager in
Tools to quickly view it every time.
• Now you can Browse you database. Be sure to select All Files before
browsing otherwise your database will not be shown.
Contd.
SQLiteOpenHelper
android.database.sqlite.SQLiteOpenHelper
• It is a helper class to manage database creation and version management.
Public Constructor
SQLiteOpenHelper(Context context, String name, Create a helper object to create,
SQLiteDatabase.CursorFactory factory, int version) open, and/or manage a database.
Public Methods
synchronized void close() Close any open database object.
Return the name of the SQLite database
String getDatabaseName()
being opened, as given to the constructor.
SQLiteDatabase getReadableDatabase() Create and/or open a database.
Create and/or open a database that will
SQLiteDatabase getWritableDatabase()
be used for reading and writing.
Called when the database is created for
abstract void onCreate(SQLiteDatabase db)
the first time.
onDowngrade(SQLiteDatabase db, int Called when the database needs to be
void
oldVersion, int newVersion) downgraded.
Called when the database has been
void onOpen(SQLiteDatabase db)
opened.
onUpgrade(SQLiteDatabase db, int Called when the database needs to be
abstract void
oldVersion, int newVersion) upgraded.
SQLiteDatabase
android.database.sqlite.SQLiteDatabase
• Database names must be unique within an application, not across all
applications.
Public Methods
static SQLiteD create(SQLiteDatabase.CursorFactory fact Create a memory backed SQLite database.
atabase ory)
int delete(String table, String whereClause, Str Convenience method for deleting rows in the
ing[] whereArgs) database.
static boolean deleteDatabase(File file) Deletes a database including its journal file and other
auxiliary files that may have been created by the
database engine.
void execSQL(String sql) Execute a single SQL statement that is NOT a
SELECT or any other SQL statement that returns data.
void execSQL(String sql, Object[] bindArgs) Execute a single SQL statement that is NOT a
SELECT/INSERT/UPDATE/DELETE.
long getMaximumSize() Returns the maximum size the database may grow to.
final String getPath() Gets the path to the database file.
int getVersion() Gets the database version.
long insert(String table, String nullColumnHack, Convenience method for inserting a row into the
ContentValues values) database.
static SQLiteD openDatabase(String path, SQLiteDatabas Open the database according to the
atabase e.CursorFactory factory, int flags OPEN_READWRITE OPEN_READONLY CREA
flags, DatabaseErrorHandler errorHandler) TE_IF_NECESSARY and/or NO_LOCALIZED_COLLA
TORS.
Contd.
Public Methods
static SQLiteData openDatabase(String path, SQLiteDatabase.CursorFa Open the database according to the
base ctory factory, int flags) flags OPEN_READWRITE OPEN_REA
DONLY CREATE_IF_NECESSARY an
d/or NO_LOCALIZED_COLLATORS.
static SQLiteData openOrCreateDatabase(String path, SQLiteDatabase. Equivalent to openDatabase(path,
base CursorFactory factory, DatabaseErrorHandler errorHan factory, CREATE_IF_NECESSARY,
dler) errorHandler).
Cursor query(String table, String[] columns, String selection, S Query the given table, returning
tring[] selectionArgs, String groupBy, String having, Stri a Cursor over the result set.
ng orderBy, String limit)
Cursor rawQuery(String sql, String[] selectionArgs, Cancellatio Runs the provided SQL and returns
nSignal cancellationSignal) a Cursor over the result set.
Runs the provided SQL and returns
a Cursor over the result set.
long setMaximumSize(long numBytes) Sets the maximum size the database
will grow to.
void setVersion(int version) Sets the database version.
String toString() Returns a string containing a concise,
human-readable description of this
object.
int update(String table, ContentValues values, String wher Convenience method for updating rows
eClause, String[] whereArgs) in the database.
Cursor
android.database.Cursor
• This interface provides random read-write access to the result set returned by
a database query.
Public Methods
Closes the Cursor, releasing all of its resources and making it
abstract void close()
completely invalid.
copyStringToBuffer(int
Retrieves the requested column text and stores it in the buffer
abstract void columnIndex, CharArrayBuffer
provided.
buffer)
abstract int getColumnCount() Return total number of columns
getColumnIndex(String Returns the zero-based index for the given column name, or -
abstract int
columnName) 1 if the column doesn't exist.
Returns a string array holding the names of all of the columns
abstract
getColumnNames() in the result set in the order in which they were listed in the
String[]
result.
abstract int getCount() Returns the numbers of rows in the cursor.
abstract
getDouble(int columnIndex) Returns the value of the requested column as a double.
double
abstract
getExtras() Returns a bundle of extra values.
Bundle
abstract float getFloat(int columnIndex) Returns the value of the requested column as a float.
abstract int getInt(int columnIndex) Returns the value of the requested column as an int.
abstract int getPosition() Returns the current position of the cursor in the row set.
abstract
getString(int columnIndex) Returns the value of the requested column as a String.
String
Cursor
Public Methods
Returns data type of the given column's
abstract int getType(int columnIndex)
value.
Returns whether the cursor is pointing to
abstract boolean isAfterLast()
the position after the last row.
Returns whether the cursor is pointing to
abstract boolean isBeforeFirst()
the position before the first row.
abstract boolean isClosed() return true if the cursor is closed
Returns whether the cursor is pointing to
abstract boolean isFirst()
the first row.
Returns whether the cursor is pointing to
abstract boolean isLast()
the last row.
Returns true if the value in the indicated
abstract boolean isNull(int columnIndex)
column is null.
abstract boolean moveToFirst() Move the cursor to the first row.
abstract boolean moveToLast() Move the cursor to the last row.
abstract boolean moveToNext() Move the cursor to the next row.
abstract boolean moveToPosition(int position) Move the cursor to an absolute position.
abstract boolean moveToPrevious() Move the cursor to the previous row.
ContentValues
android.content.ContentValues
• This class is used to store a set of values.
Public Constructors
ContentValues() Creates an empty set of values using the default initial size
ContentValues(int size) Creates an empty set of values using the given initial size
Public Methods
void clear() Removes all values.
Returns true if this object has the named
boolean containsKey(String key)
value.
Compares this instance with the specified
boolean equals(Object object)
object and indicates if they are equal.
Object get(String key) Gets a value.
Boolean getAsBoolean(String key) Gets a value and converts it to a Boolean.
Byte getAsByte(String key) Gets a value and converts it to a Byte.
byte[] getAsByteArray(String key) Gets a value that is a byte array.
Double getAsDouble(String key) Gets a value and converts it to a Double.
Float getAsFloat(String key) Gets a value and converts it to a Float.
Integer getAsInteger(String key) Gets a value and converts it to an Integer.
String getAsString(String key) Gets a value and converts it to a String.
void put(String key, Byte value) Adds a value to the set.
void put(String key, Integer value) Adds a value to the set.
SQLite Example: Contact data?
public class Contact {
int _id;
String _name;
String _phone_number;
public Contact(){ }
public Contact(int id, String name, String _phone_number){
this._id = id;
this._name = name;
this._phone_number = _phone_number;
}
Data Storage 15
Contd.
public int getID(){
return this._id;
}
public void setID(int id){
this._id = id;
}
public String getName(){
return this._name;
}
public void setName(String name){
this._name = name;
}
public String getPhoneNumber(){
return this._phone_number;
}
public void setPhoneNumber(String phone_number){
this._phone_number = phone_number;
}
}
Data Storage 16
Contd.
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
Data Storage 17
Contd.
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS +
"(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
Data Storage 18
Contd.
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
//2nd argument is String containing nullColumnHack
db.close(); // Closing database connection
}
Data Storage 19
Contd.
// code to get the single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Data Storage 20
Contd.
// code to update the single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
Data Storage 22
Accessing Content
• Applications access the content through a
ContentResolver instance
– ContentResolver allows querying, inserting, deleting and
updating data from the content provider
ContentResolver cr = getContentResolver();
Data Storage 23