Databases in Android using SQLite – Part I

This entry is part 24 of 50 in the series Android Development Primer

In this post I will show you how to integrate SQLite and Java in your Android Application. If you do not have a fair idea of SQLite, I would suggest you to take a look at my previous post and follow the instructions.

Create an Activity and start programming. Complete Source Code is at the bottom.

  • Set the Content View of the activity. Do not put any elements in the layout.
  • Switch over to the java file and write the below lines after the setContentView() method.
    SQLiteDatabase db = openOrCreateDatabase("NeroDB", MODE_PRIVATE, null);
    db.execSQL("CREATE TABLE IF NOT EXISTS NeroTable(LastName VARCHAR, FirstName VARCHAR, Age INT(3));");
    db.execSQL("INSERT INTO NeroTable VALUES('NeroLast1', 'NeroFirst1', 20);");
    db.execSQL("INSERT INTO NeroTable VALUES('NeroLast2', 'NeroFirst2', 21);");
    db.execSQL("INSERT INTO NeroTable VALUES('NeroLast3', 'NeroFirst3', 22);");
    db.close();
    
  • Since, this post assumes that you have a fair idea of SQLite, you can change the name of the Database, table and the values inside the table to whatever you wish.
  • Save your activity and execute it on the emulator.
  • It is apparent that you have no way of knowing whether the database and the table were successfully created and whether the values were inserted into it.
  • This is where DDMS comes into play. Switch over to the DDMS section and you should see the File Explorer section just above the LogCat and Console. This is an explorer for the files in the SD card of the emulator. Remember that the emulator must be running in order for you to browse the files.
  • Navigate to data/data/<yourapplicationname>/databases. Here you should see a database file with the name of the database. If it is there, your database was successfully created. If not, something went wrong and you should check your code.

Db1

  • Remember that your application may encounter exceptions that require you to Force Close you application. In such cases refer to the LogCat in the DDMS and it should point you exactly to what exception was encountered. Also, you should know that since the exception may be encountered in on of the SQL queries, your Database and the table might have been successfully created and the exception occured thereafter.

Understanding the Code

  • SQLite Database db :- This is an instance of SQLite Database that we are creating.
  • openOrCreateDatabase(String Name, int mode, CursorFactory Factory) :- This functions opens the database if there exists a database by the name provided. If not, it creates one and opens it. Mode is provided in order to let the system know the accessibility of the database. By MODE_PRIVATE, we tell the system that this database is private to our application. CursorFactory is beyond the scope of this post. We do not need to use it and hence it is provided a value of null.
  • execSQL() :- This function allows us to write the SQL query as a string and execute it. Remember that there are other ways to write queries in which pure SQL will not be used.
  • close() :- This function closes the database. Recall that we had used the openOrCreateDatabase to open the database. Closing the database is essential to prevent leak.

COMPLETE SOURCE CODE

Main.java

package com.nero.myfirstapp;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Main extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SQLiteDatabase db = openOrCreateDatabase("NeroDB", MODE_PRIVATE, null);
        db.execSQL("CREATE TABLE IF NOT EXISTS NeroTable(LastName VARCHAR, FirstName VARCHAR, Age INT(3));");
        db.execSQL("INSERT INTO NeroTable VALUES('NeroLast1', 'NeroFirst1', 20);");
        db.execSQL("INSERT INTO NeroTable VALUES('NeroLast2', 'NeroFirst2', 21);");
        db.execSQL("INSERT INTO NeroTable VALUES('NeroLast3', 'NeroFirst3', 22);");
        db.close();
    }
}

Series Navigation<< Android development: Introducing SQLiteDatabases in Android using SQLite – Part II >>

Leave a Reply

Your email address will not be published. Required fields are marked *

*

* Copy This Password *

* Type Or Paste Password Here *

43,702 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>