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 must 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 the customer functionalities.
Step 1:
Right-click on "Values" -> "New" -> "Values Resource File". Name this file as "color". Add the following code to this file:
<resources>
<color name="txt">#FFFFFF</color>
<color name="bg">#454545</color>
<color name="withdar1">#4d2177</color>
</resources>
Step 2:
Make the following changes in "strings.xml":
<resources>
<string name="app_name" >BankDB </string>
<string name="action_settings" >Settings</string>
<string name="hello_world" >Welcome to the BANK..... </string>
<string name="admin">Admin</string>
<string name="admintxt">Welcome Admin...</string>
</resources>
Step 3:
Do the following changes in "dimens.xml":
<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
<dimen name="wel_admin">30dp</dimen>
<dimen name="form_ele">20dp</dimen>
</resources>
Step 4:
Make the following changes in "activity_main.xml" in the layout (your main layout file): Use LinearLayout element.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:layout_marginLeft="70dp"
android:textColor="@color/txt"/>
<Button
android:id="@+id/admin"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginTop="50dp"
android:background="@drawable/admin_design"
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:
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):
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/admintxt"
android:layout_marginLeft="80dp"
android:textColor="@color/txt"
android:layout_marginTop="20dp"
android:textSize="@dimen/wel_admin"/>
<Button
android:id="@+id/create"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginTop="70dp"
android:layout_marginLeft="40dp"
android:background="@drawable/admin_design"
android:text="Add new"
android:paddingLeft="10dp"
android:paddingRight="10dp"/>
<Button
android:id="@+id/del"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginTop="70dp"
android:layout_marginLeft="40dp"
android:background="@drawable/admin_design"
android:text="Delete Acc"
android:paddingLeft="10dp"
android:paddingRight="10dp"/>
<Button
android:id="@+id/view"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginTop="70dp"
android:layout_marginLeft="40dp"
android:background="@drawable/admin_design"
android:text="View Acc"
android:paddingLeft="10dp"
android:paddingRight="10dp"/>
The layout looks like:
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:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Create an account...."
android:layout_marginLeft="60dp"
android:layout_marginTop="20dp"
android:textSize="@dimen/wel_admin"
/>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/t1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Acc id: "
android:layout_marginLeft="20dp"
android:layout_marginTop="40dp"
android:textSize="@dimen/form_ele"/>
<EditText
android:id="@+id/accid"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_marginTop="40dp"
android:layout_toRightOf="@id/t1"
android:layout_marginLeft="30dp"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/t2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Acc type: "
android:layout_marginLeft="20dp"
android:layout_marginTop="40dp"
android:textSize="@dimen/form_ele"/>
<EditText
android:id="@+id/acctype"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_marginTop="40dp"
android:layout_toRightOf="@id/t2"
android:layout_marginLeft="10dp"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/t3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bal: "
android:layout_marginLeft="20dp"
android:layout_marginTop="40dp"
android:textSize="@dimen/form_ele"/>
<EditText
android:id="@+id/accbal"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_marginTop="40dp"
android:layout_toRightOf="@id/t3"
android:layout_marginLeft="60dp"/>
</RelativeLayout>
<Button
android:id="@+id/bCreate"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginTop="80dp"
android:layout_marginLeft="130dp"
android:text="Create"
android:background="@drawable/admin_design"/>
Relative Layout is added whereever needed. The layout looks like:
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:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete an account...."
android:layout_marginLeft="60dp"
android:layout_marginTop="20dp"
android:textSize="@dimen/wel_admin"
/>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/d1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Acc id: "
android:layout_marginLeft="20dp"
android:layout_marginTop="60dp"
android:textSize="@dimen/form_ele"/>
<EditText
android:id="@+id/acciddel"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_marginTop="60dp"
android:layout_toRightOf="@id/t1"
android:layout_marginLeft="110dp"/>
</RelativeLayout>
<Button
android:id="@+id/bdel"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginTop="80dp"
android:layout_marginLeft="130dp"
android:text="Delete"
android:background="@drawable/admin_design"/>
The layout looks like:
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:
<TextView
android:id="@+id/v"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
/>
Let us now start with the Java part.
Step 9:
Open "MainACtivity.java" (created by default) and add the following code in it:
package com.example.bankdb;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b=(Button)findViewById(R.id.admin);
final Context context=this;
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// final Context context=this;
Intent i=new Intent(context,Admin.class);
startActivity(i);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
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:
package com.example.bankdb;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.example.bankdb.R;
public class Admin extends Activity
{
Button create;
Button del;
Button view;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.admin_layout);
create=(Button)findViewById(R.id.create);
del=(Button)findViewById(R.id.del);
view=(Button)findViewById(R.id.view);
final Context context=this;
create.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i= new Intent(context,Create.class);
startActivity(i);
}
});
del.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i= new Intent(context,Del.class);
startActivity(i);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i= new Intent(context,ViewAcc.class);
startActivity(i);
}
});
}
}
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:
package com.example.bankdb;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Create extends Activity {
Button b;
EditText t1;
EditText t2;
EditText t3;
SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_layout);
b=(Button)findViewById(R.id.bCreate);
t1=(EditText)findViewById(R.id.accid);
t2=(EditText)findViewById(R.id.acctype);
t3=(EditText)findViewById(R.id.accbal);
final Context context=this;
try
{
db=openOrCreateDatabase("Banking1",SQLiteDatabase.CREATE_IF_NECESSARY,null);
db.execSQL("CREATE TABLE bank (id integer PRIMARY KEY, type text, bal integer)");
}
catch(Exception e)
{
e.printStackTrace();
}
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String s=t1.getText().toString();
String s1=t2.getText().toString();
String s2=t3.getText().toString();
//db.execSQL("INSERT INTO log VALUES (s)");
ContentValues values=new ContentValues();
values.put("id",s);
values.put("type",s1);
values.put("bal",s2);
if((db.insert("bank",null,values))!= -1)
{
Toast.makeText(Create.this, "Inserted...", 2000).show();
}
else
{
Toast.makeText(Create.this,"Error...",2000).show();
}
t1.setText("");
t2.setText("");
t3.setText("");
Intent i=new Intent(context,Admin.class);
startActivity(i);
}
});
}
}
In the code above I have created a database. The values entered by the admin are then entered in 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:
package com.example.bankdb;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Del extends Activity {
Button b;
EditText e;
SQLiteDatabase db;
SQLiteOpenHelper d;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.del_layout);
b=(Button)findViewById(R.id.bdel);
e=(EditText)findViewById(R.id.acciddel);
final Context context=this;
try
{
db=openOrCreateDatabase("Banking1",SQLiteDatabase.CREATE_IF_NECESSARY,null);
}
catch(SQLiteException e)
{
e.printStackTrace();
System.out.print("ERROR.............");
}
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String t=(e.getText().toString());
try
{
String d="DELETE FROM bank WHERE id="+t;
db.execSQL(d);
}
catch(Exception e)
{
System.out.print("Error..................");
}
e.setText("");
Toast.makeText(Del.this, "Deleted...", 2000).show();
Intent i=new Intent(context,Admin.class);
startActivity(i);
}
});
}
}
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:
package com.example.bankdb;
import android.app.Activity;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.*;
import java.util.ArrayList;
import java.util.List;
public class ViewAcc extends Activity {
SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_layout2);
try
{
db=openOrCreateDatabase("Banking1",SQLiteDatabase.CREATE_IF_NECESSARY,null);
Cursor c= db.rawQuery("SELECT * FROM bank",null);
TextView v=(TextView)findViewById(R.id.v);
c.moveToFirst();
String temp="";
while(! c.isAfterLast())
{
String s2=c.getString(0);
String s3=c.getString(1);
String s4=c.getString(2);
temp=temp+"\n Id:"+s2+"\tType:"+s3+"\tBal:"+s4;
c.moveToNext();
}
v.setText(temp);
}
catch(SQLiteException e)
{
}
}
}
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:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bankdb"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="16" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.bankdb.MainActivity"
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="com.example.bankdb.ViewAcc"
android:label="View">
</activity>
<activity android:name=".Create"
android:label="Create"/>
<activity android:name=".Del"
android:label="Delete"/>
<activity android:name=".Admin"
android:label="Admin"/>
</application>
</manifest>
The output screens looks like:
On clicking Admin you will get:
On clicking Add New you will get (I have filled in some values):
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):
The "Toast" will be generated once you click on the Delete button.
On clicking View Acc you will get:
This ends our tutorial. The article containing the Customer functionalities will be uploaded soon.
Enjoy coding :)