1、DbManager代码
1 package com.zyh.zyhimportdatabase; 2 3 import java.io.File; 4 import java.io.FileOutputStream; 5 import java.io.InputStream; 6 7 import android.content.Context; 8 import android.database.sqlite.SQLiteDatabase; 9 import android.os.Environment; 10 11 public class DbManager { 12 private static final int BUFFER_SIZE = 1024; 13 private static final String DB_NAME = "person2.db"; 14 private static final String PACKAGE_NAME = "com.zyh.zyhimportdatabase"; 15 private static final String DB_PATH = "/data" + 16 Environment.getDataDirectory().getAbsolutePath() + "/" + PACKAGE_NAME; 17 18 private SQLiteDatabase database; 19 private Context context; 20 21 public DbManager(Context context){ 22 this.context = context; 23 } 24 25 public void openDatabase(){ 26 this.database = this.openDatabase(DB_PATH + "/" + DB_NAME); 27 } 28 29 private SQLiteDatabase openDatabase(String dbFile) { 30 try { 31 File db_file = new File(dbFile); 32 if(!db_file.exists()){ 33 InputStream is = this.context.getResources().openRawResource(R.raw.person2); 34 FileOutputStream fos = new FileOutputStream(dbFile); 35 byte[] buffer = new byte[BUFFER_SIZE]; 36 int len = 0; 37 while((len = is.read(buffer)) > 0){ 38 fos.write(buffer, 0, len); 39 } 40 fos.close(); 41 is.close(); 42 } 43 44 SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(db_file, null); 45 return db; 46 } catch (Exception e) { 47 // TODO Auto-generated catch block 48 e.printStackTrace(); 49 } 50 return null; 51 } 52 53 public SQLiteDatabase getDb(){ 54 return this.database; 55 } 56 57 public void closeDatabase(){ 58 this.database.close(); 59 } 60 }
2、activity代码
1 package com.zyh.zyhimportdatabase; 2 3 import android.os.Bundle; 4 import android.os.Environment; 5 import android.util.Log; 6 import android.app.Activity; 7 import android.database.sqlite.SQLiteDatabase; 8 9 public class MainActivity extends Activity { 10 11 @Override 12 protected void onCreate(Bundle savedInstanceState) { 13 super.onCreate(savedInstanceState); 14 setContentView(R.layout.activity_main); 15 16 //Log.i("zyh", Environment.getDataDirectory().getAbsolutePath()); 17 DbManager dbHelper = new DbManager(getApplicationContext()); 18 dbHelper.openDatabase(); 19 SQLiteDatabase db = dbHelper.getDb(); 20 System.out.println(db.isReadOnly()); 21 dbHelper.closeDatabase(); 22 23 } 24 25 }
上述代码的参考:http://www.cnblogs.com/xiaowenji/archive/2011/01/03/1925014.html
注意:A、关于对getReadableDatabase()的误区:可以参考http://blog.csdn.net/liuhe688/article/details/6715983/和http://blog.chinaunix.net/uid-22816738-id-3802353.html
B、关于多线程对db的使用,正确的方法可以参考:http://blog.csdn.net/sky_monkey/article/details/23820021