 
                http://www.androidhive.info/2013/09/android-sqlite-database-with-multiple-tables/
In my previous tutorial Android SQLite Database Tutorial I explained how to use SQLite database in your android application. But that covered the scenario, only when you have one table in the database. I am getting lot of queries about handling the sqlite database when it is having multiple tables.
I explained here how to handle the SQLite database when it is having multiple tables.
To make it easier for you to understand, I am taking a real use case example of TODO Applicationdatabase schema in this tutorial. This article doesn’t covers how to design the application, but explains the database design, preparing database helper classes and models.
I considered a basic Todo Application with minimal functionality like creating a todo note andassigning it under a tag(s) (category). So for this we just need three tables in the database.
The three tables are
todos – to store all todo notes
tags – to store list of tags
todo_tags – to store the tags which are assigned to a todo
Check the below diagram that explains the table structure and the relationship between tables

So let’s start by creating a new project in Eclipse IDE
1. Create a new project in Eclipse from File ⇒ New ⇒ Android ⇒ Application Project. I named my package name as info.androidhive.sqlite and left the main activity name as MainActivity.java
2. We need two more packages to keep helpers and model classes. Right Clicking on src ⇒ New ⇒ Package and name them as info.androidhive.sqlite.helper andinfo.androidhive.sqlite.model
Next step is to create model classes for our database tables just to make single row as an object. We need only two models for todos and tags. For todo_tags we don’t need a model class.
3. Create a new class file under info.androidhive.sqlite.helper package named Todo.java and type the code like below. This is the model class for todos table
| packageinfo.androidhive.sqlite.model;publicclassTodo {    intid;    String note;    intstatus;    String created_at;    // constructors    publicTodo() {    }    publicTodo(String note, intstatus) {        this.note = note;        this.status = status;    }    publicTodo(intid, String note, intstatus) {        this.id = id;        this.note = note;        this.status = status;    }    // setters    publicvoidsetId(intid) {        this.id = id;    }    publicvoidsetNote(String note) {        this.note = note;    }    publicvoidsetStatus(intstatus) {        this.status = status;    }        publicvoidsetCreatedAt(String created_at){        this.created_at = created_at;    }    // getters    publiclonggetId() {        returnthis.id;    }    publicString getNote() {        returnthis.note;    }    publicintgetStatus() {        returnthis.status;    }} | 
4. Create one more model class for tags table named Tag.java under the same package.
| packageinfo.androidhive.sqlite.model;publicclassTag {    intid;    String tag_name;    // constructors    publicTag() {    }    publicTag(String tag_name) {        this.tag_name = tag_name;    }    publicTag(intid, String tag_name) {        this.id = id;        this.tag_name = tag_name;    }    // setter    publicvoidsetId(intid) {        this.id = id;    }    publicvoidsetTagName(String tag_name) {        this.tag_name = tag_name;    }    // getter    publicintgetId() {        returnthis.id;    }    publicString getTagName() {        returnthis.tag_name;    }} | 
Database helper class contains all the methods to perform database operations like opening connection, closing connection, insert, update, read, delete and other things. As this class is helper class, place this under helper package.
5. So create another class named DatabaseHelper.java underinfo.androidhive.sqlite.helper package and extend the class from SQLiteOpenHelper
| publicclassDatabaseHelper extendsSQLiteOpenHelper { | 
6. Add required variables like database name, database version, column names. I also executed table create statements in onCreate() method. Type the following code in DatabaseHelper.java class
| publicclassDatabaseHelper extendsSQLiteOpenHelper {    // Logcat tag    privatestaticfinalString LOG = "DatabaseHelper";    // Database Version    privatestaticfinalintDATABASE_VERSION = 1;    // Database Name    privatestaticfinalString DATABASE_NAME = "contactsManager";    // Table Names    privatestaticfinalString TABLE_TODO = "todos";    privatestaticfinalString TABLE_TAG = "tags";    privatestaticfinalString TABLE_TODO_TAG = "todo_tags";    // Common column names    privatestaticfinalString KEY_ID = "id";    privatestaticfinalString KEY_CREATED_AT = "created_at";    // NOTES Table - column nmaes    privatestaticfinalString KEY_TODO = "todo";    privatestaticfinalString KEY_STATUS = "status";    // TAGS Table - column names    privatestaticfinalString KEY_TAG_NAME = "tag_name";    // NOTE_TAGS Table - column names    privatestaticfinalString KEY_TODO_ID = "todo_id";    privatestaticfinalString KEY_TAG_ID = "tag_id";    // Table Create Statements    // Todo table create statement    privatestaticfinalString CREATE_TABLE_TODO = "CREATE TABLE "            + TABLE_TODO + "("+ KEY_ID + " INTEGER PRIMARY KEY,"+ KEY_TODO            + " TEXT,"+ KEY_STATUS + " INTEGER,"+ KEY_CREATED_AT            + " DATETIME"+ ")";    // Tag table create statement    privatestaticfinalString CREATE_TABLE_TAG = "CREATE TABLE "+ TABLE_TAG            + "("+ KEY_ID + " INTEGER PRIMARY KEY,"+ KEY_TAG_NAME + " TEXT,"            + KEY_CREATED_AT + " DATETIME"+ ")";    // todo_tag table create statement    privatestaticfinalString CREATE_TABLE_TODO_TAG = "CREATE TABLE "            + TABLE_TODO_TAG + "("+ KEY_ID + " INTEGER PRIMARY KEY,"            + KEY_TODO_ID + " INTEGER,"+ KEY_TAG_ID + " INTEGER,"            + KEY_CREATED_AT + " DATETIME"+ ")";    publicDatabaseHelper(Context context) {        super(context, DATABASE_NAME, null, DATABASE_VERSION);    }    @Override    publicvoidonCreate(SQLiteDatabase db) {        // creating required tables        db.execSQL(CREATE_TABLE_TODO);        db.execSQL(CREATE_TABLE_TAG);        db.execSQL(CREATE_TABLE_TODO_TAG);    }    @Override    publicvoidonUpgrade(SQLiteDatabase db, intoldVersion, intnewVersion) {        // on upgrade drop older tables        db.execSQL("DROP TABLE IF EXISTS "+ TABLE_TODO);        db.execSQL("DROP TABLE IF EXISTS "+ TABLE_TAG);        db.execSQL("DROP TABLE IF EXISTS "+ TABLE_TODO_TAG);        // create new tables        onCreate(db);    } | 
From now on we are going to add one by one method into DatabaseHelper.class
The function will create a todo item in todos table. In this same function we are assigning the todo to a tag name which inserts a row in todo_tags table.
| /* * Creating a todo */publiclongcreateToDo(Todo todo, long[] tag_ids) {    SQLiteDatabase db = this.getWritableDatabase();    ContentValues values = newContentValues();    values.put(KEY_TODO, todo.getNote());    values.put(KEY_STATUS, todo.getStatus());    values.put(KEY_CREATED_AT, getDateTime());    // insert row    longtodo_id = db.insert(TABLE_TODO, null, values);    // assigning tags to todo    for(longtag_id : tag_ids) {        createTodoTag(todo_id, tag_id);    }    returntodo_id;} | 
Following will fetch a todo from todos table.
| /* * get single todo */publicTodo getTodo(longtodo_id) {    SQLiteDatabase db = this.getReadableDatabase();    String selectQuery = "SELECT  * FROM "+ TABLE_TODO + " WHERE "            + KEY_ID + " = "+ todo_id;    Log.e(LOG, selectQuery);    Cursor c = db.rawQuery(selectQuery, null);    if(c != null)        c.moveToFirst();    Todo td = newTodo();    td.setId(c.getInt(c.getColumnIndex(KEY_ID)));    td.setNote((c.getString(c.getColumnIndex(KEY_TODO))));    td.setCreatedAt(c.getString(c.getColumnIndex(KEY_CREATED_AT)));    returntd;} | 
Fetching all todos involves reading all todo rows and adding them to a list array.
| /* * getting all todos * */publicList<Todo> getAllToDos() {    List<Todo> todos = newArrayList<Todo>();    String selectQuery = "SELECT  * FROM "+ TABLE_TODO;    Log.e(LOG, selectQuery);    SQLiteDatabase db = this.getReadableDatabase();    Cursor c = db.rawQuery(selectQuery, null);    // looping through all rows and adding to list    if(c.moveToFirst()) {        do{            Todo td = newTodo();            td.setId(c.getInt((c.getColumnIndex(KEY_ID))));            td.setNote((c.getString(c.getColumnIndex(KEY_TODO))));            td.setCreatedAt(c.getString(c.getColumnIndex(KEY_CREATED_AT)));            // adding to todo list            todos.add(td);        } while(c.moveToNext());    }    returntodos;} | 
This is also same as reading all the rows but it filters the todos by tag name. Check the following select query which fetches the todos under Watchlist tag name.
| /* * getting all todos under single tag * */publicList<Todo> getAllToDosByTag(String tag_name) {    List<Todo> todos = newArrayList<Todo>();    String selectQuery = "SELECT  * FROM "+ TABLE_TODO + " td, "            + TABLE_TAG + " tg, "+ TABLE_TODO_TAG + " tt WHERE tg."            + KEY_TAG_NAME + " = '"+ tag_name + "'"+ " AND tg."+ KEY_ID            + " = "+ "tt."+ KEY_TAG_ID + " AND td."+ KEY_ID + " = "            + "tt."+ KEY_TODO_ID;    Log.e(LOG, selectQuery);    SQLiteDatabase db = this.getReadableDatabase();    Cursor c = db.rawQuery(selectQuery, null);    // looping through all rows and adding to list    if(c.moveToFirst()) {        do{            Todo td = newTodo();            td.setId(c.getInt((c.getColumnIndex(KEY_ID))));            td.setNote((c.getString(c.getColumnIndex(KEY_TODO))));            td.setCreatedAt(c.getString(c.getColumnIndex(KEY_CREATED_AT)));            // adding to todo list            todos.add(td);        } while(c.moveToNext());    }    returntodos;} | 
Following function will update a todo. It will update Todo values only, not the tag name.
| /* * Updating a todo */publicintupdateToDo(Todo todo) {    SQLiteDatabase db = this.getWritableDatabase();    ContentValues values = newContentValues();    values.put(KEY_TODO, todo.getNote());    values.put(KEY_STATUS, todo.getStatus());    // updating row    returndb.update(TABLE_TODO, values, KEY_ID + " = ?",            newString[] { String.valueOf(todo.getId()) });} | 
Pass todo id to the following function to delete the todo from db.
| /* * Deleting a todo */publicvoiddeleteToDo(longtado_id) {    SQLiteDatabase db = this.getWritableDatabase();    db.delete(TABLE_TODO, KEY_ID + " = ?",            newString[] { String.valueOf(tado_id) });} | 
Until now we are done creating the CRUD methods onto todos table. Now we can start the methods required on tags table.
Following method will insert a row into tags table.
| /* * Creating tag */publiclongcreateTag(Tag tag) {    SQLiteDatabase db = this.getWritableDatabase();    ContentValues values = newContentValues();    values.put(KEY_TAG_NAME, tag.getTagName());    values.put(KEY_CREATED_AT, getDateTime());    // insert row    longtag_id = db.insert(TABLE_TAG, null, values);    returntag_id;} | 
Performing select all statement on tags table will give you list of tag names.
| /** * getting all tags * */publicList<Tag> getAllTags() {    List<Tag> tags = newArrayList<Tag>();    String selectQuery = "SELECT  * FROM "+ TABLE_TAG;    Log.e(LOG, selectQuery);    SQLiteDatabase db = this.getReadableDatabase();    Cursor c = db.rawQuery(selectQuery, null);    // looping through all rows and adding to list    if(c.moveToFirst()) {        do{            Tag t = newTag();            t.setId(c.getInt((c.getColumnIndex(KEY_ID))));            t.setTagName(c.getString(c.getColumnIndex(KEY_TAG_NAME)));            // adding to tags list            tags.add(t);        } while(c.moveToNext());    }    returntags;} | 
Following method will update tag.
| /* * Updating a tag */publicintupdateTag(Tag tag) {    SQLiteDatabase db = this.getWritableDatabase();    ContentValues values = newContentValues();    values.put(KEY_TAG_NAME, tag.getTagName());    // updating row    returndb.update(TABLE_TAG, values, KEY_ID + " = ?",            newString[] { String.valueOf(tag.getId()) });} | 
Following method will delete a tag from db. This also will delete all the todos under the tag name, but this is optional.
should_delete_all_tag_todos = Passing true will delete all the todos under the tag name
| /* * Deleting a tag */publicvoiddeleteTag(Tag tag, booleanshould_delete_all_tag_todos) {    SQLiteDatabase db = this.getWritableDatabase();    // before deleting tag    // check if todos under this tag should also be deleted    if(should_delete_all_tag_todos) {        // get all todos under this tag        List<Todo> allTagToDos = getAllToDosByTag(tag.getTagName());        // delete all todos        for(Todo todo : allTagToDos) {            // delete todo            deleteToDo(todo.getId());        }    }    // now delete the tag    db.delete(TABLE_TAG, KEY_ID + " = ?",            newString[] { String.valueOf(tag.getId()) });} | 
Below are the methods to access the rows from todo_tags table
Following method will assign a todo under a tag name. You can also assign multiple tags to a todo by calling this function multiple times.
| /*     * Creating todo_tag     */    publiclongcreateTodoTag(longtodo_id, longtag_id) {        SQLiteDatabase db = this.getWritableDatabase();        ContentValues values = newContentValues();        values.put(KEY_TODO_ID, todo_id);        values.put(KEY_TAG_ID, tag_id);        values.put(KEY_CREATED_AT, getDateTime());        longid = db.insert(TABLE_TODO_TAG, null, values);        returnid;    } | 
Following method will remove the tag assigned to a todo
| /* * Updating a todo tag */publicintupdateNoteTag(longid, longtag_id) {    SQLiteDatabase db = this.getWritableDatabase();    ContentValues values = newContentValues();    values.put(KEY_TAG_ID, tag_id);    // updating row    returndb.update(TABLE_TODO, values, KEY_ID + " = ?",            newString[] { String.valueOf(id) });} | 
Following simply replaces the tag name of a todo
| /* * Updating a todo tag */publicintupdateNoteTag(longid, longtag_id) {    SQLiteDatabase db = this.getWritableDatabase();    ContentValues values = newContentValues();    values.put(KEY_TAG_ID, tag_id);    // updating row    returndb.update(TABLE_TODO, values, KEY_ID + " = ?",            newString[] { String.valueOf(id) });} | 
Importantly don’t forget to close the database connection once you done using it. Call following method when you don’t need access to db anymore.
| // closing database    publicvoidcloseDB() {        SQLiteDatabase db = this.getReadableDatabase();        if(db != null&& db.isOpen())            db.close();    } | 
As this tutorial already seems lengthy I am not considering giving an example with a sample application. In upcoming tutorial I will give you a simple todo application which will give you complete picture of using multiple SQLite tables in your android apps.
For now we will test the class just by printing the data to Logcat.
Open your main activity class and type the following. In the below I just created sample tags and todo data and performed the all the operations by calling the methods which we prepared in DatabaseHelper class.
| packageinfo.androidhive.sqlite;importinfo.androidhive.sqlite.helper.DatabaseHelper;importinfo.androidhive.sqlite.model.Tag;importinfo.androidhive.sqlite.model.Todo;importjava.util.List;importandroid.app.Activity;importandroid.os.Bundle;importandroid.util.Log;publicclassMainActivity extendsActivity {    // Database Helper    DatabaseHelper db;    @Override    protectedvoidonCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        db = newDatabaseHelper(getApplicationContext());        // Creating tags        Tag tag1 = newTag("Shopping");        Tag tag2 = newTag("Important");        Tag tag3 = newTag("Watchlist");        Tag tag4 = newTag("Androidhive");        // Inserting tags in db        longtag1_id = db.createTag(tag1);        longtag2_id = db.createTag(tag2);        longtag3_id = db.createTag(tag3);        longtag4_id = db.createTag(tag4);        Log.d("Tag Count", "Tag Count: "+ db.getAllTags().size());        // Creating ToDos        Todo todo1 = newTodo("iPhone 5S", 0);        Todo todo2 = newTodo("Galaxy Note II", 0);        Todo todo3 = newTodo("Whiteboard", 0);        Todo todo4 = newTodo("Riddick", 0);        Todo todo5 = newTodo("Prisoners", 0);        Todo todo6 = newTodo("The Croods", 0);        Todo todo7 = newTodo("Insidious: Chapter 2", 0);        Todo todo8 = newTodo("Don't forget to call MOM", 0);        Todo todo9 = newTodo("Collect money from John", 0);        Todo todo10 = newTodo("Post new Article", 0);        Todo todo11 = newTodo("Take database backup", 0);        // Inserting todos in db        // Inserting todos under "Shopping" Tag        longtodo1_id = db.createToDo(todo1, newlong[] { tag1_id });        longtodo2_id = db.createToDo(todo2, newlong[] { tag1_id });        longtodo3_id = db.createToDo(todo3, newlong[] { tag1_id });        // Inserting todos under "Watchlist" Tag        longtodo4_id = db.createToDo(todo4, newlong[] { tag3_id });        longtodo5_id = db.createToDo(todo5, newlong[] { tag3_id });        longtodo6_id = db.createToDo(todo6, newlong[] { tag3_id });        longtodo7_id = db.createToDo(todo7, newlong[] { tag3_id });        // Inserting todos under "Important" Tag        longtodo8_id = db.createToDo(todo8, newlong[] { tag2_id });        longtodo9_id = db.createToDo(todo9, newlong[] { tag2_id });        // Inserting todos under "Androidhive" Tag        longtodo10_id = db.createToDo(todo10, newlong[] { tag4_id });        longtodo11_id = db.createToDo(todo11, newlong[] { tag4_id });        Log.e("Todo Count", "Todo count: "+ db.getToDoCount());        // "Post new Article" - assigning this under "Important" Tag        // Now this will have - "Androidhive" and "Important" Tags        db.createTodoTag(todo10_id, tag2_id);        // Getting all tag names        Log.d("Get Tags", "Getting All Tags");        List<Tag> allTags = db.getAllTags();        for(Tag tag : allTags) {            Log.d("Tag Name", tag.getTagName());        }        // Getting all Todos        Log.d("Get Todos", "Getting All ToDos");        List<Todo> allToDos = db.getAllToDos();        for(Todo todo : allToDos) {            Log.d("ToDo", todo.getNote());        }        // Getting todos under "Watchlist" tag name        Log.d("ToDo", "Get todos under single Tag name");        List<Todo> tagsWatchList = db.getAllToDosByTag(tag3.getTagName());        for(Todo todo : tagsWatchList) {            Log.d("ToDo Watchlist", todo.getNote());        }        // Deleting a ToDo        Log.d("Delete ToDo", "Deleting a Todo");        Log.d("Tag Count", "Tag Count Before Deleting: "+ db.getToDoCount());        db.deleteToDo(todo8_id);        Log.d("Tag Count", "Tag Count After Deleting: "+ db.getToDoCount());        // Deleting all Todos under "Shopping" tag        Log.d("Tag Count",                "Tag Count Before Deleting 'Shopping' Todos: "                        + db.getToDoCount());        db.deleteTag(tag1, true);        Log.d("Tag Count",                "Tag Count After Deleting 'Shopping' Todos: "                        + db.getToDoCount());        // Updating tag name        tag3.setTagName("Movies to watch");        db.updateTag(tag3);        // Don't forget to close database connection        db.closeDB();            }} | 
Run the application and the check the Logcat.
| packageinfo.androidhive.sqlite.helper;importinfo.androidhive.sqlite.model.Tag;importinfo.androidhive.sqlite.model.Todo;importjava.text.SimpleDateFormat;importjava.util.ArrayList;importjava.util.Date;importjava.util.List;importjava.util.Locale;importandroid.content.ContentValues;importandroid.content.Context;importandroid.database.Cursor;importandroid.database.sqlite.SQLiteDatabase;importandroid.database.sqlite.SQLiteOpenHelper;importandroid.util.Log;publicclassDatabaseHelper extendsSQLiteOpenHelper {    // Logcat tag    privatestaticfinalString LOG = DatabaseHelper.class.getName();    // Database Version    privatestaticfinalintDATABASE_VERSION = 1;    // Database Name    privatestaticfinalString DATABASE_NAME = "contactsManager";    // Table Names    privatestaticfinalString TABLE_TODO = "todos";    privatestaticfinalString TABLE_TAG = "tags";    privatestaticfinalString TABLE_TODO_TAG = "todo_tags";    // Common column names    privatestaticfinalString KEY_ID = "id";    privatestaticfinalString KEY_CREATED_AT = "created_at";    // NOTES Table - column nmaes    privatestaticfinalString KEY_TODO = "todo";    privatestaticfinalString KEY_STATUS = "status";    // TAGS Table - column names    privatestaticfinalString KEY_TAG_NAME = "tag_name";    // NOTE_TAGS Table - column names    privatestaticfinalString KEY_TODO_ID = "todo_id";    privatestaticfinalString KEY_TAG_ID = "tag_id";    // Table Create Statements    // Todo table create statement    privatestaticfinalString CREATE_TABLE_TODO = "CREATE TABLE "            + TABLE_TODO + "("+ KEY_ID + " INTEGER PRIMARY KEY,"+ KEY_TODO            + " TEXT,"+ KEY_STATUS + " INTEGER,"+ KEY_CREATED_AT            + " DATETIME"+ ")";    // Tag table create statement    privatestaticfinalString CREATE_TABLE_TAG = "CREATE TABLE "+ TABLE_TAG            + "("+ KEY_ID + " INTEGER PRIMARY KEY,"+ KEY_TAG_NAME + " TEXT,"            + KEY_CREATED_AT + " DATETIME"+ ")";    // todo_tag table create statement    privatestaticfinalString CREATE_TABLE_TODO_TAG = "CREATE TABLE "            + TABLE_TODO_TAG + "("+ KEY_ID + " INTEGER PRIMARY KEY,"            + KEY_TODO_ID + " INTEGER,"+ KEY_TAG_ID + " INTEGER,"            + KEY_CREATED_AT + " DATETIME"+ ")";    publicDatabaseHelper(Context context) {        super(context, DATABASE_NAME, null, DATABASE_VERSION);    }    @Override    publicvoidonCreate(SQLiteDatabase db) {        // creating required tables        db.execSQL(CREATE_TABLE_TODO);        db.execSQL(CREATE_TABLE_TAG);        db.execSQL(CREATE_TABLE_TODO_TAG);    }    @Override    publicvoidonUpgrade(SQLiteDatabase db, intoldVersion, intnewVersion) {        // on upgrade drop older tables        db.execSQL("DROP TABLE IF EXISTS "+ TABLE_TODO);        db.execSQL("DROP TABLE IF EXISTS "+ TABLE_TAG);        db.execSQL("DROP TABLE IF EXISTS "+ TABLE_TODO_TAG);        // create new tables        onCreate(db);    }    // ------------------------ "todos" table methods ----------------//     /**     * Creating a todo     */    publiclongcreateToDo(Todo todo, long[] tag_ids) {        SQLiteDatabase db = this.getWritableDatabase();        ContentValues values = newContentValues();        values.put(KEY_TODO, todo.getNote());        values.put(KEY_STATUS, todo.getStatus());        values.put(KEY_CREATED_AT, getDateTime());        // insert row        longtodo_id = db.insert(TABLE_TODO, null, values);        // insert tag_ids        for(longtag_id : tag_ids) {            createTodoTag(todo_id, tag_id);        }        returntodo_id;    }    /**     * get single todo     */    publicTodo getTodo(longtodo_id) {        SQLiteDatabase db = this.getReadableDatabase();        String selectQuery = "SELECT  * FROM "+ TABLE_TODO + " WHERE "                + KEY_ID + " = "+ todo_id;        Log.e(LOG, selectQuery);        Cursor c = db.rawQuery(selectQuery, null);        if(c != null)            c.moveToFirst();        Todo td = newTodo();        td.setId(c.getInt(c.getColumnIndex(KEY_ID)));        td.setNote((c.getString(c.getColumnIndex(KEY_TODO))));        td.setCreatedAt(c.getString(c.getColumnIndex(KEY_CREATED_AT)));        returntd;    }    /**     * getting all todos     * */    publicList<Todo> getAllToDos() {        List<Todo> todos = newArrayList<Todo>();        String selectQuery = "SELECT  * FROM "+ TABLE_TODO;        Log.e(LOG, selectQuery);        SQLiteDatabase db = this.getReadableDatabase();        Cursor c = db.rawQuery(selectQuery, null);        // looping through all rows and adding to list        if(c.moveToFirst()) {            do{                Todo td = newTodo();                td.setId(c.getInt((c.getColumnIndex(KEY_ID))));                td.setNote((c.getString(c.getColumnIndex(KEY_TODO))));                td.setCreatedAt(c.getString(c.getColumnIndex(KEY_CREATED_AT)));                // adding to todo list                todos.add(td);            } while(c.moveToNext());        }        returntodos;    }    /**     * getting all todos under single tag     * */    publicList<Todo> getAllToDosByTag(String tag_name) {        List<Todo> todos = newArrayList<Todo>();        String selectQuery = "SELECT  * FROM "+ TABLE_TODO + " td, "                + TABLE_TAG + " tg, "+ TABLE_TODO_TAG + " tt WHERE tg."                + KEY_TAG_NAME + " = '"+ tag_name + "'"+ " AND tg."+ KEY_ID                + " = "+ "tt."+ KEY_TAG_ID + " AND td."+ KEY_ID + " = "                + "tt."+ KEY_TODO_ID;        Log.e(LOG, selectQuery);        SQLiteDatabase db = this.getReadableDatabase();        Cursor c = db.rawQuery(selectQuery, null);        // looping through all rows and adding to list        if(c.moveToFirst()) {            do{                Todo td = newTodo();                td.setId(c.getInt((c.getColumnIndex(KEY_ID))));                td.setNote((c.getString(c.getColumnIndex(KEY_TODO))));                td.setCreatedAt(c.getString(c.getColumnIndex(KEY_CREATED_AT)));                // adding to todo list                todos.add(td);            } while(c.moveToNext());        }        returntodos;    }    /**     * getting todo count     */    publicintgetToDoCount() {        String countQuery = "SELECT  * FROM "+ TABLE_TODO;        SQLiteDatabase db = this.getReadableDatabase();        Cursor cursor = db.rawQuery(countQuery, null);        intcount = cursor.getCount();        cursor.close();        // return count        returncount;    }    /**     * Updating a todo     */    publicintupdateToDo(Todo todo) {        SQLiteDatabase db = this.getWritableDatabase();        ContentValues values = newContentValues();        values.put(KEY_TODO, todo.getNote());        values.put(KEY_STATUS, todo.getStatus());        // updating row        returndb.update(TABLE_TODO, values, KEY_ID + " = ?",                newString[] { String.valueOf(todo.getId()) });    }    /**     * Deleting a todo     */    publicvoiddeleteToDo(longtado_id) {        SQLiteDatabase db = this.getWritableDatabase();        db.delete(TABLE_TODO, KEY_ID + " = ?",                newString[] { String.valueOf(tado_id) });    }    // ------------------------ "tags" table methods ----------------//    /**     * Creating tag     */    publiclongcreateTag(Tag tag) {        SQLiteDatabase db = this.getWritableDatabase();        ContentValues values = newContentValues();        values.put(KEY_TAG_NAME, tag.getTagName());        values.put(KEY_CREATED_AT, getDateTime());        // insert row        longtag_id = db.insert(TABLE_TAG, null, values);        returntag_id;    }    /**     * getting all tags     * */    publicList<Tag> getAllTags() {        List<Tag> tags = newArrayList<Tag>();        String selectQuery = "SELECT  * FROM "+ TABLE_TAG;        Log.e(LOG, selectQuery);        SQLiteDatabase db = this.getReadableDatabase();        Cursor c = db.rawQuery(selectQuery, null);        // looping through all rows and adding to list        if(c.moveToFirst()) {            do{                Tag t = newTag();                t.setId(c.getInt((c.getColumnIndex(KEY_ID))));                t.setTagName(c.getString(c.getColumnIndex(KEY_TAG_NAME)));                // adding to tags list                tags.add(t);            } while(c.moveToNext());        }        returntags;    }    /**     * Updating a tag     */    publicintupdateTag(Tag tag) {        SQLiteDatabase db = this.getWritableDatabase();        ContentValues values = newContentValues();        values.put(KEY_TAG_NAME, tag.getTagName());        // updating row        returndb.update(TABLE_TAG, values, KEY_ID + " = ?",                newString[] { String.valueOf(tag.getId()) });    }    /**     * Deleting a tag     */    publicvoiddeleteTag(Tag tag, booleanshould_delete_all_tag_todos) {        SQLiteDatabase db = this.getWritableDatabase();        // before deleting tag        // check if todos under this tag should also be deleted        if(should_delete_all_tag_todos) {            // get all todos under this tag            List<Todo> allTagToDos = getAllToDosByTag(tag.getTagName());            // delete all todos            for(Todo todo : allTagToDos) {                // delete todo                deleteToDo(todo.getId());            }        }        // now delete the tag        db.delete(TABLE_TAG, KEY_ID + " = ?",                newString[] { String.valueOf(tag.getId()) });    }    // ------------------------ "todo_tags" table methods ----------------//    /**     * Creating todo_tag     */    publiclongcreateTodoTag(longtodo_id, longtag_id) {        SQLiteDatabase db = this.getWritableDatabase();        ContentValues values = newContentValues();        values.put(KEY_TODO_ID, todo_id);        values.put(KEY_TAG_ID, tag_id);        values.put(KEY_CREATED_AT, getDateTime());        longid = db.insert(TABLE_TODO_TAG, null, values);        returnid;    }    /**     * Updating a todo tag     */    publicintupdateNoteTag(longid, longtag_id) {        SQLiteDatabase db = this.getWritableDatabase();        ContentValues values = newContentValues();        values.put(KEY_TAG_ID, tag_id);        // updating row        returndb.update(TABLE_TODO, values, KEY_ID + " = ?",                newString[] { String.valueOf(id) });    }    /**     * Deleting a todo tag     */    publicvoiddeleteToDoTag(longid) {        SQLiteDatabase db = this.getWritableDatabase();        db.delete(TABLE_TODO, KEY_ID + " = ?",                newString[] { String.valueOf(id) });    }    // closing database    publicvoidcloseDB() {        SQLiteDatabase db = this.getReadableDatabase();        if(db != null&& db.isOpen())            db.close();    }    /**     * get datetime     * */    privateString getDateTime() {        SimpleDateFormat dateFormat = newSimpleDateFormat(                "yyyy-MM-dd HH:mm:ss", Locale.getDefault());        Date date = newDate();        returndateFormat.format(date);    }} |