How to create a third-party database for Android software development and how to read a database from a file (34)

Source: Internet
Author: User

How to create a third-party database for Android software development and how to read a database from a file



Original by Yu Song MomoArticleIf you reprint it, please note: Reprinted to my independent domain name blogYusong Momo program Research Institute, Original address: http://www.xuanyusong.com/archives/199



I haven't updated my blog on the android development series for a long time. I don't know if everyone can still remember my old friend, hey. In fact, during this period of time, I have never been idle about Android development. The game and software development Momo of Android + IOS + unity are both running at the same time, and the awesome life will continue here. I hope that I will have the opportunity to try to develop some games or software under WP7 in a short time.




Why create a third-party database in Android software development? In the Program , you can obtain data in two ways: Local retrieval and server retrieval. If the data in the project is huge and cannot be obtained online, you need to create a third-party database. I used a more practical example to explain this to you. Recently, I have created a demo for querying call locations, the requirement of the product is that the recipient can call the phone number of the recipient on the screen. Android provides a method for obtaining the number of locations through the Internet, but I have not used this method to obtain the number of locations. Because the time for obtaining the number from the Internet cannot be controlled, it is possible that the user can obtain the number only after the phone data is connected, so the meaning of the incoming call does not exist. In addition, the online data acquisition method must be in the case of a network, so there are too many restrictions, so I gave up the online method of obtaining the mobile phone number from the home location.

Then I found the original database resource of the mobile phone number home location in on the Internet. It uses a TXT file containing the numbers of all provinces and cities in China, as shown in. The rule is to take the first six digits of the phone number to determine the location where the phone number is located. The original resources of the home database include mobile numbers and Unicom numbers. A total of 61 text files are added. We need to write the program. All the data needs to be written into the database, and then the generated database files should be put into the new job to be queried.ThisThe reason is that the volume of data in the local database is large, and it takes at least 20 minutes to write data to the database in the query project. This will cause the user to have not finished writing your database when the first phone call comes in after installing the software, and the user experience will be greatly compromised. Therefore, we need to first create this huge database in a third-party program, then put it into the software, and then directly operate the database.




The data in is indeed a little old, but the focus of this blog is not to discuss mobile phone number locations. My final idea is to place the. DB file on the server to maintain the DB file. The user downloaded the database file from the server during the first installation, which is a little far away. Next we will learn how to write the huge raw data in the local database into the database. First, we need to create a database program. As shown in, after clicking the "start to read resources and write data to the database" button, the program cyclically starts to read all the original resources locally, extract the required value and write it into the local database.



The corresponding activity is generatedbactivity,CodeAs follows:

