In this article, I tell you about working on a database in Android. In Android, we can save data in may ways, such as using MySQL, Oracle or SQLite. Here we will learn how to work using an SQLite database in Android.
To use an SQLite database we must extend the class "SQLiteOpenHelper" from the "android.databse.sqlite" package and two methods must also be overridden because these methods are abstract methods. So you will see using an example.
Step 1
As usual first of all create a new Android application project as in the following image:
Step 2
After that create a XML file as dairy.xml as "res/layout/dairy.xml" and update it as shown below:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="Diary Title"
- />
- <EditText
- android:id="@+id/diarydescriptionText"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- />
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="Content"
- />
- <EditText
- android:id="@+id/diarycontentText"
- android:layout_width="fill_parent"
- android:layout_height="200dp"
- />
- <Button
- android:id="@+id/submitButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="submit"
- android:textSize="20dp"
- />
- </LinearLayout>
Step 3
Now create a Java file as Dairy.java in the "com.db.documents" directory and update it as shown below:
- package com.db.documents;
- import android.app.Activity;
- import android.content.Intent;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.EditText;
- public class Diary extends Activity
- {
- EditText titleET, contentET;
- Button submitBT;
- MyDB dba;
- @Override
- public void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.dairy);
- dba = new MyDB(this);
- dba.open();
- titleET = (EditText) findViewById(R.id.diarydescriptionText);
- contentET = (EditText) findViewById(R.id.diarycontentText);
- submitBT = (Button) findViewById(R.id.submitButton);
- submitBT.setOnClickListener(new OnClickListener()
- {
- public void onClick(View v)
- {
- try
- {
- saveItToDB();
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- }
- });
- }
- public void saveItToDB()
- {
- dba.insertdiary(titleET.getText().toString(),
- contentET.getText().toString());
- dba.close();
- titleET.setText("");
- contentET.setText("");
- }
- }
Step 4
Create a new Java file as MyDB.java in the same directory "com.db.documents" and update it also as in the following code:
- package com.db.documents;
- import android.content.ContentValues;
- import android.content.Context;
- import android.database.Cursor;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteException;
- import android.util.Log;
- public class MyDB
- {
- private SQLiteDatabase db;
- private final Context context;
- private final MyDBhelper dbhelper;
- public MyDB(Context c)
- {
- context = c;
- dbhelper = new MyDBhelper(context, Constants.DATABASE_NAME, null,
- Constants.DATABASE_VERSION);
- }
- public void close()
- {
- db.close();
- }
- public void open() throws SQLiteException
- {
- try
- {
- db = dbhelper.getWritableDatabase();
- }
- catch (SQLiteException ex)
- {
- Log.v("Open database exception caught", ex.getMessage());
- db = dbhelper.getReadableDatabase();
- }
- }
- public long insertdiary(String title, String content)
- {
- try
- {
- ContentValues newTaskValue = new ContentValues();
- newTaskValue.put(Constants.TITLE_NAME, title);
- newTaskValue.put(Constants.CONTENT_NAME, content);
- newTaskValue.put(Constants.DATE_NAME,
- java.lang.System.currentTimeMillis());
- return db.insert(Constants.TABLE_NAME, null, newTaskValue);
- }
- catch (SQLiteException ex)
- {
- Log.v("Insert into database exception caught",
- ex.getMessage());
- return -1;
- }
- }
- public Cursor getdiaries()
- {
- Cursor c = db.query(Constants.TABLE_NAME, null, null,
- null, null, null, null);
- return c;
- }
- }
Step 5
Create a new Java file MyDBhelper.java extendig the "SQLIteOpenHelper" classs as described in the inroduction and update it as shown in the following code:
- package com.db.documents;
- import android.content.Context;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteException;
- import android.database.sqlite.SQLiteOpenHelper;
- import android.database.sqlite.SQLiteDatabase.CursorFactory;
- import android.util.Log;
- public class MyDBhelper extends SQLiteOpenHelper{
- private static final String CREATE_TABLE="create table "+
- Constants.TABLE_NAME+" ("+
- Constants.KEY_ID+" integer primary key autoincrement, "+
- Constants.TITLE_NAME+" text not null, "+
- Constants.CONTENT_NAME+" text not null, "+
- Constants.DATE_NAME+" long);";
- public MyDBhelper(Context context, String name, CursorFactory factory,
- int version) {
- super(context, name, factory, version);
- }
- @Override
- public void onCreate(SQLiteDatabase db) {
- Log.v("MyDBhelper onCreate","Creating all the tables");
- try {
- db.execSQL(CREATE_TABLE);
- } catch(SQLiteException ex) {
- Log.v("Create table exception", ex.getMessage());
- }
- }
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion,
- int newVersion) {
- Log.w("TaskDBAdapter", "Upgrading from version "+oldVersion
- +" to "+newVersion
- +", which will destroy all old data");
- db.execSQL("drop table if exists "+Constants.TABLE_NAME);
- onCreate(db);
- }
- }
Step 6
Create another Java file in the same directory as Constant.java in which we use a constant in a separate class as shown below:
- package com.db.documents;
- public class Constants {
- public static final String DATABASE_NAME="datastorage";
- public static final int DATABASE_VERSION=1;
- public static final String TABLE_NAME="diaries";
- public static final String TITLE_NAME="title";
- public static final String CONTENT_NAME="content";
- public static final String DATE_NAME="recorddate";
- public static final String KEY_ID="_id";
- }
Step 7
Now open the AndroidManifest.xml file and update it with the following code:
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.db.documents"
- android:versionCode="1"
- android:versionName="1.0" >
- <uses-sdk
- android:minSdkVersion="8"
- android:targetSdkVersion="17" />
- <application
- android:allowBackup="true"
- android:icon="@drawable/ic_launcher"
- android:label="@string/app_name"
- android:theme="@style/AppTheme" >
- <activity
- android:name="com.db.documents.Diary"
- android:label="@string/app_name" >
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- <activity android:name=".MyPreferences" />
- <activity android:name=".DisplayDiaries"/>
- </application>
- </manifest>
See Output
data entry
Database in SQLite