Summary of onCreate execution caused by sqlite's storage location on the mobile phone, sqliteoncreate

Source: Internet
Author: User
Tags try catch

Summary of onCreate execution caused by sqlite's storage location on the mobile phone, sqliteoncreate

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

We all know that in order to operate databases, android generally inherits the SQLiteOpenHelper class and implements its three functions.

As follows:

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(20),content varchar(40),time varchar(20) ,head varchar(20),isCheck byte)");}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}}
</Pre> <p> you can see that a table named lgx_table is created with columns such as id, name, and content. </P> then, in the Activity, use getWritableDatabase or getReadableDatabase () method to instantiate a SQLiteDatabase <p> </p> <pre name = "code" class = "java"> MessageDataBasemessageDataBase = new MessageDataBase (context, "lgx", null, 1); SQLiteDatabase database = messageDataBase. getWritableDatabase ();


We can see that a database named "lgx" is created.


Here is a question. After the above steps, where is the database stored?


The database is stored in data/[your packageName]/databses,

1. If it is a simulatorIn Eclipse, go to this step to see DBMS ---> File Explorer --> data ----> data ---> your packageName


 

I will not describe it here.

2. If it is a real machine,First, the real machine is root. Download a Root Explorer. My testing machine is Huawei honor 3c.

After the preceding steps are completed, you can access data/jz. his. jzhis/databases.

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

Now we know where the database is stored. Do you think this is my purpose to write this blog? Let's continue. Hey, hey.

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

First, I put a ready-made database in res/raw. I will paste it into the SD card of my mobile phone in the code.

See 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 path on your mobile phone */private static String DATABASE_PATH = Environment. getExternalStorageDirectory () + "/aaaaa/";/*** database name */public static final String dbName = "mzk_db"; private SQLiteDatabase mSDB; public static CopyOfCityInfoDataSupport2 get Instance (Context context) {initDataBase (context); if (cityInfoDataSupport = null) {cityInfoDataSupport = new CopyOfCityInfoDataSupport2 ();} return cityInfoDataSupport ;} /*** initial database trial */private static void initDataBase (Context context) {boolean dbExist = checkDataBase (); if (dbExist) {} else {// if not, store raw data to the mobile phone SD card copyDataBase (context) ;}/ *** copy the database to the ** @ throws IOException */private static Void copyDataBase (Context context) {String databaseFilenames = DATABASE_PATH + dbName; File dir = new File (DATABASE_PATH); FileOutputStream OS = null; InputStream is = null; // you can check whether a folder exists, create an if (! Dir. exists () {dir. mkdirs ();} try {// get the output stream of the database OS = new FileOutputStream (databaseFilenames); // get 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, count); OS. flush ();} // the reason why it is not initialized here is because it is a static method, and mSDB is not set to static, it is not recommended to set it to static // mSDB = SQLiteDatabase. openOrCreateDatabase (DATABASE_PATH + // dbName, null);} catch (Exception e) {e. printStackTrace ();} finally {try {OS. close (); is. close ();} catch (IOException e) {e. printStackTrace () ;}}/ *** determines whether the database exists ** @ return */private static boolean checkDataBase () {SQLiteDatabase checkDB = nul L; String databaseFilename = DATABASE_PATH + dbName; // Add the try catch method try {// return 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. falsereturn checkDB = null? False: true;}/*** query information of all provinces ** @ return province information */public ArrayList <City> queryProvince () {// create database instance mSDB = SQLiteDatabase. openOrCreateDatabase (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. getColumnInd Ex ("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 can see that if you write the database to the mobile phone SD card, you do not need the SQLiteOpenHelper class, but directly go through

MSDB = SQLiteDatabase. openOrCreateDatabase (DATABASE_PATH + dbName, null); you can get the database instance.


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

So what should we do if we want to use SQLiteOpenHelper and write it to the SD card.

The following code is incorrect. You only need to check the 51 lines. It is precisely because of the following code that I learned how to execute the onCreate method.

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. SQLiteDatabas E; 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 mobile phone is private static String DATABASE_PATH = Environment. getExternalStorageDire Ctory (). 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 CityInfoDat ASupport (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.exe cSQL (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.exe cSQL (SQL. replace (";", "");} reader. close (); reader = null;} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace () ;}}/*** read database files (. SQL), and execute the SQL statement **/private void executeAssetsSQL (SQLiteDatabase db, String schemaName) {Log. e ("DataSupport", "executeAssetsSQL"); BufferedReader in = null; try {in = new BufferedReader (new InputStreamReader (context. getAss Ets (). open (schemaName); String line; String buffer = ""; while (line = in. readLine ())! = Null) {buffer + = line; if (line. trim (). endsWith (";") {db.exe cSQL (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 +" where 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. setlongpolling (c. getString (c. getColumnIndex ("longtitude"); city. setLatitude (c. getString (c. getC OlumnIndex ("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.exe cSQL (SQL);} public static void initDatabse (Context cntext) {boolean dbExist = checkDataBase (); // write the database in raw to the mobile phone if (! DbExist) {try {copyDataBase (cntext);} catch (IOException e) {throw new Error ("Error copying database ");}}} /*** determine whether 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 the database to the specified folder on the mobile phone * @ throws IOException */public static void copyDataBase (Context context) throws IOException {String databaseFilenames = DATABASE_PATH + dbName; file dir = new File (DATABASE_PATH); FileOutputStream OS = null; // you can create an if (! Dir. exists () {dir. mkdirs ();} try {// get the database file write stream OS = new FileOutputStream (databaseFilenames);} catch (FileNotFoundException e) {e. printStackTrace ();} // obtain the data stream InputStream of the database file 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 ();}}}

Through the above Code, my onCreate method has never been executed. After many experiments, I learned the problem, so I will summarize it here.


So when will the onCreate method be executed?

The onCreate method of SQLiteOpenHelper must be after the getReadableDatabase Method

SQLiteDatabase mSDB = getReadableDatabase () This method first checks whether there is an existing database on the mobile phone. If not, the onCreate method is executed. If yes, no ----> is executed. However, the premise is that the second parameter of your supre (context, DATABASE_PATH + dbName, null, version) cannot be an existing database path.

Here, the second parameter is converted into an existing database file, so the onCreate method will never be executed.


So when super (context, dbName, null, version); the second parameter is correct and the getReadableDatabase method is executed, a database is available in the system memory.


I am suffering from this afternoon.



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.