drop All Database Tables - Android Database

Android examples for Database:Table Drop

Description

drop All Database Tables

Demo Code


//package com.java2s;
import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteException;

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

public class Main {
    public static boolean dropAllTables(SQLiteDatabase db)
            throws SQLiteException {
        if (db == null) {
            return false;
        }/*from w w w.  j av  a2s  . co  m*/

        if (db.isReadOnly()) {
            throw new SQLiteException(
                    "can't drop tables from a read-only database");
        }

        List<String> tableNames = new ArrayList<String>();
        Cursor cursor = db.rawQuery(
                "SELECT name FROM sqlite_master WHERE type='table'", null);
        if (cursor.moveToFirst()) {
            do {
                String tableName = cursor.getString(0);
                if (!tableName.equals("android_metadata")
                        && !tableName.equals("sqlite_sequence")) {
                    tableNames.add(tableName);
                }
            } while (cursor.moveToNext());
        }

        db.beginTransaction();
        try {
            for (String tableName : tableNames) {
                db.execSQL("DROP TABLE IF EXISTS " + tableName);
            }
            db.setTransactionSuccessful();
            return true;
        } finally {
            db.endTransaction();
        }
    }
}

Related Tutorials