Introduction

This tutorial explains database connectivity in Android. We will see how to create a database and insert and delete in a database and view the database. To explain this I am making a database for a bank.
First, the user will select whether he/she is an admin or a customer. An admin can add and delete accounts and view all accounts. Customers will be able to withdraw cash, deposit cash and view his account details.
In this tutorial, we will create functionalities only for the Admin. In the next article, we will create customer functionalities.
Step 1
Right-click on "Values" -> "New" -> "Values Resource File". Name this file as "color". Add the following code to this file:
  1. <resources>
  2. <color name="txt">#FFFFFF</color>
  3. <color name="bg">#454545</color>
  4. <color name="withdar1">#4d2177</color>
  5. </resources>
Step 2
Make the following changes in "strings.xml":
  1. <resources>
  2. <string name="app_name" >BankDB </string>
  3. <string name="action_settings" >Settings</string>
  4. <string name="hello_world" >Welcome to the BANK..... </string>
  5. <string name="admin">Admin</string>
  6. <string name="admintxt">Welcome Admin...</string>
  7. </resources>
Step 3
Do the following changes in "dimens.xml":
  1. <resources>
  2. <!-- Default screen margins, per the Android Design guidelines. -->
  3. <dimen name="activity_horizontal_margin">16dp</dimen>
  4. <dimen name="activity_vertical_margin">16dp</dimen>
  5. <dimen name="wel_admin">30dp</dimen>
  6. <dimen name="form_ele">20dp</dimen>
  7. </resources>
Step 4
Make the following changes in "activity_main.xml" in the layout (your main layout file): Use LinearLayout element.
  1. <TextView
  2. android:layout_width="wrap_content"
  3. android:layout_height="wrap_content"
  4. android:text="@string/hello_world"
  5. android:layout_marginLeft="70dp"
  6. android:textColor="@color/txt"/>
  7. <Button
  8. android:id="@+id/admin"
  9. android:layout_height="wrap_content"
  10. android:layout_width="wrap_content"
  11. android:layout_marginTop="50dp"
  12. android:background="@drawable/admin_design"
  13. android:text="@string/admin"/>
Note that we are only creating an Admin here. A customer will be explained in my next article. The layout looks like:
im1.jpg
Step 5
Make the layout file for the Admin. Right-click on layout then select "New" -> "Layout Resource File". Name this file "admin_layout". Add the following code to this XML file (using LinearLayout element):
  1. <TextView
  2. android:layout_width="wrap_content"
  3. android:layout_height="wrap_content"
  4. android:text="@string/admintxt"
  5. android:layout_marginLeft="80dp"
  6. android:textColor="@color/txt"
  7. android:layout_marginTop="20dp"
  8. android:textSize="@dimen/wel_admin"/>
  9. <Button
  10. android:id="@+id/create"
  11. android:layout_height="wrap_content"
  12. android:layout_width="wrap_content"
  13. android:layout_marginTop="70dp"
  14. android:layout_marginLeft="40dp"
  15. android:background="@drawable/admin_design"
  16. android:text="Add new"
  17. android:paddingLeft="10dp"
  18. android:paddingRight="10dp"/>
  19. <Button
  20. android:id="@+id/del"
  21. android:layout_height="wrap_content"
  22. android:layout_width="wrap_content"
  23. android:layout_marginTop="70dp"
  24. android:layout_marginLeft="40dp"
  25. android:background="@drawable/admin_design"
  26. android:text="Delete Acc"
  27. android:paddingLeft="10dp"
  28. android:paddingRight="10dp"/>
  29. <Button
  30. android:id="@+id/view"
  31. android:layout_height="wrap_content"
  32. android:layout_width="wrap_content"
  33. android:layout_marginTop="70dp"
  34. android:layout_marginLeft="40dp"
  35. android:background="@drawable/admin_design"
  36. android:text="View Acc"
  37. android:paddingLeft="10dp"
  38. android:paddingRight="10dp"/>
