I need to check whether a file (with unknown extension) is a valid SQLite database. The db file is stored on the sd card. I need to import the database in my app. But if the user creates a file by the same name as of the database with any extension the file is still accepted by the code as it searches only for the name. Is there a quick way to check for the validity of sqlite db stored on memory card. I used this code, but it still accepts arbitrary file with same name as db.
String path = Environment.getExternalStorageDirectory().getPath() + "/FOLDER/DB_FILE";
SQLiteDatabase database;
database = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
if (database == null) {
Toast.makeText(getApplicationContext(), "Error: Incorrect/Corrupted File", Toast.LENGTH_SHORT).show();
return;
} else {Proceed with code here}
A SQLite database file contains a header which provides some useful information. In particular, every SQlite database file has always in it's first 16 bytes the value: SQLite format 3\0000
So you can check if your file contains that value in its first 16 bytes:
public boolean isValidSQLite(String dbPath) {
File file = new File(dbPath);
if (!file.exists() || !file.canRead()) {
return false;
}
try {
FileReader fr = new FileReader(file);
char[] buffer = new char[16];
fr.read(buffer, 0, 16);
String str = String.valueOf(buffer);
fr.close();
return str.equals("SQLite format 3\u0000");
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With