Android Development-sqlite Operation

Source: Internet
Author: User
Tags command access

In writing the core part of the article I would like to briefly mention a small trick:

Usually in the layout of the use of a general may find a head or tail of a whole will be used frequently, in the usual Java program such a repeating part of the general consider a class to encapsulate, in android What happens in XML-like files? Here consider The encapsulation of the parts with an XML file.

First look at a real XML file I wrote

It can be seen that this XML file contains a lot of picture files, we can define a drawable by the XML defined by the The drawable object. It allows a picture to display different patterns in different states, such as a Button, which has pressed,focused , or other state, by using the State List drawable , you can provide a different picture for each state.

The Drawable object also has some other properties:

Android:drawableput adrawableResources
Android:state_pressedwhether to press, like a button to touch or tap.
Android:state_focusedwhether to get the focus, such as the user selected a text box.
Android:state_hoveredwhether the cursor hovers, usually withfocused StateSame, it is4.0the new features
android:state_selectedis selected, it is associated withFocus Statenot exactly the same as aList ViewWhen selected, the various sub-components within it may be selected through the arrow keys.
Android:state_checkablewhether the component can beCheck. such as:RadioButtonis can beCheckthe.
Android:state_checkedwaschecked, such as: aRadioButtoncan beCheckup.
Android:state_enabledability to accept touch or click events
android:state_activatedbe activated
Android:state_window_focusedif the application is in the foreground, the application is not in the foreground when a notification bar is pulled down or a dialog box pops up

The following will go into the whole of the article:sqlite Some of the operations can be sqlite database access (including command access and visual DDMS access)

The beginning of the problem: I recently needed to complete a small project on Android , the way the project was developed using prototyping, and at the beginning we had the idea of dividing the modules needed and some simple features.

But at the very least, the user's login and registration function module is required. (There are actually two ways to call SQLite and validate through a web servlet )

In order to have the initial experience and the existing Android Foundation, so in the early selection of android user Registration and login selection is sqlite Database for validation.

Here are some of my simple understandings of SQLite :

SQLite is a lightweight database, is an acid-compliant relational database management system, its design goals are embedded, and has been used in many embedded products, it occupies a very low resource.

Okay, so here I've figured out why to use him, so here's how to use him, and then compare it to the other databases:

SQLite's operations must understand several objects and then understand the invocation relationship, which can be developed later:

1. First of all, sqlitedatabase, all database development is based on sqlitedatabase development. and SQLite provides this API as long as we use this database development, in the program as long as the open sqlitedatabase can be read and write operations.

Use of the 2.SQLiteOpenHelper class

In fact, through the sqlitedatabase we have been able to make database additions and deletions, but we usually do not directly on this basis, but through a tool-sqliteopenhelper

Android in order to make it easier for us to manage the database, specifically provides a sqliteopenhelper to help

This class makes it very simple to create and upgrade databases.

Sqliteopenhelper is an abstract class, and we usually need to inherit it and implement the 3 functions inside it:

This class isSqlitedatabasean auxiliary class. This class mainly generates a  Database , and manages the version of the database. The method that calls this class in the programgetwritabledatabase ()orgetreadabledatabase ()method, if there is no data at that time, thenAndroidThe system will automatically generate a database. Sqliteopenhelperis an abstract class, we usually need to inherit it and implement the3a function(This will be reflected in the next procedure).

1.onCreate (Sqlitedatabase)

This method is called when the database is first generated, that is, it is called only when the database is created, and there are other situations where we typically generate database tables in this method.

2. Onupgrade (Sqlitedatabase,int,int)
When the database needs to be upgraded, the Android system will invoke this method on its own initiative. In general, we delete the data table in this method, and create a new data table, of course, whether we need to do other operations, depends entirely on the needs of the application.

3. OnOpen (sqlitedatabase):

This is a callback function when the database is opened, and is generally not used very often in programs.

3. Is the use of the cursor in a query:

This is also an object that must be used to query the database at logon

The cursor points to every piece of data. It provides a number of methods for querying, as follows:

Public Cursor query (String table,string[] columns,string selection,string[] selectionargs,string groupby,string have , String orderby,string limit);
The meaning of each parameter is explained:
Parameter table: Table name
Parameter columns: array of column names
Parameter selection: Conditional sentence, equivalent to where
Parameter Selectionargs: Conditional clause, parameter array
Parameter groupby: grouping columns
Parameters having: grouping conditions
Parameter order BY: Row sequence
Parameter limit: Paging query restrictions
Parameter cursor: The return value, equivalent to the result set resultset
The cursor is a cursor interface that provides methods for traversing query results, such as Move pointer method Move (), Get column value Method GetString (), and so on.

