0% found this document useful (0 votes)
25 views7 pages

Mad Unit 5 Imp Questions

The document provides an overview of SQLite in Android, detailing its features, design considerations, and the importance of cursors and content providers. It explains how to perform basic database operations such as creating, updating, and deleting records, as well as the role of the SQLiteOpenHelper class in managing database versions. Additionally, it outlines the steps to create a content provider for sharing data between applications.

Uploaded by

vainu85
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)
25 views7 pages

Mad Unit 5 Imp Questions

The document provides an overview of SQLite in Android, detailing its features, design considerations, and the importance of cursors and content providers. It explains how to perform basic database operations such as creating, updating, and deleting records, as well as the role of the SQLiteOpenHelper class in managing database versions. Additionally, it outlines the steps to create a content provider for sharing data between applications.

Uploaded by

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

Unit-V

SAQs
1. What is SQLite? Explain its features.
Ans)
Android provides structured data persistence through a combination of SQLite databases and
Content Providers. SQLite databases can be used to store application data using a managed,
structured approach. Android offers a full SQLite relational database library. Every application
can create its own databases over which it has complete control. SQLite is embedded into every
android device. Since the database requires limited memory at runtime (approx. 250KB) it is
widely chosen for embedding in devices.
SQLite is a well-regarded relational database management system RDBMS). It is:

1. Open-source
2. Standards-compliant
3. Lightweight
4. Single-tier
It has been implemented as a compact C library that’s included as part of the Android
software stack.
2. What are design consideration of SQLite Database
Ans)
while designing the database we need to keep the following Android-specific
considerations in mind your database.
1. Files (such as bitmaps or audio files) are not usually stored within database tables.
Use a string to store a path to the file, preferably a fully qualified URI.
2. Although not strictly a requirement, it’s strongly recommended that all tables include
an auto-increment key field as a unique index field for each row. If you plan to share
your table using a Content Provider, a unique ID field is required.

3. What is cursor in SQLite database. What is its importance.


Ans)
A cursor represents the result of a query and basically points to one row of the query result.
This way Android can buffer the query results efficiently , as it does not have to load all data
into memory. A query returns a cursor object.
The Cursor class includes a number of navigation functions, which are used to place to
cursor a desired ,location in ResultSet, some of the methods are
1. moveToFirst — Moves the cursor to the first row in the query result
2. moveToNext — Moves the cursor to the next row
3. moveToPrevious — Moves the cursor to the previous row
4. getCount — Returns the number of rows in the result set.
5. getColumnName — Returns the name of the specified column index

4. What is null column hack


Ans)While inserting a record into SQLite Database, If you want to add an empty row to
an SQLite database, by passing in an empty Content Values object, you must also pass in
the name of a column whose value can be explicitly set to null. If you set the null column
hack parameter to null, ,when inserting an empty Content Values object in the insert method
then SQLite will throw an exception.
It’s generally good practice to ensure that your code doesn’t attempt to insert empty Content
Values into an SQLite database.
5. What is importance of content Provider? Give an example.
Ans)
The security model of android does not allow an application to access data from another
application. Still we may want to share data from our app to another app or our app might need
data which can be accessed from another app. Content providers is the best away to share data
across applications.
Content Providers provide an interface for publishing data that will be consumed using a
Content Resolver. They allow you to decouple the application components that consume data
from their underlying data sources, providing a generic mechanism through which
applications can share their data or consume data provided by others. Example: WhatsApp
and contacts App.
6. How to open and create database without SDQLiteDatabase Helper class.
Ans)
If we prefer to manage the creation, opening, and version control of your databases directly,
rather than using the SQLite Open Helper, we can use the application Context’s
openOrCreateDatabase method to create the database itself:

SQLiteDatabase db = context.openOrCreateDatabase(DATABASE_NAME,
Context.MODE_PRIVATE, null);

