Android SQLite Database

Android provides many ways to store the data.One of the way is SQLite.By default SQLite had embedded with android devices so we are no need to install it manually.

SQLite is lightweight,fast,and compact.Unlike other database, SQLite need not to be configured,started,stoped,managed.

Refer this post for multiple tables in SQLite database.

You can download source code here.

This is code for SQLiteActivity.I have create SQLiteHandler instance inside of SQLiteActivity and call its methods insertRecord() and getRecord().

package com.etr.sqliteexample;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SQLiteActivity extends Activity {
EditText et_Value;
Button insert_Value, get_Value;
SQLiteHandler handler;

@Override
protected void onCreate(Bundle savedInstanceState) {
try {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sqlite);

et_Value = (EditText) findViewById(R.id.enter_value);
insert_Value = (Button) findViewById(R.id.insert);
get_Value = (Button) findViewById(R.id.getValue);

handler = new SQLiteHandler(this);

insert_Value.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
String value = et_Value.getText().toString();
if (value.trim().length() > 0) {
Toast.makeText(SQLiteActivity.this,
handler.insertRecord(value), Toast.LENGTH_LONG)
.show();
et_Value.setText("");
} else {
Toast.makeText(SQLiteActivity.this,
"Insert value before click button",
Toast.LENGTH_LONG).show();
}
}
});

get_Value.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
ArrayList<String> values = handler.getRecord();
for (String name : values) {
Toast.makeText(SQLiteActivity.this, name,
Toast.LENGTH_LONG).show();
}
}
});

} catch (Exception e) {
Log.v("Exception", Log.getStackTraceString(e));
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.sqlite, menu);
return true;
}

}

android.database.sqlite is a package to access the SQLite.This package includes SQLiteOpenHelper,SQLiteDatabase classes.

SQLiteOpenHelper is used to create database and database version management.

onCreate(SQLiteDatabase db) is a SQLiteOpenHelper method.It called when the database is created for the first time.

onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) is a SQLiteOpenHelper method.It called when the database needs to be upgraded.

SQLiteDatabase is a class. It is used to perform CRUD operation.

package com.etr.sqliteexample;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class SQLiteHandler extends SQLiteOpenHelper {

private static final String databaseName = "STUDENTINFODATABASE";
private static final int databaseVersion = 1;

private static final String tableName = "STUDENTINFOTABLE";

public SQLiteHandler(Context context) {
super(context, databaseName, null, databaseVersion);
}

@Override
public void onCreate(SQLiteDatabase db) {
try {
String query = "CREATE TABLE " + tableName
+ "(ID INTEGER PRIMARY KEY,NAME TEXT)";
db.execSQL(query);
} catch (SQLException se) {
Log.v("Exception", Log.getStackTraceString(se));
}
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
String query = "DROP TABLE IF EXISTS " + tableName;
db.execSQL(query);
onCreate(db);
} catch (SQLException se) {
Log.v("Exception", Log.getStackTraceString(se));
}
}

public String insertRecord(String name) {
try {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("NAME", name);
db.insert(tableName, null, contentValues);
db.close();
return "Record inserted successfully";
} catch (SQLException se) {
Log.v("Exception", Log.getStackTraceString(se));
return se.getMessage();
}
}

public ArrayList<String> getRecord() {
ArrayList<String> names = new ArrayList<String>();
try {
SQLiteDatabase database = this.getReadableDatabase();
String selectQuery = "SELECT * FROM " + tableName;
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
names.add(cursor.getString(1));
} while (cursor.moveToNext());
}
} catch (SQLiteException e) {
Log.v("Exception", Log.getStackTraceString(e));
} catch (Exception e) {
Log.v("Exception", Log.getStackTraceString(e));
}
return names;
}
}

This is code for activity_sqlite.xml.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".SQLiteActivity" >

    <EditText
        android:id="@+id/enter_value"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="55dp"
        android:ems="10"
        android:hint="Enter your values"
        android:paddingLeft="15dp" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/insert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/enter_value"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="29dp"
        android:text="Insert Record" />

    <Button
        android:id="@+id/getValue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Retrieve Record" />

</RelativeLayout>

Refer the below screenshots for your understand.


Andrroid SQLite Database

Refer below screenshot for SQLite Storage Location.


Andrroid SQLite Database

Comments

Popular posts from this blog

SQLiteDatabase With Multiple Tables

Programmatically turn ON/OFF WiFi on Android device

Android Service and IntentService