The layout looks like:
im2.jpg
Step 6
Create a new layout file for adding a new account to the database in the same way as was done above and name this new file as "create_layout". Add the following to this file, again inside LinearLayout element:
  1. <TextView
  2. android:layout_width="wrap_content"
  3. android:layout_height="wrap_content"
  4. android:text="Create an account...."
  5. android:layout_marginLeft="60dp"
  6. android:layout_marginTop="20dp"
  7. android:textSize="@dimen/wel_admin"
  8. />
  9. <RelativeLayout
  10. android:layout_width="fill_parent"
  11. android:layout_height="wrap_content">
  12. <TextView
  13. android:id="@+id/t1"
  14. android:layout_width="wrap_content"
  15. android:layout_height="wrap_content"
  16. android:text="Acc id: "
  17. android:layout_marginLeft="20dp"
  18. android:layout_marginTop="40dp"
  19. android:textSize="@dimen/form_ele"/>
  20. <EditText
  21. android:id="@+id/accid"
  22. android:layout_height="wrap_content"
  23. android:layout_width="fill_parent"
  24. android:layout_marginTop="40dp"
  25. android:layout_toRightOf="@id/t1"
  26. android:layout_marginLeft="30dp"/>
  27. </RelativeLayout>
  28. <RelativeLayout
  29. android:layout_width="fill_parent"
  30. android:layout_height="wrap_content">
  31. <TextView
  32. android:id="@+id/t2"
  33. android:layout_width="wrap_content"
  34. android:layout_height="wrap_content"
  35. android:text="Acc type: "
  36. android:layout_marginLeft="20dp"
  37. android:layout_marginTop="40dp"
  38. android:textSize="@dimen/form_ele"/>
  39. <EditText
  40. android:id="@+id/acctype"
  41. android:layout_height="wrap_content"
  42. android:layout_width="fill_parent"
  43. android:layout_marginTop="40dp"
  44. android:layout_toRightOf="@id/t2"
  45. android:layout_marginLeft="10dp"/>
  46. </RelativeLayout>
  47. <RelativeLayout
  48. android:layout_width="fill_parent"
  49. android:layout_height="wrap_content">
  50. <TextView
  51. android:id="@+id/t3"
  52. android:layout_width="wrap_content"
  53. android:layout_height="wrap_content"
  54. android:text="Bal: "
  55. android:layout_marginLeft="20dp"
  56. android:layout_marginTop="40dp"
  57. android:textSize="@dimen/form_ele"/>
  58. <EditText
  59. android:id="@+id/accbal"
  60. android:layout_height="wrap_content"
  61. android:layout_width="fill_parent"
  62. android:layout_marginTop="40dp"
  63. android:layout_toRightOf="@id/t3"
  64. android:layout_marginLeft="60dp"/>
  65. </RelativeLayout>
  66. <Button
  67. android:id="@+id/bCreate"
  68. android:layout_height="wrap_content"
  69. android:layout_width="wrap_content"
  70. android:layout_marginTop="80dp"
  71. android:layout_marginLeft="130dp"
  72. android:text="Create"
  73. android:background="@drawable/admin_design"/>
Relative Layout is added wherever needed. The layout looks like:
im3.jpg
Step 7
Create yet another layout file for deleting and name this file "del_layout". Add the following code in the LinearLayout element of this file:
  1. <TextView
  2. android:layout_width="wrap_content"
  3. android:layout_height="wrap_content"
  4. android:text="Delete an account...."
  5. android:layout_marginLeft="60dp"
  6. android:layout_marginTop="20dp"
  7. android:textSize="@dimen/wel_admin"
  8. />
  9. <RelativeLayout
  10. android:layout_width="fill_parent"
  11. android:layout_height="wrap_content">
  12. <TextView
  13. android:id="@+id/d1"
  14. android:layout_width="wrap_content"
  15. android:layout_height="wrap_content"
  16. android:text="Acc id: "
  17. android:layout_marginLeft="20dp"
  18. android:layout_marginTop="60dp"
  19. android:textSize="@dimen/form_ele"/>
  20. <EditText
  21. android:id="@+id/acciddel"
  22. android:layout_height="wrap_content"
  23. android:layout_width="fill_parent"
  24. android:layout_marginTop="60dp"
  25. android:layout_toRightOf="@id/t1"
  26. android:layout_marginLeft="110dp"/>
  27. </RelativeLayout>
  28. <Button
  29. android:id="@+id/bdel"
  30. android:layout_height="wrap_content"
  31. android:layout_width="wrap_content"
  32. android:layout_marginTop="80dp"
  33. android:layout_marginLeft="130dp"
  34. android:text="Delete"
  35. android:background="@drawable/admin_design"/>
The layout looks like:
im4.jpg
Step 8
Create another layout file for viewing and name it as "view_layout2". Add the following code in the LinearLayout element of this file:
  1. <TextView
  2. android:id="@+id/v"
  3. android:layout_height="fill_parent"
  4. android:layout_width="fill_parent"
  5. />
Let us now start with the Java part.
Step 9
Open "MainACtivity.java" (created by default) and add the following code in it:
  1. package com.example.bankdb;
  2. import android.content.Context;
  3. import android.content.Intent;
  4. import android.os.Bundle;
  5. import android.app.Activity;
  6. import android.view.Menu;
  7. import android.view.View;
  8. import android.widget.Button;
  9. public class MainActivity extends Activity {
  10. Button b;
  11. @Override
  12. protected void onCreate(Bundle savedInstanceState) {
  13. super.onCreate(savedInstanceState);
  14. setContentView(R.layout.activity_main);
  15. b=(Button)findViewById(R.id.admin);
  16. final Context context=this;
  17. b.setOnClickListener(new View.OnClickListener() {
  18. @Override
  19. public void onClick(View v) {
  20. // final Context context=this;
  21. Intent i=new Intent(context,Admin.class);
  22. startActivity(i);
  23. }
  24. });
  25. }
  26. @Override
  27. public boolean onCreateOptionsMenu(Menu menu) {
  28. // Inflate the menu; this adds items to the action bar if it is present.
  29. getMenuInflater().inflate(R.menu.main, menu);
  30. return true;
  31. }
  32. }
