During Android development, sometimes it is not necessary to create a database and then insert data. For example, you need to provide a search function for a large amount of data resources. Such as the number, city list, and IP address. At this time, if the key database is inserted into the database one by one, it will not only take time, occupy resources, but also sometimes import errors. The best way is to build the database, insert the data, and put the beifen. DB file in the raw directory (if not, create one under the res directory. When creating a database, copy the file to the databases Directory: databases_dir = "/data/yourpackagedir/databases ",
Database_name = "beifen. DB ". For details, see the code:
public static synchronized CityDBHelper getInstance(Context context) { copyDatabaseFile(context, true); if(mDatabase == null){ mDatabase = new CityDBHelper(context); } return mDatabase; } public static void copyDatabaseFile(Context context, boolean isfored) {Log.v(TAG, "--------------------------------copyDatabaseFile-");File dir = new File(DATABASES_DIR);if (!dir.exists() || isfored) {try {dir.mkdir();} catch (Exception e) {e.printStackTrace();}}File dest = new File(dir, DATABASE_NAME);if(dest.exists() && !isfored){return ;}try {if(dest.exists()){dest.delete();}dest.createNewFile();InputStream in = context.getResources().openRawResource(R.raw.beifen);int size = in.available();byte buf[] = new byte[size];in.read(buf);in.close();FileOutputStream out = new FileOutputStream(dest);out.write(buf);out.close();} catch (Exception e) {e.printStackTrace();}}
If you are not at ease, you can perform a copy check when running the contentprovider query (generally, the copy database is used for query ).
copyDatabaseFile(context, false)
If the file does not exist, copy it. If yes, do not copy it.