In development, it is sometimes necessary to use the DB file database, so it is necessary to import it into the project and then write it to the application's DB file for use.
The code is simple and can be used directly.
It takes two steps to use:
1. Create the raw file and import the db file as follows:
2. Code
public class Dbopenhelper {private final int buffer_size = 400000;public static final String db_name = "idiom.db";//number of saved According to the library file name public static final String package_name = "Cn.edu.bzu.happy";//Application Package name public static final String db_path = "/data" + En Vironment.getdatadirectory (). GetAbsolutePath () + "/" + package_name+ "/databases"; The location of the database in the phone//sdcard path (not good in Android 4.4, the file was successfully created on the phone)//public static final String Db_path = Environment.getexternalstoragedirectory (). GetAbsolutePath () + "/idiom";p rivate Context context;public DBOpenHelper ( Context context) {This.context = context;} Public Sqlitedatabase OpenDatabase () {try {file Mydatapath = new File (Db_path); if (!mydatapath.exists ()) { Mydatapath.mkdirs ();//If you do not have this directory, create}string dbfile=mydatapath+ "/" +db_name;if (! New file (DBFile). Exists ())) {//Determine if the database file exists or import if it does not exist, or open the database directly inputstream is = Context.getresources (). Openrawresource (R.RAW.IDIOM); Database to import fileoutputstream fos = new FileOutputStream (dbfile); byte[] buffer = new Byte[buffer_size];int Count = 0;while ((count = is.read (buffer)) > 0) {fos.write (buffer, 0, count);} Fos.close (); Is.close ();} Sqlitedatabase db = Sqlitedatabase.openorcreatedatabase (dbfile,null); return db;} catch (FileNotFoundException e) {log.e ("Database", "File not Found"); E.printstacktrace ();} catch (IOException e) {LOG.E ( "Database", "IO exception"); E.printstacktrace ();} return null;}}
Use:
public class Testdao {private Dbopenhelper dbhelper;public Testdao (context context) {DBHelper = new Dbopenhelper (context) ;} Public list<test> getalltests () {list<test> animals = new arraylist<test> (); Sqlitedatabase sqlitedatabase = Dbhelper.opendatabase (); cursor cursor = sqlitedatabase.rawquery ("SELECT * from Test", null); while (Cursor.movetonext ()) {//Get Your Data}}}
Testdao test = new Testdao (); test.getalltests ();
Use of the SQLite database (db file) for Android development