Search code examples
unity-game-engineunityscript

ApplicationData.persistentDataPath Unity Editor to Android


Does anyone know, where do I have to place a file (sqlite file) in the unity project directory structure, in order to, after apk compilation and installation the file remains stored in the persistentDataPath at Android side?

Thanks in advance!


Solution

  • Directly inside Assets folder, create a folder with name "StreamingAssets" and put your sqlite database file in this folder then use the following code to extract and copy the sqlite database to persistentDataPath:

    void InitSqliteFile (string dbName)
    {
        // dbName = "example.sqlite";
        pathDB = System.IO.Path.Combine (Application.persistentDataPath, dbName);
        //original path
        string sourcePath = System.IO.Path.Combine (Application.streamingAssetsPath, dbName);
    
        //if DB does not exist in persistent data folder (folder "Documents" on iOS) or source DB is newer then copy it
        if (!System.IO.File.Exists (pathDB) || (System.IO.File.GetLastWriteTimeUtc(sourcePath) > System.IO.File.GetLastWriteTimeUtc(pathDB))) {
    
            if (sourcePath.Contains ("://")) {
                // Android  
                WWW www = new WWW (sourcePath);
                // Wait for download to complete - not pretty at all but easy hack for now 
                // and it would not take long since the data is on the local device.
                while (!www.isDone) {;}
    
                if (String.IsNullOrEmpty(www.error)) {                  
                    System.IO.File.WriteAllBytes(pathDB, www.bytes);
                } else {
                    CanExQuery = false;                                     
                }   
    
            } else {
                // Mac, Windows, Iphone
    
                //validate the existens of the DB in the original folder (folder "streamingAssets")
                if (System.IO.File.Exists (sourcePath)) {
    
                    //copy file - alle systems except Android
                    System.IO.File.Copy (sourcePath, pathDB, true);
    
                } else {
                    CanExQuery = false;
                    Debug.Log ("ERROR: the file DB named " + dbName + " doesn't exist in the StreamingAssets Folder, please copy it there.");
                }   
    
            }           
    
        }
    }