Xamarin: extract android sqlite to a local folder on the device

Dear all,
I need to export my android sqlite database to a folder on my memory so I can get access to it outside my mobile.
example of use : " I need to take a backup of my database and see what does it contain."
I searched the web and did not found any Xamarin method that works .
anyone have an idea about how to do this?

Tagged:

Best Answer

Answers

  • ChristopheBERNARDChristopheBERNARD BEMember ✭✭✭✭

    Hello @chahid ,

    i'm not an expert but sql lite it's a file why you don't TRY to use copy
    File.Copy("your path and name of your db DB", "your BACK UP file DB", true);

    have a nice day

  • xamarinChaxamarinCha LBMember ✭✭

    I tried this method :
    private void extractdatabase() { string SAMPLE_DB_NAME = this.GetDatabasePath("SM_Database.db3").ToString(); File sd = Android.OS.Environment.ExternalStorageDirectory; File data = Android.OS.Environment.DataDirectory; FileChannel source = null; FileChannel destination = null; String currentDBPath = SAMPLE_DB_NAME; String backupDBPath = SAMPLE_DB_NAME; File currentDB = new File(data, currentDBPath); File backupDB = new File(sd, backupDBPath); try { source = new FileInputStream(currentDB).Channel; destination = new FileOutputStream(backupDB).Channel; destination.TransferFrom(source, 0, source.Size()); source.Close(); destination.Close(); Toast.MakeText(this, "DB Exported!", ToastLength.Short).Show(); } catch (IOException e) { e.PrintStackTrace(); } }

    but it gives error on "source = new FileInputStream(currentDB).Channel;" invalid path.
    so I don't know maybe I am missing something about the right path to my database.

  • ChristopheBERNARDChristopheBERNARD BEMember ✭✭✭✭

    Hello @chahib

    `
    public static bool CopyDatabase()
    {
    //initiale DB
    string path = @/storage/emulated/0/DYNAMIC_LAYOUT/DB/;
    string dbName = "db_DynamicLayout.db";

            //back up db info
            string backupDBPath = @"/storage/emulated/0/CHBAppTesting/";
            string dbBackUpName = "db_backUp.db";
    
            //
            bool bOk = false;
    
            try
            {
                //
                Java.IO.File currentDB = new Java.IO.File(path, dbName);
                Java.IO.File backupDB = new Java.IO.File(backupDBPath, dbBackUpName);
    
                //
                if (!backupDB.Exists())
                    backupDB.CreateNewFile();
    
                //
                Java.Nio.Channels.FileChannel src = new Java.IO.FileInputStream(currentDB).Channel;
                Java.Nio.Channels.FileChannel dst = new Java.IO.FileOutputStream(backupDB).Channel;
    
                //
                dst.TransferFrom(src, 0, src.Size());
    
                //
                src.Close();
                dst.Close();
            }
            catch (SQLiteException e)
            {
                //
                Log.Error("CopyDatabase", e.Message);
                Log.Error("CopyDatabase", e.ToString());
            }
    
            //
            return bOk;
        }
    

    `

    i've try this code and it's works => it's just a sample but i can copy the database to an other folder and all datas inside the initialize database has been well transfer too ...

    hope this help

  • xamarinChaxamarinCha LBMember ✭✭

    ty @ChristopheBERNARD for your reply.
    but I still have a Java.IO.IOException: open failed: ENOENT (No such file or directory) error when I use backupDB.CreateNewFile();
    I am not being able to find my database on the device maybe the path is wrong or I am missing some permission or something else.

  • ChristopheBERNARDChristopheBERNARD BEMember ✭✭✭✭

    @chahid i think as you mentioned your path is not correct..
    browse to your device and see where is your database ...

    this method i copy paste work well for me :)

    have a nice day

  • DiogoLeaoDiogoLeao USMember ✭✭

    public class Foo { public static void CopyDatabase(Context context, string databaseName) { var bytes = System.IO.File.ReadAllBytes(context.GetDatabasePath(databaseName).AbsolutePath); var fileCopyName = string.Format("/sdcard/Database_{0:dd-MM-yyyy_HH-mm-ss-tt}.db", System.DateTime.Now); System.IO.File.WriteAllBytes(fileCopyName, bytes); } }

  • xamarinChaxamarinCha LBMember ✭✭

    Hi @DiogoLeao Thank you for your reply and sorry for the late reply.
    I tried your method but I am getting System.IO.DirectoryNotFoundException: Could not find a part of the path "/data/data/com.aims.socratemobile/databases/SM_Database.db3".
    My database name is "SM_Database.db3".
    can you provide me the code to create the database maybe my problem is in the creation part.
    here is my creation code:

    using Android.App;
    using SQLite;
    using System;
    using System.IO;
    namespace SocrateMobile.DataBase
    {
        class DatabaseClass
        {
            private static string dbPath = Path.Combine( System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal),"SM_Database.db3");
    
            public string GetDBPath()
            {
                return dbPath;
            }
    
            private SQLiteConnection SQLConn = new SQLiteConnection(dbPath);
            public SQLiteConnection getSqlConnection()
            {
                return SQLConn;
            }
    
            public void CreateDatabase()
            {
                SQLConn.CreateTable<AllocatedAmountsTB>();
                SQLConn.CreateTable<TempAnalysisTB>();
            }
        }
    }
    
  • xamarinChaxamarinCha LBMember ✭✭

    Thank you @DiogoLeao this works for me .

  • SuchithSuchith INMember ✭✭

    You can copy the DB file to device Download folder and from there you can access it. For more details you can check here: http://www.appliedcodelog.com/2017/07/how-to-fetch-android-sqlite-db-file.html

  • @xamarinCha
    did you got it "/data/data/com.aims.socratemobile/databases/SM_Database.db3".?
    I'm facing same problem unable to see my created db on device path.

    please suugest if you got answer.

    Thanks in Advance

Sign In or Register to comment.