On button click, another activity, namely Admin, is loaded.
Step 10
Create a Java class in the same package and name it as "Admin". Write the following code in this Java file:
  1. package com.example.bankdb;
  2. import android.app.Activity;
  3. import android.content.Context;
  4. import android.content.Intent;
  5. import android.os.Bundle;
  6. import android.view.View;
  7. import android.widget.Button;
  8. import com.example.bankdb.R;
  9. public class Admin extends Activity
  10. {
  11. Button create;
  12. Button del;
  13. Button view;
  14. @Override
  15. protected void onCreate(Bundle savedInstanceState) {
  16. super.onCreate(savedInstanceState);
  17. setContentView(R.layout.admin_layout);
  18. create=(Button)findViewById(R.id.create);
  19. del=(Button)findViewById(R.id.del);
  20. view=(Button)findViewById(R.id.view);
  21. final Context context=this;
  22. create.setOnClickListener(new View.OnClickListener() {
  23. @Override
  24. public void onClick(View v) {
  25. Intent i= new Intent(context,Create.class);
  26. startActivity(i);
  27. }
  28. });
  29. del.setOnClickListener(new View.OnClickListener() {
  30. @Override
  31. public void onClick(View v) {
  32. Intent i= new Intent(context,Del.class);
  33. startActivity(i);
  34. }
  35. });
  36. view.setOnClickListener(new View.OnClickListener() {
  37. @Override
  38. public void onClick(View v) {
  39. Intent i= new Intent(context,ViewAcc.class);
  40. startActivity(i);
  41. }
  42. });
  43. }
  44. }
The Create, Del and View activities are loaded on clicking the respective buttons in this activity.
Step 11
Create a Java class in the same package and name it as "Create". Write the following code in this Java file:
  1. package com.example.bankdb;
  2. import android.app.Activity;
  3. import android.content.ContentValues;
  4. import android.content.Context;
  5. import android.content.Intent;
  6. import android.database.Cursor;
  7. import android.database.sqlite.SQLiteDatabase;
  8. import android.os.Bundle;
  9. import android.view.View;
  10. import android.widget.Button;
  11. import android.widget.EditText;
  12. import android.widget.TextView;
  13. import android.widget.Toast;
  14. public class Create extends Activity {
  15. Button b;
  16. EditText t1;
  17. EditText t2;
  18. EditText t3;
  19. SQLiteDatabase db;
  20. @Override
  21. protected void onCreate(Bundle savedInstanceState) {
  22. super.onCreate(savedInstanceState);
  23. setContentView(R.layout.create_layout);
  24. b=(Button)findViewById(R.id.bCreate);
  25. t1=(EditText)findViewById(R.id.accid);
  26. t2=(EditText)findViewById(R.id.acctype);
  27. t3=(EditText)findViewById(R.id.accbal);
  28. final Context context=this;
  29. try
  30. {
  31. db=openOrCreateDatabase("Banking1",SQLiteDatabase.CREATE_IF_NECESSARY,null);
  32. db.execSQL("CREATE TABLE bank (id integer PRIMARY KEY, type text, bal integer)");
  33. }
  34. catch(Exception e)
  35. {
  36. e.printStackTrace();
  37. }
  38. b.setOnClickListener(new View.OnClickListener() {
  39. @Override
  40. public void onClick(View v) {
  41. String s=t1.getText().toString();
  42. String s1=t2.getText().toString();
  43. String s2=t3.getText().toString();
  44. //db.execSQL("INSERT INTO log VALUES (s)");
  45. ContentValues values=new ContentValues();
  46. values.put("id",s);
  47. values.put("type",s1);
  48. values.put("bal",s2);
  49. if((db.insert("bank",null,values))!= -1)
  50. {
  51. Toast.makeText(Create.this, "Inserted...", 2000).show();
  52. }
  53. else
  54. {
  55. Toast.makeText(Create.this,"Error...",2000).show();
  56. }
  57. t1.setText("");
  58. t2.setText("");
  59. t3.setText("");
  60. Intent i=new Intent(context,Admin.class);
  61. startActivity(i);
  62. }
  63. });
  64. }
  65. }
