Android development-data storage II, android Data Storage

Source: Internet
Author: User

Android development-data storage II, android Data Storage

This chapter continues to explain how to store and manage data in Android development. Knowledge Point: SQLite and SwipeRefreshLayout controls are refreshed.

1. Functional Requirements

Exercise Using SQLite

  • Create a logon interface. The database field contains the user name, password, and logon status.
  • After successful simulated logon, write the user name and logon status (logged on in progress) to the database and go to the new page with the exit button
  • When you click exit, the current user's logon status is cleared.
  • The User Name of the last logon is displayed during the next logon.
  • Saves the logon history of all users, but only one record is retained for one user name.
2. Software Implementation

Figure 1

Figure 2

Figure 3

Figure 4

Figure 5

Brief description: on the left-side Navigation Pane (figure 5), you can select the logon page (figure 1) and logon list page (figure 2 ). After successful logon, the logon list page is displayed. You can select exit to clear the logon status of the current user. Logon list. The page information can be refreshed from the drop-down list (Figure 3 ).

3. Related Knowledge (1) SQLite Introduction

SQLite is a lightweight database and ACID-compliant relational database management system. It is contained in a relatively small C library. It is a public project established by D. Richard IPP. It is designed to be embedded, and has been used in many embedded products. It occupies very low resources. In embedded devices, it may only take several hundred KB of memory.

SQLite consists of the following parts: SQL Compiler, kernel, backend, and attachment. By using virtual machines and virtual database engine (VDBE), SQLite is more convenient to debug, modify, and expand the SQLite kernel. All SQL statements are compiled into readable assembly that can be executed in the SQLite virtual machine. The overall structure of SQLite is as follows:

(2) SQLite Performance
  • In terms of data storage, the pocket-sized SQLite can support databases of up to 2 TB size. Each database exists in the form of a single file, these data are stored on the disk in the form of B-Tree data structure.
  • In terms of transaction processing, SQLite achieves independent transaction processing through database-level isolation and shared locks. This means that multiple processes can read data from the same database at the same time, but only one can write data. An exclusive lock must be obtained before a process or thread wants the database to perform write operations. After an exclusive lock is obtained, other read or write operations will not happen again.
  • SQLite uses a dynamic data type. When a value is inserted into the database, SQLite checks its type. If the type does not match the associated column, SQLite will try to convert the value to the type of the column. If it cannot be converted, the value will be stored as its own type, which SQLite calls "weak type ". However, there is a special case. If it is an integer primary key, other types will not be converted, and a "datatype missmatch" error will be reported.
(3) SQLite supports field types

SQLite currently supports the following types of data storage fields: VARCHAR (10), NVARCHAR (15), TEXT, INTEGER, FLOAT, BOOLEAN, CLOB, BLOB, TIMESTAMP, NUMERIC (10, 5), varying character (24), national varying character (16 ).

(4) SQLite data operation rules

In the Android project, after the database is generated, it is stored in the/data/[PACKAGE_NAME]/databases directory.

1. When adding, updating, and deleting data, you can use the following general statements:
  • Db.exe cuteSQL (String SQL );
  • Db.exe cuteSQL (String SQL, Object [] bindArgs); // use placeholders in SQL statements, and the second parameter is the actual parameter set.
2. Special SQL operation statements
  • Db. insert (String table, String nullColumnHack, ContentValues values );
  • Db. update (String table, Contentvalues values, String whereClause, String whereArgs );
  • Db. delete (String table, String whereClause, String whereArgs );
  • Db. rawQuery (String SQL, String [] selectionArgs );
  • Db. query (String table, String [] columns, String selection, String [] selectionArgs, String groupBy, String having, String orderBy );
  • Db. query (String table, String [] columns, String selection, String [] selectionArgs, String groupBy, String having, String orderBy, String limit );
  • Db. query (String distinct, String table, String [] columns, String selection, String [] selectionArgs, String groupBy, String having );

The first parameter of the preceding method indicates the name of the table to be operated;

The second parameter in insert indicates that if each column of the inserted data is empty, you must specify the name of a column in this row. The system sets this column to NULL without errors;

