1. Dbmanager Code
1 Packagecom.zyh.zyhimportdatabase;2 3 ImportJava.io.File;4 ImportJava.io.FileOutputStream;5 ImportJava.io.InputStream;6 7 ImportAndroid.content.Context;8 Importandroid.database.sqlite.SQLiteDatabase;9 Importandroid.os.Environment;Ten One Public classDbManager { A Private Static Final intBuffer_size = 1024; - Private Static FinalString db_name = "Person2.db"; - Private Static FinalString package_name = "Com.zyh.zyhimportdatabase"; the Private Static FinalString Db_path = "/data" + -Environment.getdatadirectory (). GetAbsolutePath () + "/" +package_name; - - Privatesqlitedatabase database; + Privatecontext context; - + PublicDbManager (Context context) { A This. Context =context; at } - - Public voidOpenDatabase () { - This. Database = This. OpenDatabase (Db_path + "/" +db_name); - } - in Privatesqlitedatabase OpenDatabase (String dbfile) { - Try { toFile Db_file =NewFile (dbfile); + if(!db_file.exists ()) { -InputStream is = This. Context.getresources (). Openrawresource (R.raw.person2); theFileOutputStream fos =NewFileOutputStream (dbfile); * byte[] buffer =New byte[buffer_size]; $ intLen = 0;Panax Notoginseng while(len = is.read (buffer)) > 0){ -Fos.write (buffer, 0, Len); the } + fos.close (); A is.close (); the } + -Sqlitedatabase db = Sqlitedatabase.openorcreatedatabase (Db_file,NULL); $ returndb; $}Catch(Exception e) { - //TODO auto-generated Catch block - e.printstacktrace (); the } - return NULL;Wuyi } the - Publicsqlitedatabase Getdb () { Wu return This. Database; - } About $ Public voidcloseDatabase () { - This. Database.close (); - } -}
2. Activity Code
1 Packagecom.zyh.zyhimportdatabase;2 3 ImportAndroid.os.Bundle;4 Importandroid.os.Environment;5 ImportAndroid.util.Log;6 Importandroid.app.Activity;7 Importandroid.database.sqlite.SQLiteDatabase;8 9 Public classMainactivityextendsActivity {Ten One @Override A protected voidonCreate (Bundle savedinstancestate) { - Super. OnCreate (savedinstancestate); - Setcontentview (r.layout.activity_main); the - //log.i ("Zyh", Environment.getdatadirectory (). GetAbsolutePath ()); -DbManager DBHelper =NewDbManager (Getapplicationcontext ()); - dbhelper.opendatabase (); +Sqlitedatabase db =Dbhelper.getdb (); - System.out.println (Db.isreadonly ()); + dbhelper.closedatabase (); A at } - -}
Reference to the above code: http://www.cnblogs.com/xiaowenji/archive/2011/01/03/1925014.html
Note: A, about the Getreadabledatabase () misunderstanding: You can refer to http://blog.csdn.net/liuhe688/article/details/6715983/and/HTTP Blog.chinaunix.net/uid-22816738-id-3802353.html
B, on the use of multi-threaded db, the correct method can be consulted: http://blog.csdn.net/sky_monkey/article/details/23820021
Where to put the database file in raw, how to open it in the application