Copy Database

- This code is use for copy application database to sdcard.
- This solution is use when you are testing android app in mobile.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileUtility
{
    // Status reply 1 when file copy successfully
    // Status reply 0 when file copy unsuccessfully
    private static int status = 0;
   
    // copyFile() pass source and destination as argumenr.
    public static int copyFile(File src, File dst) throws IOException
    {
        try
        {
            InputStream in = new FileInputStream(src);
            OutputStream out = new FileOutputStream(dst);

            // Transfer bytes from in to out
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0)
            {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
            status = 1;
        }
        catch (Exception ex)
        {
            status = 0;
        }
        return status;
    }
   
    // Use this method in where you wont to use
    public void backupDatabase()
    {
        int status = 0;
        File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();
        if (sd.canWrite())
        {
            // Change current DB path as per your requirement.
            String currentDBPath = "/data/com.demo.packagename/databases/database_name.db";
            // Change current DB path as per your requirement.
            String backupDBPath = "databse_copy.db";
            File currentDB = new File(data, currentDBPath);
            File backupDB = new File(sd, backupDBPath);
            if (currentDB.exists())
            {
                try
                {
                    status = FileUtility.copyFile(currentDB, backupDB);
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
        if(status == 1)
        {}
        else if(status == 0)
        {}
    }
}

Comments

Popular posts from this blog

Android - Set cursor drawable programmatically

Create custom button in android

Android - Shared Preferences Tutorial