Create Database in Android

Introduction

 
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:
 
newdocuments.jpg
 
Step 2
 
After that create a XML file as dairy.xml as "res/layout/dairy.xml" and update it as shown below:
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.    android:orientation="vertical"  
  4.    android:layout_width="fill_parent"  
  5.    android:layout_height="fill_parent"  
  6.    >  
  7.    <TextView  
  8.       android:layout_width="fill_parent"  
  9.       android:layout_height="wrap_content"  
  10.       android:text="Diary Title"  
  11.       />  
  12.    <EditText  
  13.       android:id="@+id/diarydescriptionText"  
  14.       android:layout_width="fill_parent"  
  15.       android:layout_height="wrap_content"  
  16.       />  
  17.    <TextView  
  18.       android:layout_width="fill_parent"  
  19.       android:layout_height="wrap_content"  
  20.       android:text="Content"  
  21.       />  
  22.    <EditText  
  23.       android:id="@+id/diarycontentText"  
  24.       android:layout_width="fill_parent"  
  25.       android:layout_height="200dp"  
  26.       />  
  27.    <Button  
  28.       android:id="@+id/submitButton"  
  29.       android:layout_width="wrap_content"  
  30.       android:layout_height="wrap_content"  
  31.       android:text="submit"  
  32.       android:textSize="20dp"  
  33.       />  
  34. </LinearLayout> 
Step 3
 
