Android login and registration using SQLite Database

Source: Internet
Author: User

first, let's talk about the concept of SQLite:

SQLite is an open-source embedded relational database, which can reduce the overhead of the application Program to manage data, SQLite is portable, easy to use, small, efficient, and reliable. Currently, sqlite3 is integrated in Android. SQLite does not support static data types, but uses column relationships. This means that its data type does not have the table column attribute, but has the data attribute. When a value is inserted into the database, SQLite checks its type. If this type does not match the associated column, SQLite will try to convert the value to the column type. If the conversion fails, the value is stored as its own type. SQLite supports null, integer, real, text, and BLOB data types. For example, you can store strings in integer fields, floating point numbers in Boolean fields, or date values in numeric fields. But there is one exception. If your primary key is integer, you can only store 6 4-digit integers. If you store data other than integers in this field, an error will occur. In addition, when SQLite parses the reate TABLE statement, it will ignore the data type information following the field name in the create table statement.

Features of SQLite

The SQLite database has the following features:

1. Zero Configuration

Sqlite3 does not require installation, configuration, startup, shutdown, or database instance configuration. When the system crashes, it does not need to perform any restoration operations and is automatically restored when the database is used next time.

2. Portable

It runs on Windows, Linux, BSD, Mac OS X, and some commercial Unix systems, such as Sun's Solaris and IBM's Aix. Similarly, it can also work in many embedded operating systems, such as Android, QNX, VxWorks, Palm OS, symbin, and Windows CE.

3. Compact

SQLite is designed to be lightweight and self-contained. With a header file and a lib library, you can use relational databases without starting any system processes.

4. Simple

SQLite has simple and easy-to-use APIs.

5. Reliable

The source code of SQLite reaches 100% branch test coverage.

Login and Registration

1. as follows:

2. Write JavaBean

This class is very simple, just define ID, username, password, age, sex, so it is not provided here! The service-layer service classCode:

Use sqliteopenhelper abstract class to create a database

The abstract class sqliteopenhelper is used to manage database versions, which is not required.

To manage database versions, the sqliteopenhelper class provides two important methods: oncreate (sqlitedatabasedb) and onupgrade (sqlitedatabase dB, int oldversion, intnewversion) used to generate a database table when you first use the software. The latter is used to update the database table structure when you upgrade the software.

Databasehelper. Java

Public Class Databasehelper Extends Sqliteopenhelper {
Static String name = "user. DB ";
Static Int Dbversion = 1;
Public Databasehelper (context ){
Super (Context, name, Null , Dbversion );
}
// Use only once during creation
Public Void Oncreate (sqlitedatabase dB ){
String SQL = "CREATE TABLE user (ID integer primary key autoincrement, username varchar (20), password varchar (20), age integer, sex varchar (2 ))";
Db.exe csql (SQL );
}
Public Void Onupgrade (sqlitedatabase dB, Int Oldversion, Int Newversion ){

}

}

 

Sqlitedatabase.exe csql (string SQL) can be used to execute non-query SQL commands, which have no results
Including: Create Table/drop table/insert, etc.

Then, userservice. Java implements table operations:

Public Class Userservice {
Private Databasehelper dbhelper;
Public Userservice (context ){
Dbhelper = New Databasehelper (context );
}

// Logon
Public Boolean Login (string username, string password ){
Sqlitedatabase SDB = dbhelper. getreadabledatabase ();
String SQL = "select * from user where username =? And Password =? ";
Cursor cursor = SDB. rawquery (SQL, New String [] {username, password });
If (Cursor. movetofirst () = True ){
Cursor. Close ();
Return True ;
}
Return False ;
}
// Registration
Public Boolean Register (User user ){
Sqlitedatabase SDB = dbhelper. getreadabledatabase ();
String SQL = "insert into user (username, password, Age, Sex) values (?,?,?,?) ";
Object OBJ [] = {user. GetUserName (), user. GetPassword (), user. getage (), user. getsex ()};
Sdb.exe csql (SQL, OBJ );
Return True ;
}
}

 

The above Code sets a cursor:

Android uses cursors to navigate query results
Cursors is described by the Android. database. cursor object.
A cursors is a simple pointer from
One or ...... )
Cursors returns the tuples at the moment when it locates.
The following code is used to explain the problem:

// To create a cursor (cursor), you must execute a query or use the rawquery () method through SQL.
// Or a more well-designed method, such as the query () method
Cursor cur = my_database.rawquery ("select * form test ", Null Null Null Null );
Ififififif (cur! = Null Null Null Null ){ // The cursor is not empty.
// Returns the index starting from 0 for the column with the given name. If the attribute column does not exist,-1 is returned.
// Retrieve attribute values using their indexes
Int Int Int Int Numcolumn = cur. getcolumnindex ("somenumber ");
Ififififif (cur. movetofirst ()){
// Cur. movetofirst () points the cursor to the first row. If the cursor points to the first row, true is returned.
Do {
Int Int Int Int Num = cur. getint (numcolumn); // obtain the value of this attribute in the current row
/* Cursor provides different methods for returning different data types
For example, getint ( Int Index)/getstring ( Int Index) and so on */
/* Do some things */
} While While While While (Cur. movetonext ());
/* Move the cursor to the next row. If the cursor has passed the end Of the result set,
If no row can be moved False */
// Other methods that may be moved are previous () and first ().
}
}

 

Close the cursor !!!
The following is the test code: Public Class Usertest Extends Androidtestcase {
Public Void Datatest () Throws Throwable {
Databasehelper dbhepler = New Databasehelper ( This . Getcontext ());
Dbhepler. getreadabledatabase ();
}
// Register
Public Void Registertest () Throws Throwable {
Userservice uservice = New Userservice ( This . Getcontext ());
User user = New User ();
User. setusername ("renhaili ");
User. setpassword ("123 ");
User. setage (20 );
User. setsex ("female ");
Uservice. Register (User );
}
// Login
Public Void Logintest () Throws Throwable {
Userservice uservice = New Userservice ( This . Getcontext ());
String username = "renhaili ";
String Password = "123 ";
Boolean Flag = uservice. login (username, password );
If (FLAG ){
Log. I ("tag", "Logon successful ");
} Else {
Log. I ("tag", "Logon Failed ");
}
}

}

Common exceptions

Android. database. SQLite. sqliteexception: Can't upgrade read-only database from version 0 to 1:

This error is basically caused by SQL problems. Check the SQL carefully.

Finally, I want to say: After writing the implementation class, I 'd better write this test class to test it. Otherwise, it will be very troublesome to encounter errors in the future. So I passed all the tests and wrote the interface and activity, the code of the interface and activity is not provided. The Source Code address is provided. If you are interested, you can download the code for reference !!!

Source code:Http://files.cnblogs.com/greatverve/SQLiteLogin.7z

URL: http://greatverve.cnblogs.com/archive/2011/12/26/android-sqlite-login.html

 

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.