After we have created the database, we must handle the creation and upgrade logic handled
within the onCreate and onUpgrade handlers of the SQLite Open Helper typically using the
database’s execSQL method to create and drop tables, as required.
7. What is query method in SQLite Library.
Ans)
To execute a query on a Database object, use the query method, passing in the following parameters:
1. An optional Boolean that specifies if the result set should contain only unique value
2. The name of the table to query.
3. A projection, as an array of strings, that lists the columns to include in the result set.
4. A where clause that defines the rows to be returned. we can include ? wildcards that will be
replaced by the values passed in through the selection argument parameter.
5. An array of selection argument strings that will replace the ? wildcards in the where clause.
6. A group by clause that defines how the resulting rows will be grouped.
7. A having clause that defines which row groups to include if you specified a group by
clause.
8. A string that describes the order of the returned rows.
9. A string that defines the maximum number of rows in the result set i.e limit
String table = "table2";
String[] columns = {"column1", "column3"};
String selection = "column3 =?";
String[] selectionArgs = {"apple"};
String groupBy = null;
String having = null;
String orderBy = "column3 DESC";
String limit = "10";
Cursor cursor = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy,
limit);

Long Answer Questions with Answers

1. What is SQLite database? How to create, delete and update rows the database
explain ?
Ans)

SQLiteDataBase is the base class for working with a SQLite database in android and provides
methods to open, query, update and close the database. In addition it provides the execSQL()
method, which allows to execute an SQL statement directly.

Void execSQL (String sql)

Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns
data.
To perform the following database operations, SQLiteDatabase class provides various methods.
a) Insert operations:- for inserting values to the database, we need to save data into
contentvalues object. ContentValues allow defining key/value pairs. The key represents the
table column_name and the value represents the content corresponding to that column.
ContentValues can be used for inserts and updates of database entries.

General Form

Public long insert(String tableName,String null ColumnHack,ContentValues values)

SQLiteDatabase db=this.getWrtitableDatabase();
ContentValues values=new ContentValues();
Values.put(Coulumn1, Value1);
Values.put(Coulumn2, Value2);
Values.put(Coulumn3, Value3);
Values.put(Coulumn4, Value4);

// insert row in table


Long insert=db.insert(TABLE_NAME,null,values);

b) Update Operation:- to update the existing record in your Android sqlite database table,
you need to execute the following method.
General Form

Public int update(String tableName,ContentValues contentValues, String whereClause,


String[] whereArgs)
➢ The first argument takes the name of the table.
➢ The second argument takes a new record. Here, we pass the content value object
which contains data corresponding to each column a key/value pair. So all the
columns which need to get updated are provided in thecontent value object as a
key/value pair.
➢ The third argument specifies the where Clause( it’s a condition) For example update
the employee name where employee id is”123”. Here the where clause is Id=”.
➢ The fourth argument takes the value corresponding to the where clause. For the
above example it is “123”

Update function will return number of rows affected if success, 0 otherwise.

c) Delete operation:- similarly you can perform the delete operation on an Android SQLite
database table. It takes three arguments. The first is the table name, the second is the where
clause and th e third is the value corresponding to that where clause.
General Form
Db.delete(TABLE_NAME,WHERE_CLAUSE,WHERE_ARGUMENTS);

d) Read operation:-to read values from an Android SQLite database table, we must use
cursors. We execute the select operation on the database and we get multiple rows as a
result. We assign those to a cursor. A cursor points to one row at a time. This is how
we get the required data.

RawQuery: This query directly accepts SQL as an input. you can pass SQL statements(s)
and SQLiteDatabase will execute that query for you.
Public Cursor rawQuery (String sql, String[] selectionArgs)

2. What is importance of SQLiteOpenHelper class in SQLite Library.