Import Java. io. bufferedreader; import Java. io. ioexception; import Java. io. inputstream; import Java. io. inputstreamreader; import Java. io. unsupportedencodingexception; import android. app. activity; import android. content. res. resources; import android. content. res. resources. notfoundexception; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. util. log; import android. view. View; import android. view. view. onclicklistener; import android. widget. button; import android. widget. textview; import android. widget. toast; public class generatedbactivity extends activity {// dB object public dbhelper m_db = NULL; // The Public button Button Object public button = NULL; // The Text object public textview textnumber = NULL; public textview textcity = NULL; Public textview textlocation = NULL; // value passed in the receiving thread, used to refresh uihandler handler = new Handler () {// annotation 3 @ overridepublic void handlemessage (Message MSG) {bundle = MSG. getdata (); // obtain the number, city, and provincial string number = bundle. getstring ("Number"); string city = bundle. getstring ("city"); string location = bundle. getstring ("location"); // update uitextnumber. settext (number); textcity. settext (city); textlocation. settext (location); super. handlemessage (MSG) ;}}; @ overridepublic void oncreate (bundle savedin Stancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); // obtain the dbhelper object m_db = dbhelper. getinstance (this); // get the button object button = (button) This. findviewbyid (R. id. button); button. settext ("start to read resources and write them to the Database"); // obtain the Text object textnumber = (textview) This. findviewbyid (R. id. number); textcity = (textview) This. findviewbyid (R. id. city); textlocation = (textview) This. findviewbyid (R. id. location); // start to read the resource button. se Tonclicklistener (New onclicklistener () {@ overridepublic void onclick (view v) {// Note 1 // start the thread to read the resource and write it into the database. New thread () {@ overridepublic void run () {int COUNT = dbhelper. locations. length; For (INT I = 0; I <count; I ++) {loadlocationfile (I );}}}. start () ;}}) ;}private void loadlocationfile (INT resourceid) {// annotation 2 resources res = This. getresources (); inputstream in = NULL; bufferedreader BR = NULL; try {In = res. openr Awresource (R. raw. location_a0 + resourceid); string STR; BR = new bufferedreader (New inputstreamreader (in, "GBK"); While (STR = BR. readline ())! = NULL) {// The feature value of the mobile phone number is the first seven string numbers = Str. substring (0, 6); // The number of the mobile phone number starting from the second digit to the last string city = Str. substring (24, str. length (); // write data to the database m_db.insert (dbhelper. table_name, new string [] {dbhelper. number, dbhelper. city, dbhelper. location}, new string [] {number, city, dbhelper. locations [resourceid]}); message MSG = new message (); bundle = new bundle (); bundle. putstring ("Number", "mobile phone number feature data:" + number ); Bundle. putstring ("city", "mobile phone number:" + city); bundle. putstring ("location", "Provincial mobile phone number OPERATOR:" + dbhelper. locations [resourceid]); MSG. setdata (bundle); handler. sendmessage (MSG); log. V ("xuanyusong", "mobile phone number feature data:" + number + "mobile phone number City:" + city + "mobile phone number provincial carrier:" + dbhelper. locations [resourceid]);} catch (notfoundexception e) {toast. maketext (this, "the text file does not exist.", 100 ). show (); E. printstacktrace ();} catch (unsupportedenco Dingexception e) {toast. maketext (this, "text encoding exception", 100 ). show (); E. printstacktrace ();} catch (ioexception e) {toast. maketext (this, "file read error", 100 ). show (); E. printstacktrace ();} finally {try {If (in! = NULL) {in. Close () ;}if (BR! = NULL) {Br. Close () ;}} catch (ioexception e) {e. printstacktrace ();}}}}

Note 1: After you click the "Read and Write Database" button in the window, the program starts a thread to read resources, and the Code must be read in the thread because the data volume is large, ANR may occur when reading data in the main thread. Dbhelper. Locations. Length indicates the number of original data resource files. Here, all original resource files are read through loops.

Note 2: The loadlocationfile () method starts to read the local Original Resources. All the original resources are stored in RES/raw and the stream object of each original file is obtained using the openrawresource () method. Then, in the while loop, call the BR. Readline () method to read the data in the Text object row by row. After the data is read, it is written into the database. Because this is a thread, handler must be used to refresh the UI.

NOTE 3: each database inserted in the database sends a message using handler. Obtain the parameters attached to the message here, and refresh the UI to bring the data to reality on the screen.

The database creation and data insertion methods are written in the dbhelper class. The Code is as follows:

Package com.m15.cn; import android. content. contentvalues; import android. content. context; import android. database. SQLite. sqlitedatabase; import android. database. SQLite. sqliteopenhelper; public class dbhelper extends sqliteopenhelper {public static dbhelper minstance = NULL;/** database name **/public static final string database_name = "location. DB ";/** database version **/Private Static final int database_version = 1;/** dB object **/sqlitedatabase MDB = NULL; Context mcontext = NULL; // initialize public final static string table_name = "location_date"; public final static string id = "_ id"; public final static string number = "Number "; public final static string location = "location"; public final static string city = "city"; // index idpublic final static int id_index = 0; public final static int number_index = 1; public final static int location_index = 2; public final static int city_index = 3; /** create an external table using a database SQL statement **/public static final string name_table_create = "CREATE TABLE location_date (" + "_ id integer primary key autoincrement, "+" number text not null, "+" city text not null, "+" location text not null );"; public final static string [] Locations = {"Shanghai Mobile", "Shanghai Unicom", "Yunnan mobile", "Yunnan Unicom", "Inner Mongolia Mobile", "Inner Mongolia Unicom ", "Beijing Mobile", "Beijing Unicom", "Jilin mobile", "Jilin Unicom", "Sichuan Mobile", "Sichuan UNICOM", "Tianjin mobile", "Tianjin Unicom ", "Ningxia mobile", "Ningxia Unicom", "Anhui mobile", "Anhui Unicom", "Shandong mobile", "Shandong Unicom", "Shanxi Mobile", "Shanxi Unicom ", "Guangdong mobile", "Guangdong Unicom", "Guangxi mobile", "Guangxi Unicom", "Xinjiang mobile", "Xinjiang Unicom", "Jiangsu mobile", "Jiangsu Unicom ", "Jiangxi mobile", "Jiangxi Unicom", "HEBEI mobile", "HEBEI Unicom", "Henan mobile", "Henan Unicom", "Zhejiang mobile", "Zhejiang Unicom ", "Hainan mobile", "Hainan Unicom", "Hubei mobile", "Hubei Unicom", "Hunan Mobile", "Hunan Unicom", "Gansu mobile", "Gansu Unicom ", "Fujian Mobile", "Fujian Unicom", "Tibet Mobile", "Tibet Unicom", "Guizhou mobile", "Guizhou Unicom", "Liaoning mobile", "Liaoning Unicom ", "Chongqing Mobile", "Chongqing Unicom", "Shaanxi Mobile", "Shaanxi Unicom", "Qinghai mobile", "Qinghai Unicom", "Heilongjiang mobile ", "Heilongjiang Unicom"};/** Singleton mode **/public static synchronized dbhelper getinstance (context) {If (minstance = NULL) {minstance = new dbhelper (context);} return minstance;} public dbhelper (context) {super (context, database_name, null, database_version ); // obtain the database object MDB = getreadabledatabase (); mcontext = context ;}@ overridepublic void oncreate (sqlitedatabase dB) {// create the data database db.exe csql (name_table_create );} @ overridepublic void onupgrade (sqlitedatabase dB, int oldversion, int newversion) {}/*** insert a data record ** @ Param key * @ Param date */Public void insert (string tablename, string key [], string date []) {contentvalues values = new contentvalues (); For (INT I = 0; I <key. length; I ++) {values. put (Key [I], date [I]);} MDB. insert (tablename, null, values );}}

After the database is written, copy the generated database from the program to the local device. Copy the location. DB file of this program to your computer, as shown in.





Then you can use the database to view the software to view the generated database. Because I am using MAC for development, it is a little different from the previously written database viewing software. As shown in, the local data has been written into the database. The following describes the meaning of the field: _ id is unique in ascending order, and number indicates the first 6 fields of the number, city indicates the city where the number is located, and location indicates the province-level carrier's location. In this step, our third-party database files have been created. If a friend asks if he can use a database generated by a non-android program, I suggest you do not use it. Or you can add the system-generated tables android_metadata and sqlite_sequence to your database for a try, because the database must have the same structure as the database generated by Android. Otherwise, some Android phones cannot open the object of its dB file.





Then create a new Android project for us to query the database. First, copy the location. DB file generated in the above project to the raw folder of the new project. Start to load the content in the database in the following code.


Import Java. io. file; import Java. io. fileoutputstream; import Java. io. inputstream; import android. app. activity; import android. content. context; import android. database. cursor; import android. database. SQLite. sqlitedatabase; import android. OS. bundle; import android. view. view; import android. view. view. onclicklistener; import android. widget. button; import android. widget. edittext; import android. widget. textview; impo RT android. widget. toast; public class getinfoactivity extends activity {// file path public final static string url = "/data/CN. location. xys/Files "; // database file public final static string db_file_name =" location. DB "; // public final static string table_name =" location_date "; // index idpublic final static int id_index = 0; public final static int number_index = 1; public final static int location_index = 2; Pu BLIC final static int city_index = 3; edittext = NULL; button = NULL; textview = NULL; sqlitedatabase DB = NULL; @ overrideprotected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. getinfo); // first copy the DB file to the program memory. // annotation 1if (copydb () {// obtain the database file = new file (URL, db_file_name ); DB = sqlitedatabase. openorcreatedatabase (file, null ); Edittext = (edittext) This. findviewbyid (R. id. edit); textview = (textview) This. findviewbyid (R. id. location); button = (button) This. findviewbyid (R. id. button); button. setonclicklistener (New onclicklistener () {public void onclick (view v) {string editstr = edittext. gettext (). tostring (); If (editstr. length () = 11) {// enter the mobile phone number cursor = dB. query ("location_date", null, "Number =? ", New string [] {editstr. substring (0, 6)}, null); If (cursor! = NULL & cursor. movetofirst () {// obtain the number string text = cursor from the provincial and municipal regions. getstring (location_index) + cursor. getstring (city_index); textview. settext (text);} else {toast. maketext (getapplicationcontext (), "your mobile phone number cannot be queried in the Database", toast. length_short ). show () ;}} else {toast. maketext (getapplicationcontext (), "the mobile phone number is 11 bits, re-enter", toast. length_short ). show () ;}}) ;}}// copy the database file in the raw file to the program memory in the mobile phone. Public Boolean copydb () {try {// judge Is there any copied file in the program memory if (! (New file (URL )). exists () {inputstream is = getresources (). openrawresource (R. raw. location); fileoutputstream Fos = This. openfileoutput (db_file_name, context. mode_world_readable); // buffer size of one copy: 1 Mbyte [] buffer = new byte [1024*1024]; int COUNT = 0; // copy the database file while (COUNT = is. read (buffer)> 0) {FOS. write (buffer, 0, count);} FOS. close (); is. close ();} return true;} catch (exception e) {e. printstacktrace (); Return false ;}}}

Note 1: first copy the database files in the raw folder to the program memory, and then obtain the objects of the database files through the copied path. With database objects, you can perform addition, deletion, modification, and query operations. Enter the mobile phone number and click search.





In the end, the old rule is always included in every article.Source codeIn the end, if you still feel that I am not writing enough details, it doesn't matter. I post the source code to welcome everyone to discuss and study Yu Song Momo, hoping to make progress together with everyone.


:Http://www.xuanyusong.com/archives/199

(Content includes the database Generation Program and database query Program)


Related Article

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.