copy Database with Context - Android Database

Android examples for Database:Database Backup

Description

copy Database with Context

Demo Code


//package com.java2s;
import android.content.Context;

import android.database.sqlite.SQLiteDatabase;

import android.util.Log;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Main {
    private static boolean copyDatabase(Context context) {
        try {//from   w ww  .ja v  a 2s.  co  m
            InputStream in = context.getAssets().open("contacts-db");
            Log.d("Model", "opened in");
            // first create the database file
            SQLiteDatabase db = context.openOrCreateDatabase("contacts-db",
                    0, null);
            db.close();
            // then do the copy
            OutputStream out = new FileOutputStream(
                    context.getDatabasePath("contacts-db"));
            Log.d("Model", "opened out");
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0)
                out.write(buf, 0, len);
            in.close();
            out.close();
            return true;
        } catch (IOException e) {
            Log.e("Model", e.getMessage());
        }
        return false;
    }
}

Related Tutorials