Preface
The Android database operations that you usually see usually create an empty database at the beginning of the program, and we are performing related operations. This is easier for us to do because we followed this application from the beginning, so sometimes it is impossible for us to do everything ourselves. What if we need to use a database with existing data? Think about where the database should be stored in the Android system. It would be easier if we knew where the database was stored. Do you have any ideas now? If not, let’s take a look at the detailed introduction below.
The method is as follows
We all know that the Android database is placed under data\data\packageName\datbases\ by default;
To import the existing database, put our database in this directory when the program is first started, and then we can configure the SqliteDabase object and operate it directly.
/** * Copy the database from assets to databases */ private void copyDB() { //data/data/packageName/databases/ File mkdir = new File(getFilesDir().getParent(),"databases"); //Create databases folder if (!()) (); (TAG, "copyDb: mkdir="+()); //Database file File file = new File(mkdir,""); // Just created when the program is first started if(!()){ //Get assets management AssetManager assets = getAssets(); //Execute file copy try { InputStream open = (""); FileOutputStream fos = new FileOutputStream(file); byte[] bs = new byte[1024]; int len ; while ((len = (bs))!=-1){ (bs,0,len); } (); (); (); } catch (IOException e) { (); } } (TAG, "copyDb: exists="+()); }
Summarize
The above is the entire content of this article. I hope the content of this article will be of some help to all Android developers. If you have any questions, you can leave a message to communicate.