In development, it is sometimes necessary to use the DB file database. Therefore, it is necessary to import it into the project, and then write its usage program to the application's DB file for use.
The code is very easy. can be used directly.
There are two steps required to use:
1. Create the raw file. Import the DB file. For example, the following:
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";//Applied Package name public static final String db_path = "/data" + E Nvironment.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 folder, create}string dbfile=mydatapath+ "/" +db_name;if (! New file (DBFile). Exists ())) {//infer that the database file exists, run the 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