Ans)
To create and upgrade a database in our Android application we can use the
SQLiteOpenHelper class.
SQLiteOpenHelper is designed to get rid of two very common problems.
1. When the application runs the first time – At this point, we do not yet have a
database. So, we will have to create the tables, indexes, starter data, and so on.
2. When the application is upgraded to a newer schema – Our database will still be on
the old schema from the older edition of the app. We will have option to alter the
database schema to match the needs of the rest of the app.
SQLiteOpenHelper wraps up these logic to create and upgrade a database as per our
specifications. For that we need to create a custom subclass of SQLiteOpenHelper
implementing at least the following three methods
1. Constructor : This takes the Context (e.g., an Activity), the name of the database, an
optional cursor factory and an integer representing the version of the database schema
you are using (typically starting from 1 and increment later).
public DatabaseHelper(Context context)
{
super(context, DB_NAME, null, DB_VERSION);
}
2. onCreate(SQLiteDatabase db) : It’s called when there is no database and the app needs
one. It passes us a SQLiteDatabase object, pointing to a newly-created database, that we
can populate with tables and initial data.
3. onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) : It’s called when the
schema version we need does not match the schema version of the database, It passes us a
SQLiteDatabase object and the old and new version numbers. Hence we can figure out
the best way to convert the database from the old schema to the new one.
The SQLiteOpenHelper class provides the getReadableDatabase() and getWritableDatabase()
methods to get Access to an SQLiteDatabase object either in read or write mode.
3. Write the steps to create Content provider.
Ans)
Content Providers provide an interface for publishing data that will be consumed using a
Content Resolver. They allow you to decouple the application components that consume data
from their underlying data sources, providing a generic mechanism through which applications
can share their data or consume data provided by others. We should also need to override the
onCreate handler to initialize the underlying data source, as well as the query, update, delete,
insert, and getType methods to implement the interface used by the Content Resolver to interact
with the data.

Writing a Content providers


The following are the steps for creating Content providers
1. Create sub class of Content providers
2. Define content URI
3. Implement (or) override the required methods insert(), query(), Update(),
delete(), getType().
4. Declare the Content Provider in Androidmanifest .xml
These steps are explained below with description
1. Create a sub class for Content provider class.
Create a class and extend the content provider class available in the andriod.content package
Public class MycontentProvider extends ContenProvider
2. Defining URI:
Content URI has a special path similar to HTTP. Content provider URI consists of four
parts content://authority/path/id
a. Content:// All the content provider URIs should start with this value.
b. authority’ is java namespace of the content provider implementation (fully
qualified java package name)
c. path’ is the virtual directory within the provider that identifies the kind of
data being requested.
d. id’ is optional part that specifies the primary key of a record being requested.
We can omit this part to request all records.
3. Overriding the required methods
a) Adding new records:
We need to override insert() method of the content Provider to insert new record to the
database via Content provider. The caller method will have to specify the Content provider
URI and the values to be inserted without the ID. Successful insert operation will return the
URIs value with the newly inserted ID.
b) Updating records
To update one (or) more records via Content provider we need to specify the content
provider URL. Update() method of the Content providers Is used to update records. We
have to specify the ID of the record to be updated. to update multiple records, we have to
specify ‘selection’ parameter to indicate which rows are to be updated. This method will
return the number of rows updated.
c) Deleting records
Deleting one or more records is similar to update operations. We need to specify either Id
or ‘selection’ to delete records. The delete() method of the Content providers will return the
number of records deleted.
d) Querying the Content providers
To query the data via content provider we override query() method of Content provide. This
method has many parameters. We can specify list of columns that will be placed in the result
cursor using ‘projection’ parameter. We can specify ‘selection’ criteria, ‘sort Order etc. if
we do not specify projection parameter , all the columns will be included in the result cursor.
if we do not specify sortOrder the provider will choose its own sort order
4. Registering the provider in AndriodManifest.xml
Content providers need to be registered in AndroidManifest.xml. To register the content
providers in manifest file the <provider> element is used. The <application>element is the
parent tag of the <provider> element.
<provider>
android:name=.myprovider”
andriod:authorities=”com.examle.contentproviderexample.MyProvider”>
</provider>

Here authorities is the URI authority to access the Content provider. Typically this will be the
fully qualified name of the content provider class.

You might also like