copy Database - Android Database

Android examples for Database:Database Backup

Description

copy Database

Demo Code


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.util.Log;

public class Main{
    /*w  w  w.  j  a  v  a  2s.  co  m*/
    public static String DATABASE_PATH;
    
    public final static String DB_NAME = "Fly.sqlite";
    
    public static void copyDatabase(Context context) throws IOException {
        if (checkDatabase()) {
            return;
        }

        File dir = new File(DATABASE_PATH);

        if (!dir.exists()) { // 
            dir.mkdirs();
        }

        String databaseFilenames = DATABASE_PATH + DB_NAME;

        FileOutputStream os = new FileOutputStream(databaseFilenames);// 
        InputStream is = FileUtil.getInputStream(context, "db"
                + File.separator + DB_NAME);// 

        byte[] buffer = new byte[8 * 1024];

        int count = 0;

        while ((count = is.read(buffer)) > 0) {
            os.write(buffer, 0, count);
            os.flush();
        }

        is.close();
        os.close();
    }
    
    public static boolean checkDatabase() {
        SQLiteDatabase db = null;

        try {
            String databaseFilename = DATABASE_PATH + DB_NAME;
            db = SQLiteDatabase.openDatabase(databaseFilename, null,
                    SQLiteDatabase.OPEN_READWRITE);
            db.rawQuery("select count(1) from Flyfight", null);
        } catch (SQLiteException e) {
            db = null;
        }

        if (db != null) {
            db.close();
        }

        boolean exists = ((db != null)  true : false);

        return exists;
    }
}

Related Tutorials