Graphical Primitives and Databases
Graphical Primitives and Databases
Statement Purpose:
Student will learn about Graphical Primitives.
Activity Outcomes:
After completing this chapter students will be able to develop and complete hands on android designing.
- Introduction to SQLite
- Android Database API
- Using Content Provider
- Connecting with Database Server
Instructor Note:
Introduction
Students must read and have best practice of past four lecture.
Introduction to SQLite
Android SQLite database is an integral part ―built-in‖ component. SQLite is an Open Source database. SQLite supports standard relational database features like SQL syntax, transactions and prepared statements. It is a self-contained, transactional database engine that requires no separate server process. To use this database the knowledge of SQL alone sufficient. We need not to learn any new query language.
SQLite supports the data types such as TEXT (similar to String in Java), INTEGER (similar to long in Java) and REAL (similar to double in Java). All other types must be converted into one of these fields before getting saved in the database. SQLite does not validate, whether the data stored in to the columns are actually of the defined type, e.g. we can write an integer into a string column and vice versa.
SQLite is embedded into every android device. Since the database requires limited memory at runtime (approx. 250 KByte) it is widely chosen for embedding in devices. Android platform includes the SQLite embedded database and provides APIs to access the database. To use the SQLite database in android, we do not require a setup procedure.
We need to only have to define the SQL statements for creating and updating the database. Then the database will be managed by the android system. Access to the SQLite database
involves accessing the file system. This can be slow. Therefore it is recommended to perform database operations asynchronously. If our application creates a database, this database is stored by default in the following directory DATA/data/APP_NAME/databases/FILENAME.
The parts of the above directory have been explained below..
- DATA is the path which the getDataDirectory() method returns.
- APP_NAME is our application
- FILENAME is the name wespecify in our code for the database. Android Database API
The android.database package contains all necessary classes for working with databases. The android.database.sqlite package contains the SQLite specific classes. The following classes will be helpful while developing app that uses database.
- SQLiteDataBase
- Cursor
- SQLiteOpenHelper
SQLiteDatabase
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.
To perform the following database operations, SQLiteDatabase class provides various methods.
Insert operation – For inserting values to the database, we need to save data into ContentValues allow defining key/value pairs. The key represents the table column name and the value represents the content corresponding to that column.
The object ContentValues allows to define key/values. The key represents the table column identifier and the value represents the content for the table record in this column.
ContentValues can be used for inserts and updates of database entries.
Update Operation: To update the existing record in your Android sqlite database table, you need to execute the following method.
db.update(TABLE_NAME,content_values,WHERE_CLAUSE,WHERE_ARGUMENTS);
- 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 in a key/value pair. So, all the columns which need to get updated are provided in the content 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 emloyee ID is ―123‖. Here, the where clause is the ―id=‖.
- The fourth argument takes the value corresponding to the where clause. For the above example it is ―123‖.
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 the third is the value corresponding to that where clause.
db.delete(TABLE_NAME,WHERE_CLAUSE,WHERE_ARGUMENTS);
Read Operation:
To read values from an Android SQLite database table, we need to learn about cursors. We execute the select operation on the database and we get multiple rows as a result. We assign those rows to a cursor. A Cursor points to one row at a This is how we get the required data.
Raw Query: This query directly accepts SQL as an input. You can pass SQL statement(s) and SQLiteDatabase will execute that query for you.
db.rawQuery(sql_statement,null);
Cursor
A query returns a Cursor object. 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.
To get the number of elements of the resulting query use the getCount() method. To move between individual data rows, you can use the moveToFirst() and moveToNext() methods. The isAfterLast() method allows to check if the end of the query result has been reached.
Cursor provides typed get*() methods, e.g. getLong(columnIndex), getString(columnIndex) to access the column data for the current position of the result. The “columnIndex” is the number of the column you are accessing. Cursor also provides the getColumnIndexOrThrow(String) method which allows to get the column index for a column name of the table. A Cursor needs to be closed with the close() method call.
SQLiteOpenHelper
To create and upgrade a database in our Android application we can used the SQLiteOpenHelper class.
• onCreate()
– is called by the framework, if the database is accessed but not yet created.
- onUpgrade() – called, if the database version is increased in your application code. This method allows you to update an existing database schema or to drop the existing database and recreate it via the onCreate()
- Both methods receive an SQLiteDatabase object as parameter which is the Java representation of the database.
- The SQLite Open Helper class provides the getReadableDataBase() and getWriteableDatabase() methods to get access to an SQLiteDatabase object; either in read or write mode. The database tables should use the identifier _id for the primary key of the table. Several Android functions rely on this Enhancing the display of Records After retrieving the records, we need to display them to user. While displaying records, we need to choose the UI control. The following UI controls will be helpful for displaying more number of records from database to the user.
- ListViews are Views which allow to display a list of elements.
- ListActivities are specialized activities which make the usage of ListViews easier.
- The SimpleCursorAdapter class will map the columns to the Views based on the Cursor passed to The SimpleCursorAdapter allows to set a layout for each row of the ListViews.
You also define an array which contains the column names and another array which contains the IDs of Views which should be filled with the data Using Content Provider.
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 provider is the best way to share data across applications. Content provider is a set of data wrapped up in a custom API to read and write. Applications/Processes have to register themselves as a provider of data. Other applications can request android system to read/write that data through a predefinedAPI. Content provider API adheres to CRUD principle.
Content Provider Workflow :
Examples for content provider are Contacts that exposes user information to other applications, Media store which allows other applications to access and store media files etc.
Content providers are simple interfaces which uses standard insert(), query(), update(), delete() methods to access app data. A special URI starting with content:// will be assigned to each content providers and that will be recognized across applications or apps.
Above diagram shows how content provider works. App 1 stores its data in its own database and provides a content provider. App 2 communicates access App 1’s data through the content provider.
Writing a Content Provider
To the following are the steps for creating a content provider.
- Create sub class for ContentProvider.
- Define content URI
- Implement or override the required insert(), update(), query(), delete(), getType().
- Declare the content provider in AndroidManifest.xml The steps are explained below with description.
Create a subclass for ContentProvider
Create a class and extend the ContentProvider class available in the android.content package.
Defining URI
Content URI has a special path similar to HTTP. Content provider URI consists of four parts. content://authority/path/id
- content:// All the content provider URIs should start with this value
- ‘authority’ is Java namespace of the content provider (fully qualified Java package name)
- ‘path’ is the virtual directory within the provider that identifies the kind of data being requested.
- ‘id’ is optional part that specifies the primary key of a record being requested. We can omit this part to request all records.
Overriding the required methods
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 URI value with the newly inserted ID.
Updating records
To update one or more records via content provider we need to specify the content provider URI. update() method of the Content Provider 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.
Deleting records
Deleting one or more records is similar to update operation. We need to specify either ID or ‘selection’ to delete records. The delete() method of the ContentProvider will return the number of records deleted.
Querying the content provider
To query the data via content provider we override query() method of Content Provider. 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, ‘sortOrder’ etc. If we do not specify ‗projection‘ parameter, all the columns will be included in the result cursor. If we do not specify sort Order the provider will choose its own sort order.
getType() method
be the fully qualified name of the content provider class.
WebView
Android WebView component used in Android web app to render the android apps GUI. Web view component is a browser supported view and it allows us implementing web pages in our android application as we like. WebView gives most of the screen space in our android application.
Android Web App or Android Hybrid App
Android web app is actually a mix of web app and native android app. The app is developed using support of Android components and web technologies inside a WebView. It contain web technologies like HTML, CSS, JavaScript, SVG, Json, Ruby, Rails etc., Another common term for an Android web app is Android hybrid app.
WebView is Based on Chrome
The WebView component is fully based on same code as Chrome for android. It indicates that web app which supported in Chrome browser that can be converted into Android App. From Android 4.4 Chrome replacing the old android browser as default/ builtin browser.
WebView Needs Internet Permission
In the Android application Internet permission is mandatory if app needs to load a webpage. While installing an app the user should accepts the internet access permission. To get the internet permission in the android app, internet permission element is to add in manifest file.
Lab Activities:
Activity 1:
Step 1: Create an android project using android studio.
Step 2: After creating the project, open the java file named MainActivity.xml. MainActivity.java package com.example.kamarajios33.graphics; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.view.View; public class MainActivity extends AppCompatActivity { DemoView dv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); dv = new DemoView(this); setContentView(dv); } private class DemoView extends View { public DemoView(Context context) { super(context); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Paint ob=new Paint();
ob.setStyle(Paint.Style.FILL); ob.setColor(Color.WHITE); canvas.drawPaint(ob);
ob.setColor(Color.GRAY); canvas.drawCircle(100, 100, 60, ob); ob.setColor(Color.CYAN);
canvas.drawCircle(200, 50, 30, ob); ob.setColor(Color.MAGENTA); canvas.drawRect(200,
200, 400, 400, ob); ob.setColor(Color.RED); canvas.drawLine(250,50,350,400,ob); canvas.rotate(-45); }}}
Step 3: The output of the above code is as follows.
Activity 2:
Running the SQLite App
Step 1: Create an android project using android studio
Step 2: Create two resource files (*.xml) and two activity files (*.java) namedactivity_main.xml & activity_main2.xml and MainActivity.java & Main2Activity.java.
Step 3: Open res directory -> layout -> activity_main.xml -> Click -> Design button atbottom of the Android Studio. Put the necessary components for both resource files (activity_main.xml, activity_main2.xml)
Step 4: Design (After the design part, the xml code will be generated automatically inthe layout file )
This method is used to handle requests for the MIME type of data at the given URI. We use either vnd.android.cursor.item or vnd.android.cursor.dir/ The vnd.android.cursor.item is used to represent specific item. Another one is used to specify all items.
Registering the provider in AndroidManifest.xml
Content providers need to be registered in the 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.
Create an activity file
MainActivity.java
package com.example.kamarajios33.database;
import android.app.AlertDialog; import android.content.Intent; import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity;
import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TableRow; import android.widget.Toast;
public class MainActivity extends AppCompatActivity { SQLiteDatabase db;
String f,l,e; @Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); db = openOrCreateDatabase(“Mydb”,MODE_PRIVATE,null);
db.execSQL(“CREATE TABLE IF NOT EXISTS student(fname VARCHAR,lname VARCHAR,email VARCHAR);”);
}
public void Adddata(View view)
{
EditText e1 = (EditText)findViewById(R.id.e1); EditText e2 = (EditText)findViewById(R.id.e2);
EditText e3 = (EditText)findViewById(R.id.e3); f = e1.getText().toString(); l=e2.getText().toString(); e=e3.getText().toString();
db.execSQL(“INSERT INTO student VALUES(‘”+f+”‘,'”+l+”‘,'”+e+”‘);”);
T o a s t . m a k e T e x t ( g e t A p p l i c a t i o n C o n t e x t ( ) , ” R o w Inserted”,Toast.LENGTH_SHORT).show();
public void close(View view)
{
System.exit(0);
}
public void showdata(View view)
{
//Toast.makeText(getApplicationContext(),”Show Data”,Toast.LENGTH_LONG).show(); Intent i = new Intent(getApplicationContext(),Main2Activity.class);
startActivity(i);
}
}
Main2Activity.java
package com.example.kamarajios33.database;
import android.content.Intent; import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle;
import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast;
public class Main2Activity extends AppCompatActivity { EditText fn,ln,em;
Button next,back,prev; SQLiteDatabase db; Integer j =0; @Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); cseitquestions.blogspot.in cseitquestions.blogspot.in setContentView(R.layout.activity_main2); fn=(EditText)findViewById(R.id.fn); ln=(EditText)findViewById(R.id.ln); em=(EditText)findViewById(R.id.em); back
=(Button)findViewById(R.id.button2); next=(Button)findViewById(R.id.button); prev=(Button)findViewById(R.id.b3);
db = openOrCreateDatabase(“Mydb”,MODE_PRIVATE,null);
final Cursor c = db.rawQuery(“select * from student”,null); c.moveToFirst(); fn.setText(c.getString(c.getColumnIndex(“fname”))); ln.setText(c.getString(c.getColumnIndex(“lname”))); em.setText(c.getString(c.getColumnIndex(“email”))); back.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View v) {
Intent il = new Intent(getApplicationContext(), MainActivity.class); startActivity(il); System.exit(0);
} });
next.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try
{ c.moveToNext(); fn.setText(c.getString(c.getColumnIndex(“fname”))); ln.setText(c.getString(c.getColumnIndex(“lname”))); em.setText(c.getString(c.getColumnIndex(“email”)));
} catch (Exception e) {
Toast.makeText(getApplicationContext(),”Last Record”,Toast.LENGTH_LONG).show(); e.printStackTrace();
} }});
prev.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try
{ c.moveToPrevious(); fn.setText(c.getString(c.getColumnIndex(“fname”))); ln.setText(c.getString(c.getColumnIndex(“lname”))); em.setText(c.getString(c.getColumnIndex(“email”)));
}
catch (Exception e)
{ Toast.makeText(getApplicationContext(),”First Record”,Toast.LENGTH_LONG).show(); e.printStackTrace();
}}
});
}}
Step 6: Run the project. While running, the following output will be shown in the emulator.
Home Activities:
- Write XML code for generating the following layout. And send the information of both edit texts via email, sms and save in database. After saving in database, wait for 5 sec and move to next activity to get a view of database.