1 October 2013

How to delete your database in Android ?

SOLUTION FOR
My solution is for  people who need implementation for : API 8 until 15 (as  API 16 and above has built-in method,which i will mention too)

STORY:
Let's say that you want delete your amazing database,so you look here:
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
and you see method called      deleteDatabase(File file)
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#deleteDatabase(java.io.File)

 Awesome ,but there is a  .. bad news.

It was  added in API level 16 :(, so as long as you write application that will be works on Android 4.1 and above,then ...NO PROBLEM.
However ....  what to do ,if you want support Android 4.0.x (21.7% of devices in use in 09'2013) or Android 2.3.3- 2.3.7 (30.7%   of devices in use in 09'2013) ?

SOLUTION:
Solution was written for The Android Open Source Project and it is NOT mine. (which is a good news)

If solution exists in  API 16,then ... Why not Let's rip off API 16 source code  and inject to your application :),which ... works perfectly well.

*SOURCE CODE FROM android.database.sqlite.SQLiteDatabase*
/**
* Deletes a database including its journal file and other auxiliary files
* that may have been created by the database engine.
*
* @param file The database file path.
* @return True if the database was successfully deleted.
*/
public static boolean deleteDatabase(File file) {
   if (file == null) {
    throw new IllegalArgumentException("file must not be null");
}

boolean deleted = false;
deleted |= file.delete();
deleted |= new File(file.getPath() + "-journal").delete();
deleted |= new File(file.getPath() + "-shm").delete();
deleted |= new File(file.getPath() + "-wal").delete();

File dir = file.getParentFile();
if (dir != null) {
   final String prefix = file.getName() + "-mj";
   final FileFilter filter = new FileFilter() {
    @Override
    public boolean accept(File candidate) {
     return candidate.getName().startsWith(prefix);
    }
   };
   for (File masterJournal : dir.listFiles(filter)) {
    deleted |= masterJournal.delete();
   }
  }
  return deleted;
}


Simply use this method (you can store in your common used utility class )


(Source code uses this  license)

/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/