Cursor Cursor Common methods

Method name

Method description

GetCount ()

Get total number of data items

IsFirst ()

Determine if the first record

Islast ()

Determine if the last record

Movetofirst ()

Move to the first record

Movetolast ()

Move to the last record

Move (int offset)

Move to a specified record

MoveToNext ()

Move to Next record

Movetoprevious ()

Move to previous record

Getcolumnindexorthrow (String columnName)

Get column index based on column name

getInt (int columnindex)

Gets the int type value of the specified column index

getString (int columnindex)

Gets the string type value for the specified column miniature

Because this explanation is very abstract, through practical examples to understand the additions and deletions of sqlite to change the crud operation (The following is part):

1  Packagecom.lingdududu.testSQLiteDb;2 3 ImportAndroid.content.Context;4 Importandroid.database.sqlite.SQLiteDatabase;5 Importandroid.database.sqlite.SQLiteDatabase.CursorFactory;6 ImportAndroid.database.sqlite.SQLiteOpenHelper;7 ImportAndroid.util.Log;8 9  Public classStudbhelperextendsSqliteopenhelper {Ten  One Private Static FinalString TAG = "Testsqlite"; A  Public Static Final intVERSION = 1; -  - //You must have a constructor the  PublicStudbhelper (Context context, String name, Cursorfactory factory, - intversion) { - Super(context, name, Factory, version); - } +  - //This method is called when the database is created for the first time +  Public voidonCreate (Sqlitedatabase db) { AString sql = "CREATE TABLE stu_table (ID int,sname varchar (), Sage int,ssex varchar (10))"; at //output log information to create a database -LOG.I (TAG, "Create Database------------->"); - //The execsql function is used to execute SQL statements - db.execsql (SQL); - } -  in //This method is executed when the database is updated -  Public voidOnupgrade (Sqlitedatabase db,intOldversion,intnewversion) { to //Output update log information for database +LOG.I (TAG, "Update Database------------->"); - } the}

The Rawquery () method in the query inherits the first parameter of query as a select statement, and the second parameter is The value of the placeholder parameter in the SELECT statement , The parameter can be set to NULL if the SELECT statement does not use a placeholder .

Here's how:sqlite 's database access (including command access and visual DDMS Access) is resolved:

There are many examples that can be found on the Internet:

I summarize as follows:

Connect to your phone and PC side

In your PC, under Android SDK,

And

Add to System environment variables

In the command window, typing the command:

ADB shell- can be ordered to view the phone's files, and commands are basically linux commands, you can see that Android is actually the kernel is Linux.

CD data

CD data

This will enter the file where the Android project is located can be viewed with the LS command

Cd-com.example.test1(your project file name)

At this point, if

Note that there is no root permission, so you need to install the root Wizard on your phone. After root access

Su- Enter admin mode

Cd-com.example.test1(your project file name)

After you go in and look at all, you will see that there are databases, enter databases, show all will find your database name, here is used "info.db".

CD databases

Sqlite3 info.db

If it appears:

Then it is very likely that there is no mobile file System/xbin in the sqlite3 file so you need to import the specific can see the online tutorial.

The steps to visualize the operation are as follows:

But finding it cumbersome and visualizing the data is not good.

So I chose another way of editing: (the bottom or the command line is just the package on the basis)

In Android , you can use the Eclipse plugin DDMS to view

Need to download

    • Re Manager and SQLite Expert Personal 3

Re file manager increases read and write access to files

In Eclipse

Download the RE manager http://shouji.baidu.com/soft/item?docid=6865576&from=web_alad_6 to your Android phone and open it after installation.

Locate the Data folder, press and hold to open the options, and locate the permission settings

Finally, the import of the required database files is exported:

Also involves permission issues:

Cannot export from import

When I have given the maximum permissions on the command line, I still report the same error when I click Pull- a file from the device to continue the network search.

Finally found that the use of command pull in cmd to copy files is no problem, finally resolved .

The removed DB file can be imported into SQLite's visualizer:

This completes the basic operation of SQLite

Reference:

http://blog.csdn.net/leasystu/article/details/7250885

Http://www.cnblogs.com/walkingp/archive/2011/03/28/1997437.html

http://fruithardcandy.iteye.com/blog/1880672

Http://jingyan.baidu.com/article/6b97984d9b1bed1ca3b0bf4a.html

http://blog.csdn.net/codeeer/article/details/30237597

I hope my blog can help everyone.

One small step in the day, a big step to the Moon ~!!!

Android Development-sqlite Operation

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.