A summary of where OnCreate is executed by SQLite's storage location on the phone

Source: Internet
Author: User
Tags try catch


Reprint please indicate the source, thank you: http://blog.csdn.net/harryweasley/article/details/46467495

As we all know, Android in order to operate the database, generally inherit the Sqliteopenhelper class, and implement his three functions.

As shown below:

package jz.his.db;import Android.content.context;import Android.database.sqlite.sqlitedatabase;import Android.database.sqlite.sqlitedatabase.cursorfactory;import Android.database.sqlite.sqliteopenhelper;public class Messagedatabase extends Sqliteopenhelper {public Messagedatabase (context context, String name, cursorfactory factory,int version) {Super (context, name, Factory, version) ;} @Overridepublic void OnCreate (Sqlitedatabase db) {db.execsql ("CREATE Table lgx_table (_id integer PRIMARY key AutoIncrement, "+" name varchar (+), content varchar (+), Time varchar ((), head varchar (), Ischeck byte) "); @Overridepublic void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {}} 
</pre><p> can see that a table named Lgx_table is created with a id,name,content column in it. </p><p></p> then instantiate a sqlitedatabase in the activity with the Getwritabledatabase or Getreadabledatabase () method <p></p><p></p><pre name= "code" class= "java" >messagedatabasemessagedatabase = new Messagedatabase (Context, "LGX", NULL, 1); Sqlitedatabase database = Messagedatabase.getwritabledatabase ();


As we can see, a database named "LGX" was created.


Here's a question, where is the database saved after the above steps?


The database is saved in Data/data/[your packagename]/databses,

1. in the case of an emulator, go directly through eclipse and take this step to see the DBMS--->file explorer-->data---->data--->your packagename


Many online introductions, I do not introduce here.

2. If it is a real machine, first This real machine is root, download a root Explorer. My test machine is Huawei Glory 3c.

When we are done with the above steps, we will see such a situation when we enter data/data/jz.his.jzhis/databases/.

In fact LGX is the database we just created, lgx-journal is the database log.

Now that we know where the database is stored, do you think that's what I'm writing this blog for? Keep looking down, hey.

If I don't want to save the database in my phone system memory, but I want to put my database in the SD card of my phone, what should I do?

First of all, I put a ready-made database in the Res/raw, and later in the code, it will be copied into the phone SD card.

Look at the following code:

Package Com.example.province;import Java.io.file;import Java.io.fileoutputstream;import java.io.IOException;import Java.io.inputstream;import Java.util.arraylist;import Android.content.context;import android.database.Cursor; Import Android.database.sqlite.sqlitedatabase;import Android.database.sqlite.sqlitedatabase.cursorfactory;import Android.database.sqlite.sqliteexception;import Android.database.sqlite.sqliteopenhelper;import Android.os.environment;public class CopyOfCityInfoDataSupport2 {private static CopyOfCityInfoDataSupport2 cityinfodatasupport;/** * Database in the phone path */private static String Database_path = Environment.getexternalstoragedirectory () + "/aaaaa/";/** * Database name */public static final String dbName = "mzk_db";p rivate sqlitedatabase msdb;public static COPYOFCI TyInfoDataSupport2 getinstance (Context context) {initdatabase (context); if (cityinfodatasupport = = null) { Cityinfodatasupport = new CopyOfCityInfoDataSupport2 ();} return cityinfodatasupport;} /** * Preliminary database */private static VOID initdatabase (Context context) {Boolean dbexist = Checkdatabase (); if (dbexist) {} else {///if not present, the data in raw is stored in the SD card of the phone Copyda Tabase (context);}} /** * Copy Database to phone specified folder * * @throws ioexception */private static void Copydatabase (context context) {String DatabaseFileName s = Database_path + dbName; File dir = new file (Database_path); FileOutputStream OS = Null;inputstream is = null;//Determines if a folder exists and does not exist to create an if (!dir.exists ()) {dir.mkdirs ();} try {//Gets the output stream of the database OS = new FileOutputStream (databasefilenames);//Gets the input stream of the data file is = Context.getresources (). Openrawresource (r.raw.mzk_db); byte[] buffer = new Byte[8192];int count = 0;while ((count = is.read (buffer))! =-1) {os.write (buffer, 0, C Ount); Os.flush ();} This is not initialized here because this is a static method, and msdb is not set to static, nor is it recommended to be static//msdb = Sqlitedatabase.openorcreatedatabase (Database_path +// DbName, null);} catch (Exception e) {e.printstacktrace ();} finally {try {os.close (); Is.close ();} catch (IOException e) { E.printstacktrace ();}}} /** * Determine if the database exists * * @return */private static Boolean ChecKdatabase () {sqlitedatabase CheckDB = null; String databasefilename = Database_path + dbname;//To add itself to the try catch method try {//returns the latest database CHECKDB = Sqlitedatabase.opendatabase (DatabaseFileName, null,sqlitedatabase.open_readonly);} catch (Sqliteexception e) {//Todo:handle exception}if (CheckDB! = null) {Checkdb.close ();} If CheckDB is null, there is no database, return falsereturn CheckDB = = null? False:true;} /** * Query All provinces information * * @return Province information */public arraylist<city> queryprovince () {//Create an instance of the database msdb = Sqlitedatabase.openorc Reatedatabase (Database_path + dbName, NULL); arraylist<city> list = new arraylist<city> (); String sql = "SELECT * from Fs_province"; cursor cursor = msdb.rawquery (sql, NULL), while (Cursor.movetonext ()) {City city = new City (); String id = cursor.getstring (cursor.getcolumnindex ("Provinceid")); String name = cursor.getstring (Cursor.getcolumnindex ("Provincename")); City.setname (name); City.setid (ID); List.add ( City);} if (cursor! = NULL) {Cursor.close ();} return list;} public void ClosedatabasE () {if (MSDB! = null) {Msdb.close ();}}} 


We see that if the database is written to the phone SD card, there is no need to sqliteopenhelper class, but directly through

MSDB = sqlitedatabase.openorcreatedatabase (Database_path + dbName, null), you can get an instance of the database.


However, this method has a disadvantage, that is, the database can not be upgraded. Obviously this is very bad.

So if we still want to use Sqliteopenhelper, and then write it to the SD card, and how to do it.

The following code is wrong, you just have to look at 51 lines, it is because of the following code, I studied the OnCreate method exactly when to execute.

Package Jz.his.db;import Java.io.bufferedreader;import Java.io.file;import java.io.filenotfoundexception;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.io.InputStreamReader; Import Java.util.arraylist;import java.util.list;import Jz.his.jzhis.r;import Android.content.context;import Android.database.cursor;import Android.database.sqlite.sqlitedatabase;import Android.database.sqlite.sqliteexception;import Android.database.sqlite.sqliteopenhelper;import Android.os.environment;import Android.util.log;public class Cityinfodatasupport extends sqliteopenhelper{private    Final static String TAG = "Cityinfodatasupport";    public static final String dbName = "Cityego"; The path of the database in the phone private static String Database_path = Environment.getexternalstoragedirectory (). GetAbsolutePath () + "/    Com.bcinfo.pwzs/";    private static int version = 1;    Private final String geocoding_table_name = "GEOCODING"; Private Sqlitedatabase MSDB = getreadabledAtabase ();    private static Cityinfodatasupport Mdatasupport;    Context context;                public static Cityinfodatasupport getinstance (context context) {Initdatabse (context);        if (Mdatasupport = = null) {Mdatasupport = new Cityinfodatasupport (context);    } return mdatasupport;    } cityinfodatasupport (Context context) {Super (context, database_path+dbname, NULL, version);    } @Override public void OnCreate (Sqlitedatabase db) {executeassetssql (db, "Geocoding_create.sql"); } @Override public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {String sql = "Drop        Table if exits "+ geocoding_table_name;        Db.execsql (SQL);    OnCreate (DB);        } private void Loadsql (Sqlitedatabase db, String schemaName) {InputStream InputS;            try {InputS = Context.getassets (). open (SchemaName); BufferedReader reader = new BufferedreaDer (New InputStreamReader (InputS));            String sql = null;            while ((sql = Reader.readline ()) = null) {Db.execsql ("Sql.replace ("; "," "));            } reader.close ();        reader = null;        } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); }}/** * Read the database file (. sql) and execute the SQL statement * */private void Executeassetssql (Sqlitedatabase db, String Scheman        AME) {LOG.E ("Datasupport", "Executeassetssql");        BufferedReader in = null;            try {in = new BufferedReader (New InputStreamReader (Context.getassets (). Open (SchemaName)));            String Line;            String buffer = "";                while (line = In.readline ()) = null) {buffer + = line;                if (Line.trim (). EndsWith (";"))                    {Db.execsql (Buffer.replace (";", "")); Buffer= "";        }}} catch (IOException e) {log.e ("Db-error", e.tostring ());            } finally {try {if (in! = null) in.close ();            } catch (IOException e) {log.e ("Db-error", e.tostring ());    }}} public synchronized void Insertcityinfo () {Loadsql (MSDB, "geocoding_data.txt");        } public synchronized list<city> Querydatabyid (string field, String id) {String sql = "";        list<city> citylist = new arraylist<city> ();        if (Field.equals ("grade")) {sql = "select * from" + Geocoding_table_name + "where grade =?"; } else if (Field.equals ("parent")) {sql = "select * from" + Geocoding_table_name + "wher E parent =?        ";        } string[] params = new string[] {ID}; Cursor C = Msdb.rawquery (sql, params);            while (C.movetonext ()) {City city = new City ();            City.setgbcode (C.getstring (C.getcolumnindex ("Gbcode"));            City.setgbname (C.getstring (C.getcolumnindex ("Gbname"));            City.setgrade (C.getstring (C.getcolumnindex ("grade"));            City.setlongitude (C.getstring (C.getcolumnindex ("longtitude"));            City.setlatitude (C.getstring (C.getcolumnindex ("latitude"));            City.setparent (C.getstring (C.getcolumnindex ("parent"));        Citylist.add (city);        } if (c! = null) {c.close ();    } return citylist;        } public void Deleteapptemptraffic () {String sql = ' Delete from ' + geocoding_table_name;    Msdb.execsql (SQL);        public static void Initdatabse (Context cntext) {Boolean dbexist = Checkdatabase (); To determine whether a database exists or not, write the database in raw to the phone if (!dbexist) {try {CopydatabASE (Cntext);            } catch (IOException e) {throw new error ("Error copying database");        }}}/** * Determine if the database exists * @return false or True */public static Boolean checkdatabase () {        Sqlitedatabase CheckDB = null;            try {String databasefilename = Database_path + dbName;        CheckDB = sqlitedatabase.opendatabase (DatabaseFileName, NULL, sqlitedatabase.open_readonly);        } catch (Sqliteexception e) {} if (CheckDB! = null) {checkdb.close (); } return CheckDB! = null?    True:false; /** * Copy Database to phone specified folder * @throws IOException */public static void Copydatabase (context context) throws        IOException {String databasefilenames = Database_path + dbName;        File dir = new file (Database_path);        FileOutputStream OS = null;    Determine if a folder exists and does not exist create a new if (!dir.exists ())    {Dir.mkdirs ();        } try {//Get write stream for database file OS = new FileOutputStream (databasefilenames);        } catch (FileNotFoundException e) {e.printstacktrace ();        }//Get the data stream of the database file InputStream is = Context.getresources (). Openrawresource (R.raw.cityego);        byte[] buffer = new byte[8192];        int count = 0;                try {while ((count = is.read (buffer)) > 0) {os.write (buffer, 0, count);            Os.flush ();            }} catch (IOException e) {} try {is.close ();        Os.close ();        } catch (IOException e) {e.printstacktrace (); }    }}

With this code above, my OnCreate method has not been executed. Finally, after many experiments, I know the problem, so here is a summary.


So when exactly does the OnCreate method execute?

The OnCreate method of Sqliteopenhelper must be after the Getreadabledatabase method.

Sqlitedatabase MSDB = Getreadabledatabase () This method first checks whether there is an existing database in the phone, and if not, executes the OnCreate method, if any, and does not perform----> But here's a premise, Your Supre (context, database_path+dbname, NULL, version), the second parameter cannot be a database path that already exists.

Here I am, the second argument is made into the existing database file, so the OnCreate method will never execute.


So when super (context, dbName, NULL, version), the second parameter is correct and the Getreadabledatabase method is executed, the database is stored in the system.


Tortured me for an afternoon ah ah ah ah.



A summary of where OnCreate is executed by SQLite's storage location on the phone

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.