Android instance-Mobile security Defender (33)-Import the database into the program

Source: Internet
Author: User

First, the goal

1, in the project introduced Sqlitedatabase database, through the input and output stream to copy the database to the specified path directory;

2, through the Sqlitedatabase OpenDatabase () using the database, through the Rawquery () method to execute the SQL statement;

3, the initial realization of the number attribution to the query function.

Database structure:

DATA1:DATA2:

Database in Project: Query result:

Second, the Code implementation

1. Copy the Telephone attribution database (name address.db) to the Assets folder of the project;

2, in the Project SRC folder New Database Toolkit (named Com.example.mobilesafe.db.dao), under which new tool class (named Numberaddqueryutils);

3. Create a new static method (named Querynumber) with the return value type string in the tool class (Numberaddqueryutils), which needs to pass in the string type parameter number;

4, in the new Method (Querynumber) through the database object Sqlitedatabase OpenDatabase (String path, cursorfactory factory, int flags) method to open the database, The second parameter, factory, indicates that the factory can use NULL as the default, and the third parameter, flags, indicates the open mode (with the OPEN_READONLY representation open as read-only in sqlitedatabase). For the first parameter, path indicates the paths of the database that needs to be loaded, because the SQL database cannot be loaded by file, so you need to copy the database to the system's data/data/package name (this example is Com.example.mobilesafe) when the program is initialized. files/database name. db (see step 8th for details), at which point the value of path is "data/data/com.example.mobilesafe/files/address.db", and path is defined as a static member variable of class and assigned value;

5, the 4th Step OpenDatabase () method returns a Sqlitedatabase object (named Database), through the Sqlitedatabase object (named Database) rawquery (String sql, String[] Selectionargs) method executes the database query statement, the parameter string SQL represents the SQL statement that needs to be executed (this needs to be written according to the characteristics of the database, in this case the select location from data2 where id = ( Select Outkey from data1 where id =?) ), parameter string[] Selectionargs for all of the SQL statements? An array of the corresponding parameters (which needs to be instantiated via new, this example is the parameter number passed in by the Querynumber method), because number is 11 bits, and the database has only 7 bits, so the substring (int) of the string object (number) Start, int end) method intercepts the first 7 digits (that is, 0,7, where 7 is not taken)

6, the 5th cloth in the Rawquery () method to return the cursor object (named cursor), using the while statement to determine whether the cursor object (cursor) has the next item (MoveToNext ()), if any, The GetString (int columnindex) method of the Cursor object (cursor) is used in the while statement to obtain the attribution, and the parameter int columnindex is the column number of the column in which the attribution information resides. This method returns an object of type string (named location), because the database data is incomplete or update is not timely, there are some number of non-attribution, so at the beginning of the Querynumber method instantiate location, and make its value equal to the number, The value is assigned to location when the attribution is queried in the while statement;

7. Release the cursor object resource through the close () method of the Cursor object (cursor), and finally return to location;

Querynumber (String number) method code;

1  Public Staticstring Querynumber (string number) {2         3String location =Number ;4 5Sqlitedatabase database = sqlitedatabase.opendatabase (path,NULL,6 sqlitedatabase.open_readonly);7cursor cursor =Database.rawquery (8"Select location from data2 where id = (select Outkey from data1 where id =?)",9                 NewString[] {number.substring (0, 7) });Ten          while(Cursor.movetonext ()) { OneLocation = cursor.getstring (0); A         } - cursor.close (); -         return""; the}
View Code

8. When the program is initialized, copy the database under the Assets folder to the development directory. In the initialization interface (splashactivity), create a new copy of the database to the path directory (named Copydb ()), the method type is private. In the Copydb () method:

(1) A file object (named file) is instantiated by using the new file Dir, and the parameter file dir is the directory created for the file (in this case the directory is a file in the program, so it can be passed Getfilesdir () method), the parameter string name is the file name (in this case, the file name of the copy is the same as the filename in the Open method);

(2) The open (string filename) method with the Getassets () method (in fact, omitted here under Content) opens a file with the filename (parameter String filename) under the Assets folder. To get the InputStream object (named is). Because this method has an exception, the Try...catch ... The statement will catch the exception;

(3) using the new FileOutputStream (file file) method to instantiate a file output stream object FileOutputStream (named Fos), the parameter file file is the file object created in (2);

(4) Instantiate a byte array object of length 1024 by new (named Buffer), and then define an int object with a value of 0 (named Len);

(5) Read its length through the read (byte[] buffer) method of the InputStream object (is) and assign the result to an int object (len), parameter byte[] buffer to an array object in (4). Use the While statement to determine whether the read result is-a-to-do related operation (when there is no data in the InputStream object, this will return 1), if the judgment condition is not equal to 1 is established, then execute the while statement;

(6) write (byte[] buffer, int byteoffset, int byteCount) in the while statement through the FileOutputStream object (FOS) Method writes the data from the InputStream object to the FileOutputStream object, the parameter byte[] buffer is the byte data, which is buffer in (4), and the parameter int byteoffset represents the starting position from buffer (0). The parameter int bytecount indicates the length (len) written to the stream from buffer

(7) Close the input stream InputStream object (is) and the output stream FileOutputStream object (FOS);

(8) Optimize the Copy method. Therefore, the copy data Method (Copydb ()) is always executed when the program is initialized, so that duplicate copies are made, so the file (that is, step (1)) in the Copydb () method is created by the file object's exists () method and Length () method to determine if the file exists and the length is greater than 0, if there is a print log or output "initialization complete" and other statements, etc., if not exist, then carry out the above steps (1) to (7);

Copy the database to the specified directory code:

1 Private voidCopydb () {2         Try {3File File =NewFile (Getfilesdir (), "address.db");4             if(File.exists () &&file.length () >0){5                 //There is no need to copy6SYSTEM.OUT.PRINTLN ("Database has been copied");7}Else{8                 //Copy Database9InputStream is = Getassets (). Open ("Address.db"); TenFileOutputStream fos =Newfileoutputstream (file); One                 byte[] buffer =New byte[1024]; A                 intLen = 0; -                  while(Len= (is.read (buffer)))!=-1){ -Fos.write (buffer, 0, Len); the                 } - is.close (); - fos.close (); -             }             +}Catch(IOException e) { - e.printstacktrace (); +         } A}
View Code

9, in the "Number Attribution to Query page" (numberaddqueryactivity) of the "Query number Attribution" Method (Numberaddquery) to determine that the input text box is not empty (that is, else statement), The previous phone number (Phone_number) is passed in through the Querynumber (String #) method in the tool class (Numberaddqueryutils), returning a String-type address value (named addresses);

10, through the TextView object (show_number_add) of the SetText (charsequence text) method will be 9 to fill in the value, so that the number to find the attribution.

Use the method code in the tool class:

1 // go to the database and query the number attribution. 2             String address = Numberaddqueryutils.querynumber (phone_number); 3             Show_number_add.settext (address);
View Code

Android instance-Mobile security Defender (33)-Import the database into the program

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.