The third parameter in insert is a variable of the ContentValues type, which is a Map consisting of key-value pairs. key indicates the column name, and value indicates the value to be inserted in the column;

The second parameter of update is similar, except that it updates the key of this field to the latest value,

The third parameter whereClause indicates the WHERE expression, for example, "age>? And age <?" And so on. The final whereArgs parameter is the actual parameter value of the placeholder;

The parameters of the delete method are the same as those of the update method;

Db. query parameters are input to indicate query. They return a Cursor object at the same time, representing the Cursor of the dataset.

In addition to the preceding basic SQL statement, SQLite also supports transaction operations, such as the following:

1 public void TestTransaction (List <Person> persons) {2 db. beginTransaction (); // start transaction 3 try {4 for (Person person: persons) {5 db.exe cSQL ("insert into person VALUES (null ,?, ?, ?) ", New Object [] {person. name, person. age, });}
Db. setTransactionSuccessful (); // SET transaction success 6} finally {7 db. endTransaction (); // end transaction 8} 9}
(4) Comparison of SQLite General SQL statements and special module operations
  • Db.exe cuteSQL (String SQL). With this method, programmers who are skilled in writing SQL statements can quickly write SQL statements. Accelerate development. However, such SQL statements are too coupled and inflexible. Once the database field is modified, the corresponding business needs to be modified.
  • Using special operation statements, instead of Directly Writing SQL statements, you need to input different tables, fields, and other information, which is relatively troublesome, however, it reduces the coupling between the system business module and the database. In terms of database design, if the planning is good, when making database fields, modifications, and additions, you do not need to modify or modify a few business logic codes.
(5) SwipeRefreshLayout

Various drop-down controls and drop-down operations are emerging in Android development. Google finally launched its own drop-down component SwipeRefreshLayout, Which is lightweight, flexible, and easy to operate.

The swipeRefreshLayout class is placed in the android-support-v4.jar. The SwipeRefreshLayout component only accepts one child component, that is, the component to be refreshed. It uses a listener mechanism to notify listeners with this component of refreshing events. In other words, our Activity must implement the notification interface. This Activity is responsible for handling event refresh and refreshing the corresponding view. Once the listener receives the event, it determines what should be handled during the refresh process. To display a "Refresh Animation", it must callsetRefrshing(true)Otherwise, the animation will be called.setRefreshing(false).

(6) SwipeRefreshLayout: 1. Add the SwipeRefreshLayout control to the layout file and place the view to be refreshed in the control. For example, refresh a Fragment View:
<    android:id="@+id/sr"    android:layout_width="match_parent"    android:layout_height="match_parent"><RelativeLayout    android:layout_width="match_parent"    android:layout_height="match_parent"     <FrameLayout        android:id="@+id/fl_content"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:layout_above="@id/line" /></RelativeLayout></>
2. perform the following operations in the background code:
Sr = (SwipeRefreshLayout) findViewById (R. id. sr); sr. setColorSchemeResources (android. r. color. holo_blue_bright, android. r. color. holo_green_light, android. r. color. holo_orange_light, android. r. color. holo_red_light); sr. setOnRefreshListener (new SwipeRefreshLayout. onRefreshListener () {@ Override public void onRefresh () {appLoginDetailFragment (); // operation sr for Refresh. setRefreshing (false );}});
4. Analysis of core project code

The Demo structure of the Android database operation project is as follows:

(1) database processing

Database processing is placed in the db package. dbhelper is the basic operation for creating a database, including the table creation statement. clssqlite indicates providing general operation templates such as database query and opening.

(2) logon handling

Logon handling requirements: After a simulated logon is successful, the user name and logon status (logon in progress) are written to the database to save the logon history of all users, but only one record is retained for one user name. Therefore, during logon, you must first check whether the data table contains the information of the Logon account. The core code is as follows:

1 private void init () 2 {3 try {4 db = new clssqlite (); 5 db. openDB (getActivity (); 6 login_on.setOnClickListener (new View. onClickListener () {7 @ Override 8 public void onClick (View arg0) {9 SimpleDateFormat format = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss "); // you can set the format here. The 10 // format () method is used to format the time. 11 Date datenow = new Date (); 12 String returnTime = format. format (datenow); 13 String account = operator. getText (). toString (); 14 String passwords = password. getText (). toString (); 15 // check whether the account contains 16 int loginstatus = db. checklogin ("select count (*) as data from LoginData where account = '" + account + "'"); 17 try {Thread. sleep (400); 18} catch (InterruptedException e) {19 e. printStackTrace ();} 20 String SQL = "insert into LoginData (account, password, loginstatus, logintime) values ('" + account + "', '" + passwords + "', 1, '"+ returnTime +"') "; 21 if (loginstatus> 0) 22 SQL =" update LoginData set loginstatus = 1, logintime = '"+ returnTime +" 'where account =' "+ account +" '"; 23 db. openDB (getActivity (); 24 if(db.exe cuteSQL (SQL)> = 0) 25 {26 // save login name 27 result. setText ("Logon successful"); 28 account_save.edit (). putString ("account", account ). commit (); 29 (MainActivity) mContext ). appLoginDetailFragment (); 30 (MainActivity) mContext ). setToolbarTitle ("Logon List"); 31} else {32 result. setText ("Logon Failed"); 33 }}34}); 35} catch (Exception ex) 36 {37 result. setText ("Logon exception");} 38}
(3) display the User Name For The Last Logon

This knowledge can be stored using SharedPreferences in the previous chapter. After Successful Logon, the user name is saved according to the code account_save.edit (). putString ("account", account). commit.

(4) Exit and clear the logon status

When you exit, you must first verify that the user has logged on. If you have logged on, update the logon Status field in the data table. The core code is as follows:

1 public boolean onOptionsItemSelected (MenuItem item) {2 int id = item. getItemId (); 3 // Exit Processing 4 if (id = R. id. action_loginoutmode) {5 db. openDB (this); 6 String account = LoginFragment. account_save.getString ("account", "00000"); 7 int loginstatus = db. checklogin ("select count (*) as data from LoginData where account = '" + account + "' and loginstatus = 1"); 8 if (loginstatus> 0) 9 {10 String SQL = "update LoginData set loginstatus = 0 where account = '" + account + "'"; 11 db. openDB (this); 12 db.exe cuteSQL (SQL); 13 appLoginDetailFragment (); 14 Toast. makeText (getApplicationContext (), "Logon successful", Toast. LENGTH_SHORT ). show (); 15} 16 else17 {18 Toast. makeText (getApplicationContext (), "not logged on", Toast. LENGTH_SHORT ). show (); 19} 20} 21 return super. onOptionsItemSelected (item); 22}
(5) Logon Information Display

The logon Status display displays the field information stored in the data table on the interface. The page refresh operation triggers a refresh event when the listview is pulled to the top. The related code is as follows:

1 listView. setOnScrollListener (new AbsListView. onScrollListener () {2 @ Override 3 public void onScrollStateChanged (AbsListView view, int scrollState) {4} 5 @ Override 6 public void onScroll (AbsListView view, int cursor, 7 int visibleItemCount, int totalItemCount) {8 if (listView! = Null & listView. getChildCount ()> 0) {9 boolean enable = (firstVisibleItem = 0) & (view. getChildAt (firstVisibleItem ). getTop () = 0); 10 // call the refresh control 11 (MainActivity) mContext ). setSwipeRefreshEnable (enable); 12} 13} 14 });
5. Download the project source code

The source code of this project is on the 360 cloud disk and the development environment is Android Studio 2.0 beta 7.

Https:// access password f3d5. File Name: android database storage operation demo.


Related Article

Cloud Intelligence Leading the Digital Future

Alibaba Cloud ACtivate Online Conference, Nov. 20th & 21st, 2019 (UTC+08)

Register Now >

Starter Package

SSD Cloud server and data transfer for only $2.50 a month

Get Started >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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: and provide relevant evidence. A staff member will contact you within 5 working days.