* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download SQLITE TUTORIAL in android
Open Database Connectivity wikipedia , lookup
Entity–attribute–value model wikipedia , lookup
Concurrency control wikipedia , lookup
Microsoft Jet Database Engine wikipedia , lookup
Extensible Storage Engine wikipedia , lookup
Relational model wikipedia , lookup
Clusterpoint wikipedia , lookup
Introduction: Most of the applications require the data to be saved and loaded when it is demanded. As we see in games that whole game is saved and later on this is loaded again. You also want to store user preferences so that user may customize application and store data entered by the user. Android Methods for saving data Shared Preferences: When you want a limited application data such as user preferences related to application UI, you prefer to store data using Shared Preferences. In this method you store data as key values pairs. Files: In android you are allowed to create and read/write to files. You can create files on the internal or external media of the device. SQLite Database: Android also facilitates to work with relational database system. The Database system used in android is SQLite Database system. Content Provider: Content Providers let you expose a well-defined interface for using and sharing private data. You can control access to Content Providers using the standard permission system. Here we are going to discuss how SQLite database is used to save data in android. Firstly, let’s have a brief introduction about SQLite database system. SQLite Database SQLite database is a Zero configuration (as it is default database provided embedded in android so no configuration is required) Lightweight ( requires minimum memory) Open source (no license) Single database file (Only one file is made against one database) If an application creates a database it is stored in following directory DATA/data/APP_NAME/databases/FILENAME. Before starting to work with database let’s discuss essential concepts which can help in understanding the topic. 1. SQL: SQL is a structured query language that is used for database manipulation. It provides simple queries to create and manipulate database system. Let’s start from data retrieval using SQL. 1.1 Select statement Select statement is used to get data from database system. The syntax of using select statement is as follow. Select col1,col2….coln From TableName where some condition order by column E.g. select rollno from students where name=’Asad’ To get all columns of a table use * as select * from students 1.2 Data Definition 1.2.1 create table This statement is used to create a new table if it does not exist. The syntax is as follow. CREATE TABLE newtable( Col1 INT, Col2 VARCHAR(50), col3 DATE NOT NULL, PRIMARY KEY (col1, col2) ); Example: create table users (uid int primary key, password varchar(50)); 1.2.2 Drop table This statement is used to drop a table from database system if it exist. Syntax is as follow. Drop table tablename Example: drop table users 1.2.3 Alter table Alter table statement is used to update table definition. Syntax is as follow: Update table tableName Add columnName type; Example: Update table users Add age int; 1.3 Data Manipulation 1.3.1 Insert statement Insert statement is used to add records in database system. Syntax is as follow: Insert into tablename(col1,col2,…,coln) values(v1,v2,…vn); Example: insert into users(uid,password) values(12,’abcd123’); 1.3.2 Delete statement Delet statement is used to delete records in database system. Syntax is as follow: Delete from tablename where somecondition; Example: Delete from users where uid=12; Delete from users will delete all records from database. 1.3.3 update statement Update statement is used to update records in database system Syntax is as follow: Update table tableName set col1=v1 where col2=v2 Example: Update table users set password=’6t8979’ where uid=12 2. Packages to use SQLite Database Following packages are used to work with SQLite Database system android.database android.database.sqlite 3. SQLiteopenHelper To create and upgrade database in our application we need a class that extends SQLiteOpenHelper class. To use it we have to override two abstract methods onCreate() and onUpgrade(). SQLiteOpenHelper provides following methods: onCreat(): this method is called when database does not exist. onUpgrade(): this method allow you to update or alter database schema. getReadableDatabase(): create or/and open a database for only data reading. getWriteableDatabase():create or/and open a database for both data reading and writing. close(): close the database if it is opened. onOpen(): this method is called when a database is opened. 4. ContentValues ContentValues is a data structure used to store key and corresponding values. Keys represent columns in database and values are their values. This is helpful for inserting and updating records in database. 5. SQLiteDataBase class This is base class to work with database system. This class has methods to manage database. It provides useful methods to insert a record delete a record and update a record in a database. All manipulation of database is done through this class. Some most commonly used methods of this class are given bellow: insert(String tableName, String nullColumnHack, ContentValues contentValues); this method is used to insert a record in a database table. delete(String table, String whereClause, String[] whereArgs) this method is used to delete a record from database table. update (String table, ContentValues contentValues,String whereClause, String[] whereArgs) this method is used to delete a record from database table. this method is used to select records from database table and return cursor object. we will learn cursor a little bit later. <Example:rawQuery("select * from users where uid = ?", new String[] { id }); query(String table, String[] columns, String selection, String[] Args, String groupByClause, String havingClause, String orderByClause, String NoOfRowsToBeFethed) this method executes given query and return cursor object. 6. Cursor Cursor is just like ResultSet in java. It contains all the records retrieved in form of result of a query. Cursor has number of methods to manipulate returned data. Some of them are as follow: MoveToNext() Move cursor to next record MoveToPrevious() Move cursor to previous record MoveToFirst() Move cursor to first record MoveToLast() Move cursor to last record MoveToPosition(int p) Move cursor to a record at given position isFirst() Returns true if it is first record isLast() Returns true if it is last record getString(int columnIndex) Return String stored at given column of a row getInt(int columnIndex) Return integer value stored at given column of a row getDouble(int columnIndex) Return double value stored at given column of a row Creating an application that explain working with database In this example I have made 5 activities first is main activity and a DataBase helper class named as DBCreator and a student class as Data Transfer Object(DTO) and a DAO class that interact with database. Let’s start with class DBCreater. code is given below: package com.mujadid001; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class DBCreator extends SQLiteOpenHelper { // constatns to refer database file, table name and datbase version public static final String student_TABLE_NAME = "Student"; public static final String DATABASE_NAME = "studentsResults.db"; private static int DATABASE_VERSION = 1; // constructor it only calls super class constructor public DBCreator(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); // TODO Auto-generated constructor stub } // onCreat() method is called to create database first time @Override public void onCreate(SQLiteDatabase db) { // sql query to create a table String sql = "CREATE TABLE " + student_TABLE_NAME + " (studentId INTEGER PRIMARY KEY AUTOINCREMENT, studentName TEXT,Marks INTEGER);"; // Logging a tag for debugging purposes Log.d(DATABASE_NAME, "oncreate"+sql); //executing sql query db.execSQL(sql); } //onupgrade() method definition @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // sql query to drop an existing table normally here alter table query is written but it is just an example db.execSQL("DROP TABLE IF EXISTS " +student_TABLE_NAME + ";"); // Logging a tag for debugging purpose Log.d(DATABASE_NAME, "onupdate"); //now calling onCreate to create table again onCreate(db); } } Explaination Constructor : it is used to create an object of this class and call constructor of super class onCreate() : onCreate() is called by android framework when we call getWritableDatabase() or getReadableDatbase() methods. it is called when database file is not present. onUpgrade() : it is called whenever a new version of datbase become available such that definition of database is changed, a new column has been added, datatype of a column is changed etc. student Class package com.mujadid001; public class student { // data memebers private int id; private String Name; public int marks; // constructors public student(String name, int marks) { Name = name; this.marks = marks; } public student(int id, String name, int marks) { super(); this.id = id; Name = name; this.marks = marks; } // setters and getters public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return Name; } public void setName(String name) { Name = name; } public int getMarks() { return marks; } public void setMarks(int marks) { this.marks = marks; } } Explanation: student class is self explanatory. it has member variables, getters , setters, construtors. DAO CLASS package com.mujadid001; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; // DAO class public class DAO { // an object of class SQLiteDatabase which have built in functions to manipulate database SQLiteDatabase db; //creating a reference of class DBCreator DBCreator dbcreator; // creating an object of type Context Context context; // constructor public DAO(Context context) { // initializing data members dbcreator=new DBCreator(context); // getting writable datbase from class DBCreator. this method is inherited in DBCreator from its parent db=dbcreator.getWritableDatabase(); } // method to insert a record public int InsertRecord(student s) { try { //sql query to insert a record String sql="inser"+DBCreator.student_TABLE_NAME+"(studentName,Marks) values('"+s.getName()+"',"+s.getMarks()+" );"; //executing sql query db.execSQL(sql); return 1; } catch(Exception e) { // logging if any exception occurs. Log.e("DB", e.toString()+" DAO.Insert"); return -1; } } // method to delete a record public int DeleteRecord(int id) { try { // using built in delete function of class SQLitDatabase return db.delete(DBCreator.student_TABLE_NAME, "studentId=?", new String[]{""+id}); } catch(Exception e) { // logging if any exception occurs. Log.e("DB", e.toString()+" DAO.delete"); return -1; } } public int UpdateRecord(student s) { try { // creating an object of type ContentValues (explained already in tutorial) ContentValues values=new ContentValues(); // storing kay value pairs in it values.put("studentName", s.getName()); values.put("marks", s.getMarks()); // calling built in update function of class SQLitDatabase return db.update(DBCreator.student_TABLE_NAME, values, "studentId=?", new String[] {String.valueOf(s.getId())}); } catch(Exception e) { // logging if any exception occurs. Log.e("DB", e.toString()+" DAO.UpdateRecord"); return -1; } } // getting all records public Cursor GetRecords() { // now I have used rawQuery function of class SQLitDatabase Cursor c=db.rawQuery("select * from "+DBCreator.student_TABLE_NAME,null); //returning an object of class Cursor(explained already in tutorial) return c; } //closing databse public void close() { db.close(); } } activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <!-- creating a button --> <Button android:id="@+id/add" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_marginTop="43dp" android:layout_weight="1" android:text="@string/Add" android:onClick="onClick" /> <!-- creating a button --> <Button android:id="@+id/remove" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/add" android:layout_alignBottom="@+id/add" android:layout_alignParentRight="true" android:layout_marginRight="25dp" android:text="@string/remove" android:onClick="onClick" /> <!-- creating a button --> <Button android:id="@+id/select" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/add" android:layout_marginTop="50dp" android:text="@string/select" android:onClick="onClick" /> <!-- creating a button --> <Button android:id="@+id/update" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/select" android:layout_alignBottom="@+id/select" android:layout_alignRight="@+id/remove" android:text="@string/update" android:onClick="onClick" /> </RelativeLayout> MainActivity.java package com.mujadid001; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; public class MainActivity extends Activity implements OnClickListener{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } // onclick method to handle click event of buttons @Override public void onClick(View view) { switch(view.getId()) { case R.id.add: //creating an intent to goto activity to add a new record Intent it=new Intent(MainActivity.this,AddActivity.class); //starting new activity startActivity(it); break; case R.id.remove: //creating an intent to goto activity to select all records it=new Intent(MainActivity.this,DeleteActivity.class); //starting new activity startActivity(it); break; case R.id.select: //creating an intent to goto activity to delete a record it=new Intent(MainActivity.this,SelectActivity.class); //starting new activity startActivity(it); break; case R.id.update: //creating an intent to goto activity to update a record it=new Intent(MainActivity.this,UpdateActivity.class); //starting new activity startActivity(it); break; } } } Explanation:MainActivity is very simple it has only one clickListener method onClick to handle click events. an intent to desired activity is created and activity is started. Activity_add.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".AddActivity" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:text="@string/sname" /> <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_below="@+id/textView1" android:ems="10" android:inputType="textPersonName" > <requestFocus /> </EditText> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/editText1" android:text="@string/marks" /> <EditText android:id="@+id/editText2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignRight="@+id/textView1" android:layout_below="@+id/textView2" android:ems="10" android:inputType="numberDecimal"/>" <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/editText2" android:layout_alignBottom="@+id/editText2" android:layout_marginLeft="35dp" android:layout_toRightOf="@+id/textView2" android:onClick="onClick" android:text="@string/submit" /> </RelativeLayout> AddActivity.java package com.mujadid001; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.EditText; import android.widget.Toast; public class AddActivity extends Activity implements OnClickListener { //data members String name; int marks; student s; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_add, menu); return true; } // overriden onClick method called when button is clicked @Override public void onClick(View v) { //getting value of editText Field String temp=((EditText)findViewById(R.id.editText2)).getText().toString(); // parsing it into integers marks=Integer.parseInt(temp); //getting value of editText Field name=((EditText)findViewById(R.id.editText1)).getText().toString(); //creating an DTO object of type student s=new student(name,marks); // creating an object of DAO class DAO dao=new DAO(AddActivity.this); // calling its method insert int i=dao.InsertRecord(s); // checking if return value is +ve then its mean a record is inserted else an error has occured if(i>0) Toast.makeText(getApplicationContext(), "1 record has been added", Toast.LENGTH_LONG).show(); else Toast.makeText(getApplicationContext(), "record has not been added", Toast.LENGTH_LONG).show(); //finishing this activity finish(); } } Explanation: in activity_add.xml we have two edittext and a button. when a button is clicked we get value of edit text field and make an object of class students and call method of DAO class insertRecord() when a record is inserted, a message is displayed and activity is finished. DELETE A RECORD activity_ delete.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".DeleteActivity" > <EditText android:id="@+id/idfield" android:layout_width="50dp" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:ems="10" android:hint="id" android:inputType="number" > <requestFocus /> </EditText> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:onClick="onClick" android:text="@string/submit" /> </RelativeLayout> DeleteActivity.java package com.mujadid001; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.EditText; import android.widget.Toast; public class DeleteActivity extends Activity implements OnClickListener{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_delete); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_delete, menu); return true; } @Override public void onClick(View v) { //getting value of editText Field String id=((EditText)findViewById(R.id.idfield)).getText().toString(); // parsing it into integers int deleteID=Integer.parseInt(id); // creating an anonymous object of DAO class and calling deleteRecord method int i=new DAO(DeleteActivity.this).DeleteRecord(deleteID); // checking if return value is +ve then its mean record has deleted else an error has occured if(i>0) Toast.makeText(getApplicationContext(), i+" record has been deleted", Toast.LENGTH_LONG).show(); else Toast.makeText(getApplicationContext(), "no record has added", Toast.LENGTH_LONG).show(); finish(); } } Explanation: in delete_activity.xml we have one edittext and a button. when a button is clicked we get value of edit text field and call method of DAO class DeleteRecord() when a record is deleted, a message is displayed and activity is finished. UPDATE A RECORD activity_ update.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".UpdateActivity" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:text="@string/prompt" /> <EditText android:id="@+id/marksPrompt" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/nameprompt" android:layout_marginTop="19dp" android:ems="10" android:hint="enter marks" android:inputType="phone" > <requestFocus /> </EditText> <EditText android:id="@+id/idfield2" android:layout_width="60dp" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_marginLeft="14dp" android:layout_toRightOf="@+id/nameprompt" android:ems="10" android:hint="id" android:inputType="phone" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/marksPrompt" android:layout_marginTop="56dp" android:layout_toRightOf="@+id/textView1" android:onClick="onClick" android:text="@string/submit" /> <EditText android:id="@+id/nameprompt" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/idfield2" android:ems="10" android:hint="Enter new name" android:inputType="textPersonName" /> </RelativeLayout> UpdateActivity.java package com.mujadid001; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.EditText; import android.widget.Toast; public class UpdateActivity extends Activity implements OnClickListener{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_update); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_update, menu); return true; } @Override public void onClick(View v) { //getting value of editText Field String id=((EditText)findViewById(R.id.idfield2)).getText().toString(); // parsing it into integers int ID=Integer.parseInt(id); String mark=((EditText)findViewById(R.id.marksPrompt)).getText().toString(); // parsing it into integers int marks=Integer.parseInt(mark); //getting value of editText Field String name=((EditText)findViewById(R.id.nameprompt)).getText().toString(); //creating an DTO object of type student student s=new student(ID,name,marks); // creating an object of DAO class DAO dao=new DAO(UpdateActivity.this); // calling its method updateRecord int i=dao.UpdateRecord(s); // checking if return value is +ve then its mean a record is updated else an error has occured if(i>0) //displaying message Toast.makeText(getApplicationContext(), "1 record has been updated", Toast.LENGTH_LONG).show(); else Toast.makeText(getApplicationContext(), "no record has added", Toast.LENGTH_LONG).show(); finish(); } } Explanation: in update_activity.xml we have three edittext fields and a button. when a button is clicked we get value of all edit text fields, make an object of class student and call method of DAO class UpdateRecord() when a record is updated, a message is displayed and activity is finished. Displaying all records activity_select.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".SelectActivity" > <ListView android:id="@+id/list1" android:layout_height="fill_parent" android:layout_width="fill_parent" ></ListView> </RelativeLayout> SelectActivity.java package com.mujadid001; import java.util.ArrayList; import android.os.Bundle; import android.app.Activity; import android.database.Cursor; import android.view.Menu; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; public class SelectActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_select); // getting reference to listview ListView lv=(ListView) findViewById(R.id.list1); // creating an object of type ArrayList ArrayList<String> al=new ArrayList<String>(); // creating an anonymous object of DAO class and calling getRecords method and storing in Cursor object Cursor c=new DAO(this).GetRecords(); // Adding all records in cursor into arraylist object while(c.moveToNext()) { //getting integer value of first column int id=c.getInt(0); //getting string value of 2nd column String name=c.getString(1); //getting integer value of 3rd column int marks=c.getInt(2); //adding them in to array list al.add(""+id+" "+name+" "+marks); } // creating an array adapter ArrayAdapter<String> adapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,al); //setting adapter to list lv.setAdapter(adapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_select, menu); return true; } } Explanation : In select_acticty.xml we have only a listView. in java class we get reference to this listview. After that we make an object of arraylist of type string. we create an object of DAO class and called method getRecords(). which returns a cursor object. we received cursor object an iterate over it to get all records and save them in arrayList. then we made an object of type arrayAdapter and then set it to list. Sample OutPut