Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Check if a file is a valid SQLite database

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}
like image 978
Rhydam Dargarh Avatar asked Sep 19 '16 15:09

Rhydam Dargarh


1 Answers

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;
    }
}
like image 119
Drilon Kurti Avatar answered Sep 22 '22 22:09

Drilon Kurti