Skip to main content

Part 2: A guide to Android SQLite ( part 2: Creating the database) - x-droov

Now that you learnt what Android sqlite is. In part 2, you'll be guided on how to create an SQLite database for your app. This creation will let you open a new database in your app's specific storage. That means that only your app will be able to read and write into that database.
In many instances, you'll have to work with an information collecting app which needs database knowledge. If you understand SQLite, all will be good for you.
Before we embark on creating our database, lets welcome those who are just joining the guide to know what they have missed.

A guide to Android sqlite: contents( course outline)

Part 1: A guide to Android SQLite( part 1: what it is)

The introduction to SQLite and the database working space. A detailed guide of what you can do with it and a wrap-up of what to look out for in an Android SQLite tutorial.

Part 2: A guide to Android SQLite ( part 2: Creating the database)

This is the first thing to learn as you embark on data management. Many will tell you that if you can create a database, you can read an existing database.
That's wrong. In this series, you'll learn both. Or you can navigate to what you want to learn.

Part 3: A guide to Android SQLite ( part 3: Reading and writing into a database)

Now that you can create a database, this article will teach you how to read records from a database and how to write into it.

Part 4: A guide to Android SQLite ( part 4: Displaying content from the database)

Once you have read data, you have to display it. Here you'll learn about using adapters, using other views and creating your own adapters manually.

Part 5: A guide to Android SQLite ( part 5: Reading an existing database)

This is the fun part. We'll drain-out what almost no Android development book will teach you, reading existing SQLite.
I spent long learning this and finally got to what I was looking for. In this part, I will let you know all I learnt and how you can apply it.

Part 6: A guide to Android SQLite ( part 6: how cursors work)

Worried of managing data that you have queried from your database, read this carefully and I will teach you something.
This is the master guide to cursors, cursor loaders and all you need to process your results.

Part 7: A guide to Android SQLite ( part 7: Living with SQLite on your own)

Don't get worried. This is your seal. I'll run you through how to organize SQLite code like a pro and tip you on how you can further deepen your knowledge on SQLite.

Part 8: A guide to Android SQLite ( part 8: SQL - the basics)

The SQL you need to survive. This is the basic guide, but will let you get what you want and leave what you want in a database.

Methods of creating an SQLitedatabase

There are two methods of creating an SQLite database:
1. Using an SQLiteOpenHelper class
2. Using the SQLiteDatabase class

Method 1: Using a database helper

A database helper is the best way of accessing the database. It'll help you with most of the Heck.
In a database helper, you have to override the onCreate and onUpgrade methods of the class.
The onCreate handles the logic to be done when the database is created. This can be creating the required tables and any other logic you want to do as it's created. It can even be saving sensitive information from a users device in the database.
The onUpgrade method is called when the database exists. It does the logic of upgrading the database version if it has changed. Or it can delete existing database if it exists.
Here's the database open helper class

package com.rea;

package com.rea;

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;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;


public class b extends SQLiteOpenHelper {

    

    private SQLiteDatabase db;

    private final Context myContext;

    public b(Context context) {

        super(context, "your db name", null, 10);

        this.myContext = context;

      

    }


    

    @Override

    public void onCreate(SQLiteDatabase db) {

   db.execSQL("Create table emmy(number integer,name text)");

    }

    @Override

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        if (newVersion > oldVersion){

           db.execSQL("delete your db name") 

        }

            

    }

    


}



Once you have created the database open helper, you now have to refer to it when doing transactions with your database.
This is done in the class that is using the database. You import the SQLiteDatabase class and use it to access the helper class by casting.
b dbHelp= new b(context);
SQLiteDatabase db= dbHelp.getWritableDatabase();
The context variable is of the type Context just like cc variable in the main activity code below.

package com.rea;

package com.rea;

import android.database.sqlite.SQLiteDatabase;

import android.database.SQLException;

import android.app.Activity;

import android.os.Bundle;

import android.view.Menu;

import android.view.MenuItem;

import android.view.View;

import android.widget.Button;

import android.widget.Toast;

import android.content.Context;

import android.database.sqlite.SQLiteException;


public class MainActivity extends Activity {

   // Cursor c;

Context cc= this;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.layout_main);

        ((Button) findViewById(R.id.button01)).setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                b myDbHelper = new b(cc);

                try {

                    SQLiteDatabase db= myDbHelper.getWritableDatabase();

                    db.rawQuery("select * from emmy",null);

                    Toast.makeText(cc, "Successfully created", Toast.LENGTH_SHORT).show();

                } catch (SQLiteException ioe) {

                    //throw new Error("Unable to create database");

               Toast.makeText(cc, "db not created", Toast.LENGTH_SHORT).show();

                }

                

           

            }

        });

    }

}


The database is opened and used in try and catch blocks inorder to handle exceptions which may crash your app in case of a mistake.
The method execSQL() will be covered in the next parts of the guide, but it's a way of querying data from the database.
In the onCreate method, we created the database and in the main activity, we used rawQuery() to select all data from the empty database.
If our database isn't created, the catch block toast will show up.

Method 2: Using the SQLiteDatabase class

Here we use methods of the SQLiteDatabase class to create our database. Because we are creating it manually, we don't need a helper class.
The SQLiteDatabase class has several methods for creating a database, but we'll use the openDatabase("string-path", Cursor factory,int) method like the example below.

package com.rea;

import android.database.sqlite.SQLiteDatabase;

import android.database.SQLException;

import android.app.Activity;

import android.os.Bundle;


import android.view.Menu;

import android.view.MenuItem;

import android.view.View;

import android.widget.Button;

import android.widget.Toast;

import android.content.Context;

import android.database.sqlite.SQLiteException;



public class MainActivity extends Activity {

   // Cursor c;

Context cc= this;

public static SQLiteDatabase db;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.layout_main);


        ((Button) findViewById(R.id.button01)).setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                

                try {

                    

                    db = SQLiteDatabase.openDatabase("/data/data/com.rea/files/emma.db",null, SQLiteDatabase.CREATE_IF_NECESSARY);

                    db.rawQuery("create table emmy(no integer,name text)",null);

                   

                    db.close();

                    Toast.makeText(cc, "Successfully created", Toast.LENGTH_SHORT).show();

                } catch (SQLiteException ioe) {

                    //throw new Error("Unable to create database");

               Toast.makeText(cc, "db not created", Toast.LENGTH_SHORT).show();

                }

                

           

            }

        });

    }


}


Here you specify the path to the database and instead of opening, you add a modifier CREATE_IF_NECESSARY. That will create a database if it is not existent. Other modifiers that you'll be using after creating the database are OPEN_READONLY and OPEN_READWRITE. All are self-explanatory.
Once you have opened the database, create some tables and close it.
Remember that some devices use file path: "/data/data/com.yourpackage/databases/emma.db" so watch out for that.
That's what you need to create a database. I can't specify all methods because no one can. You just need a running database and there is no use in knowing all methods if you know one that works. Maybe if you want to be a hacker.
Thanks for reaching the end lets meet in the next part.

Part 3: A guide to Android SQLite ( part 3: Reading and writing into a database)

Now that you can create a database, this article will teach you how to read records from a database and how to write into it.

AUTHOR

Emmy Jayson x-droov


Emmy Jayson


Comments