Android Question SQLite and invalid databases

obscure

Member
Licensed User
Longtime User
Hi all.

In my application I've added some functionality to backup and restore
a database. To prevent overwriting of the existing database with a file
that isn't a database at all, I'm doing a quick and dirty check
like this:
B4X:
Dim localDB As SQL
Dim localCursor As Cursor
Dim isValid As Boolean=True
Try
    localDB.Initialize(File.DirDefaultExternal, "test.html", False)
    localCursor = localDB.ExecQuery("SELECT ID FROM table1")
    localCursor.Close
Catch
    isValid=False
End Try

Essentially this code tries to open the file, checks if there is an ID column
and if not, the file is considered invalid.
So far so good! The bad thing is, if it's not a database file like
in the code above (test.html), the file gets deleted! I guess this should not
happen, should it?

regards,
obscure
 

MaFu

Well-Known Member
Licensed User
Longtime User
If a file is a sqlite database, the first six bytes of the file contains the string "SQLite". Therefore you should open the file for read, read the first six bytes and compare.
 
Upvote 0

mc73

Well-Known Member
Licensed User
Longtime User
Create a copy of the file, then after checks, use this copy if valid.
 
Upvote 0

obscure

Member
Licensed User
Longtime User
Thanks for your replies guys!

The users are able to browse for the backup file on
their device. So I can't simply give it another filename
Erel. (You know, there's always a dumb user who selects
an unsupported file.)

Actually, at the moment I'm doing something similar mc73.
I'm making a duplicate of the file to be checked and move
it back if it's invalid.

Mafu, your idea sounds best. I didn't think of the file
header.

Thanks again. You rock!

Cheers,
obscure
 
Upvote 0
Top