Thursday, September 6, 2012

SQLite Database in Android | Simple SQLite demo in Android


Hello Friends,

I am going to share how to create SQLite Database in Android and how to insert values and how to get values from DB. Important steps are given below-

1-Create new android project.
2-Create a Java Class DataBaseHandler and extends it with SQLiteOpenHelper class.
3-Create a Contact.java class for getter setter.
4-Create an Android activity for insert and get values from database.
5-See result in log.

1-DataBaseHandler .java
package com.manish.sqlite;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DataBaseHandler extends SQLiteOpenHelper {

// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "sqliteDemo";

// Contacts table name
private static final String TABLE_CONTACTS = "contacts";

// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";

public DataBaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

// Create tables again
onCreate(db);

}

/**
* All CRUD(Create, Read, Update, Delete) Operations
*/

public// Adding new contact
void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact._name); // Contact Name

// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}

// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();

Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME }, KEY_ID + "=?", new String[] { String.valueOf(id) },
null, null, null, null);
if (cursor != null)
cursor.moveToFirst();

Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1));

// return contact
return contact;

}

// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM contacts ORDER BY name";

SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// close inserting data from database
db.close();
// return contact list
return contactList;

}

// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());

// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });

}

// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}

// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();

// return count
return cursor.getCount();
}

}


2-Contact.java
package com.manish.sqlite;

public class Contact {

// private variables
int _id;
String _name;

// Empty constructor
public Contact() {

}

// constructor
public Contact(int keyId, String name) {
this._id = keyId;
this._name = name;

}

// constructor
public Contact(int keyId) {
this._id = keyId;

}

// constructor
public Contact(String name) {
this._name = name;

}

// getting ID
public int getID() {
return this._id;
}

// setting id
public void setID(int keyId) {
this._id = keyId;
}

// getting name
public String getName() {
return this._name;
}

// setting name
public void setName(String name) {
this._name = name;
}

}

3-SQLiteDemoActivity.java
package com.manish.sqlite;

import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class SQLiteDemoActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// final ListView lstView = (ListView) findViewById(R.id.list);
DataBaseHandler db = new DataBaseHandler(this);

// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact("Shyam"));
db.addContact(new Contact("Mohan"));
db.addContact(new Contact("Ajay"));

// Geting contacts and show it in LOG

// Reading all contacts from database
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "ID:" + cn.getID() + " Name: " + cn.getName();

// Writing Contacts to log
Log.d("Name: ", log);

}
}
}

4-Output-

09-06 22:00:32.028: D/Insert:(366): Inserting ..
09-06 22:00:32.108: D/Name:(366): ID:4 Name: Ajay
09-06 22:00:32.108: D/Name:(366): ID:3 Name: Mohan
09-06 22:00:32.108: D/Name:(366): ID:1 Name: Ram
09-06 22:00:32.108: D/Name:(366): ID:2 Name: Shyam

For Image in database and display it in a list you can refer below link-
http://www.androidhub4you.com/2012/09/hello-friends-today-i-am-going-to-share.html

2 comments:

  1. Is there any reason of using underscore Id (_id), (key)keyId in Contacts.java. Is this naming convention for variables?




    ReplyDelete
    Replies
    1. No any special reason here! you can use any thing :)
      well good habit is-
      method name- drawChart();
      variable name- int id;
      class name- Test;
      etc...

      Delete