Now create a Java file as Dairy.java in the "com.db.documents" directory and update it as shown below:
  1. package com.db.documents;  
  2. import android.app.Activity;  
  3. import android.content.Intent;  
  4. import android.os.Bundle;  
  5. import android.view.View;  
  6. import android.view.View.OnClickListener;  
  7. import android.widget.Button;  
  8. import android.widget.EditText;  
  9. public class Diary extends Activity   
  10. {  
  11.  EditText titleET, contentET;  
  12.  Button submitBT;  
  13.  MyDB dba;  
  14.  @Override  
  15.  public void onCreate(Bundle savedInstanceState)   
  16.  {  
  17.   super.onCreate(savedInstanceState);  
  18.   setContentView(R.layout.dairy);  
  19.   dba = new MyDB(this);  
  20.   dba.open();  
  21.   titleET = (EditText) findViewById(R.id.diarydescriptionText);  
  22.   contentET = (EditText) findViewById(R.id.diarycontentText);  
  23.   submitBT = (Button) findViewById(R.id.submitButton);  
  24.   submitBT.setOnClickListener(new OnClickListener()   
  25.   {  
  26.    public void onClick(View v)   
  27.    {  
  28.     try   
  29.     {  
  30.      saveItToDB();  
  31.     }   
  32.     catch (Exception e)   
  33.     {  
  34.      e.printStackTrace();  
  35.     }  
  36.    }  
  37.   });  
  38.  }  
  39.  public void saveItToDB()   
  40.  {  
  41.   dba.insertdiary(titleET.getText().toString(),  
  42.    contentET.getText().toString());  
  43.   dba.close();  
  44.   titleET.setText("");  
  45.   contentET.setText("");  
  46.  }  
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:
  1. package com.db.documents;  
  2. import android.content.ContentValues;  
  3. import android.content.Context;  
  4. import android.database.Cursor;  
  5. import android.database.sqlite.SQLiteDatabase;  
  6. import android.database.sqlite.SQLiteException;  
  7. import android.util.Log;  
  8. public class MyDB   
  9. {  
  10.  private SQLiteDatabase db;  
  11.  private final Context context;  
  12.  private final MyDBhelper dbhelper;  
  13.  public MyDB(Context c)   
  14.  {  
  15.   context = c;  
  16.   dbhelper = new MyDBhelper(context, Constants.DATABASE_NAME, null,  
  17.    Constants.DATABASE_VERSION);  
  18.  }  
  19.  public void close()   
  20.  {  
  21.   db.close();  
  22.  }  
  23.  public void open() throws SQLiteException   
  24.  {  
  25.   try   
  26.   {  
  27.    db = dbhelper.getWritableDatabase();  
  28.   }   
  29.   catch (SQLiteException ex)   
  30.   {  
  31.    Log.v("Open database exception caught", ex.getMessage());  
  32.    db = dbhelper.getReadableDatabase();  
  33.   }  
  34.  }  
  35.  public long insertdiary(String title, String content)   
  36.  {  
  37.   try   
  38.   {  
  39.    ContentValues newTaskValue = new ContentValues();  
  40.    newTaskValue.put(Constants.TITLE_NAME, title);  
  41.    newTaskValue.put(Constants.CONTENT_NAME, content);  
  42.    newTaskValue.put(Constants.DATE_NAME,  
  43.     java.lang.System.currentTimeMillis());  
  44.    return db.insert(Constants.TABLE_NAME, null, newTaskValue);  
  45.   }   
  46.   catch (SQLiteException ex)   
  47.   {  
  48.    Log.v("Insert into database exception caught",  
  49.     ex.getMessage());  
  50.    return -1;  
  51.   }  
  52.  }  
  53.  public Cursor getdiaries()  
  54.  {  
  55.   Cursor c = db.query(Constants.TABLE_NAME, nullnull,  
  56.    nullnullnullnull);  
  57.   return c;  
  58.  }  
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:
  1. package com.db.documents;  
  2. import android.content.Context;  
  3. import android.database.sqlite.SQLiteDatabase;  
  4. import android.database.sqlite.SQLiteException;  
  5. import android.database.sqlite.SQLiteOpenHelper;  
  6. import android.database.sqlite.SQLiteDatabase.CursorFactory;  
  7. import android.util.Log;  
  8. public class MyDBhelper extends SQLiteOpenHelper{  
  9. private static final String CREATE_TABLE="create table "+  
  10.             Constants.TABLE_NAME+" ("+  
  11.             Constants.KEY_ID+" integer primary key autoincrement, "+  
  12.             Constants.TITLE_NAME+" text not null, "+  
  13.             Constants.CONTENT_NAME+" text not null, "+  
  14.             Constants.DATE_NAME+" long);";  
  15.       public MyDBhelper(Context context, String name, CursorFactory factory,  
  16.                   int version) {  
  17.             super(context, name, factory, version);  
  18.       }  
  19.       @Override  
  20.       public void onCreate(SQLiteDatabase db) {  
  21.             Log.v("MyDBhelper onCreate","Creating all the tables");  
  22.             try {  
  23.                   db.execSQL(CREATE_TABLE);  
  24.             } catch(SQLiteException ex) {  
  25.                   Log.v("Create table exception", ex.getMessage());  
  26.             }  
  27.       }  
  28.       @Override  
  29.       public void onUpgrade(SQLiteDatabase db, int oldVersion,  
  30.                   int newVersion) {  
  31.             Log.w("TaskDBAdapter""Upgrading from version "+oldVersion  
  32.                         +" to "+newVersion  
  33.                         +", which will destroy all old data");  
  34.             db.execSQL("drop table if exists "+Constants.TABLE_NAME);  
  35.             onCreate(db);  
  36.       }  
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:
  1. package com.db.documents;  
  2. public class Constants {  
  3.       public static final String DATABASE_NAME="datastorage";  
  4.       public static final int DATABASE_VERSION=1;  
  5.       public static final String TABLE_NAME="diaries";  
  6.       public static final String TITLE_NAME="title";  
  7.       public static final String CONTENT_NAME="content";  
  8.       public static final String DATE_NAME="recorddate";  
  9.       public static final String KEY_ID="_id";  
Step 7
 
Now open the AndroidManifest.xml file and update it with the following code:
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.db.documents"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.     <uses-sdk  
  7.         android:minSdkVersion="8"  
  8.         android:targetSdkVersion="17" />  
  9.     <application  
  10.         android:allowBackup="true"  
  11.         android:icon="@drawable/ic_launcher"  
  12.         android:label="@string/app_name"  
  13.         android:theme="@style/AppTheme" >  
  14.         <activity  
  15.             android:name="com.db.documents.Diary"  
  16.             android:label="@string/app_name" >  
  17.             <intent-filter>  
  18.                 <action android:name="android.intent.action.MAIN" />  
  19.                 <category android:name="android.intent.category.LAUNCHER" />  
  20.             </intent-filter>  
  21.         </activity>  
  22.         <activity android:name=".MyPreferences" />  
  23.             <activity android:name=".DisplayDiaries"/>  
  24.     </application>  
  25. </manifest> 
See Output
 
data entry
 
inputto database.jpg
 
Database in SQLite
 
db1.jpg


Similar Articles