Hi everybody I just learned some things in the past week about SQLite in Unity3D with Android and I thought I share them as I had to figure out most of it myself. All code in C#.
Set up a database in the android device on runtime
This is pretty easy, if you create a connection to a file that doesn’t exist, it will be created. This is perfect to save data created by your application like scores or savegames. Note that once you created the database, it will stay there until deleted explicilty, so if you created it the first time, you will have to create a table before inserting values.
private IDbConnection dbcon;
...
public void OpenDB(string p)
{
connection = "URI=file:" + Application.persistentDataPath + "/" + p; // we set the connection to our database
//connection = "URI=file:" + p; // like this will NOT work on android
Debug.Log(connection);
dbcon = new SqliteConnection(connection);
dbcon.Open();
}
After this you can populate the database in different ways, I have attached a unitypackage to this post under the name “SQLite” where you can see an example. (note: there are many parts of the code which I took from internet examples)
Load an already populated database in the android device
This is trickier, as Android packs everything into a single file and sends it to the device. This means that if you want to send a file with it, you have to pack it in there and then somehow retrieve the data from the package. This comes in handy when you need a database already filled up with data, like a dictionary or NPC phrases.
The way to do it is to create a folder named “StreamingAssets” in your assets folder. Then place your database inside, and at runtime “stream it” in realtime:
// check if file exists in Application.persistentDataPath
string filepath = Application.persistentDataPath + "/" + p;
if(!File.Exists(filepath))
{
// if it doesn't ->
// open StreamingAssets directory and load the db ->
WWW loadDB = new WWW("jar:file://" + Application.dataPath + "!/assets/" + p); // this is the path to your StreamingAssets in android
while(!loadDB.isDone) {} // CAREFUL here, for safety reasons you shouldn't let this while loop unattended, place a timer and error check
// then save to Application.persistentDataPath
File.WriteAllBytes(filepath, loadDB.bytes);
}
//open db connection
connection = "URI=file:" + filepath;
dbcon = new SqliteConnection(connection);
dbcon.Open();
You have the full code for this example in “SQLiteLoad”
Hope it helps someone. ![]()
P.S. Some users from this forum helped a lot, you can take a look at this conversation for more information: http://forum.unity3d.com/threads/97043-Sqlite-for-Android-help-please
762728–27864–$SQLiteLoad.unitypackage (984 KB)
756768–27623–$SQLite.unitypackage (981 KB)