In the code above I have created a database. The values entered by the admin are then entered into the database. The "if" statement checks if the record is inserted properly or not. Also, note that "id" is a primary key in the database.
Step 12
Create a Java class in the same package and name it as "Del". Write the following code in this Java file:
  1. package com.example.bankdb;
  2. import android.app.Activity;
  3. import android.content.Context;
  4. import android.content.Intent;
  5. import android.database.sqlite.SQLiteDatabase;
  6. import android.database.sqlite.SQLiteException;
  7. import android.database.sqlite.SQLiteOpenHelper;
  8. import android.os.Bundle;
  9. import android.view.View;
  10. import android.widget.Button;
  11. import android.widget.EditText;
  12. import android.widget.Toast;
  13. public class Del extends Activity {
  14. Button b;
  15. EditText e;
  16. SQLiteDatabase db;
  17. SQLiteOpenHelper d;
  18. @Override
  19. protected void onCreate(Bundle savedInstanceState) {
  20. super.onCreate(savedInstanceState);
  21. setContentView(R.layout.del_layout);
  22. b=(Button)findViewById(R.id.bdel);
  23. e=(EditText)findViewById(R.id.acciddel);
  24. final Context context=this;
  25. try
  26. {
  27. db=openOrCreateDatabase("Banking1",SQLiteDatabase.CREATE_IF_NECESSARY,null);
  28. }
  29. catch(SQLiteException e)
  30. {
  31. e.printStackTrace();
  32. System.out.print("ERROR.............");
  33. }
  34. b.setOnClickListener(new View.OnClickListener() {
  35. @Override
  36. public void onClick(View v) {
  37. String t=(e.getText().toString());
  38. try
  39. {
  40. String d="DELETE FROM bank WHERE id="+t;
  41. db.execSQL(d);
  42. }
  43. catch(Exception e)
  44. {
  45. System.out.print("Error..................");
  46. }
  47. e.setText("");
  48. Toast.makeText(Del.this, "Deleted...", 2000).show();
  49. Intent i=new Intent(context,Admin.class);
  50. startActivity(i);
  51. }
  52. });
  53. }
  54. }
This code removes the record from the database having the id the same as the id entered by the admin.
Step 13
Create a Java class in the same package and name it "ViewAcc". Write the following code in this Java file:
  1. package com.example.bankdb;
  2. import android.app.Activity;
  3. import android.app.ListActivity;
  4. import android.database.Cursor;
  5. import android.database.sqlite.SQLiteDatabase;
  6. import android.database.sqlite.SQLiteException;
  7. import android.os.Bundle;
  8. import android.view.ViewGroup;
  9. import android.widget.*;
  10. import java.util.ArrayList;
  11. import java.util.List;
  12. public class ViewAcc extends Activity {
  13. SQLiteDatabase db;
  14. @Override
  15. protected void onCreate(Bundle savedInstanceState) {
  16. super.onCreate(savedInstanceState);
  17. setContentView(R.layout.view_layout2);
  18. try
  19. {
  20. db=openOrCreateDatabase("Banking1",SQLiteDatabase.CREATE_IF_NECESSARY,null);
  21. Cursor c= db.rawQuery("SELECT * FROM bank",null);
  22. TextView v=(TextView)findViewById(R.id.v);
  23. c.moveToFirst();
  24. String temp="";
  25. while(! c.isAfterLast())
  26. {
  27. String s2=c.getString(0);
  28. String s3=c.getString(1);
  29. String s4=c.getString(2);
  30. temp=temp+"\n Id:"+s2+"\tType:"+s3+"\tBal:"+s4;
  31. c.moveToNext();
  32. }
  33. v.setText(temp);
  34. }
  35. catch(SQLiteException e)
  36. {
  37. }
  38. }
  39. }
This code displays all the records in the database.
Step 14
In the end, don't forget to add the newly created activities in the manifest file "AndroidManifest.xml". Add the following code in you manifest file:
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.example.bankdb"
  4. android:versionCode="1"
  5. android:versionName="1.0" >
  6. <uses-sdk
  7. android:minSdkVersion="7"
  8. android:targetSdkVersion="16" />
  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.example.bankdb.MainActivity"
  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="com.example.bankdb.ViewAcc"
  23. android:label="View">
  24. </activity>
  25. <activity android:name=".Create"
  26. android:label="Create"/>
  27. <activity android:name=".Del"
  28. android:label="Delete"/>
  29. <activity android:name=".Admin"
  30. android:label="Admin"/>
  31. </application>
  32. </manifest>
The output screens look like:
im5.jpg
On clicking Admin you will get
im6.jpg
On clicking Add New you will get (I have filled in some values)
im7.jpg
The "Toast" will be generated once you click on the Create button.
On clicking Delete Acc you will get (I have filled in the value):
im8.jpg
The "Toast" will be generated once you click on the Delete button.
On clicking View Acc you will get:
im9.jpg
This ends our tutorial. The article containing the Customer functionalities will be uploaded soon.
Enjoy coding :)