About Android SQLite

Source: Internet
Author: User

SQLite is a very popular embedded database that supports the SQL language and has good performance with very little memory. It's also open source and can be used by anyone. Many open source projects (Mozilla, PHP, Python) use SQLite;

Android does not automatically provide a database. To use SQLite in an Android app, you must create your own database and then create a table, index, and add data to it. Android provides sqliteopenhelper to help you create a database that you can easily create by inheriting the Sqliteopenhelper class. The Sqliteopenhelper class encapsulates the logic used to create and update databases, based on the needs of the development application. Sqliteopenhelper, you need to implement at least three methods:

    • constructor to invoke the constructor of the parent class Sqliteopenhelper. This method requires four parameters: the context (for example, an Activity), the database name, an optional cursor factory (usually Null), and an integer representing the version of the database model you are using.
    • The OnCreate () method, which requires a Sqlitedatabase object as a parameter, populates the table and initializes the data as needed.
    • The Onupgrage () method, which requires three parameters, a Sqlitedatabase object, an old version number, and a new version number, so you can clearly see how to transform a database from the old model to the new one.

Detailed introduction can be consulted:

Http://www.cnblogs.com/Excellent/archive/2011/11/19/2254888.html

http://blog.csdn.net/liuhe688/article/details/6715983

The following is a simple example of adding and removing changes to illustrate: specific

Click Add Data, then click Query Data:

Then click Edit, then query:

Then delete, then query:

The implementation code is as follows:

Mainactivity.java

 PackageCom.xiaozhang.sqltest1;Importjava.util.ArrayList;ImportJava.util.HashMap;ImportJava.util.Map;Importandroid.app.Activity;Importandroid.content.ContentValues;ImportAndroid.database.Cursor;Importandroid.database.sqlite.SQLiteDatabase;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.widget.ListView;ImportAndroid.widget.SimpleAdapter; Public classMainactivityextendsActivity {PrivateDatabasehelper Databasehelper; PrivateSqlitedatabase SQLite; PrivateListView ListView; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); ListView=(ListView) Findviewbyid (R.id.listview); Databasehelper=NewDatabasehelper ( This); SQLite=databasehelper.getwritabledatabase (); }    //Add student Information     Public voidAdd (view view) {ArrayList<Student> Student =NewArraylist<student>(); Student Student1=NewStudent ("Zhang San", 23, "Henan province"); Student Student2=NewStudent ("John Doe", 25, "Shandong province"); Student Student3=NewStudent ("Harry", 21, "Shaanxi Province"); Student Student4=NewStudent ("Zhao Liu", 22, "Fujian province");        Student.add (STUDENT1);        Student.add (Student2);        Student.add (STUDENT3);        Student.add (STUDENT4); //Set up TransactionsSqlite.begintransaction ();//Start a transaction        Try {             for(Student stu:student) {sqlite.execsql ("INSERT into student VALUES (null,?,?,?)",                        Newobject[] {stu.name, stu.age, stu.address}); } sqlite.settransactionsuccessful (); //SET Transaction completion successfully}finally{sqlite.endtransaction ();//End Transaction        }    }    //Change the address named "Zhang San" to "Beijing";     Public voidUpdate (view view) {contentvalues CV=Newcontentvalues (); Student Student=NewStudent (); Student.address= "Beijing"; Student.name= "Zhang San"; Cv.put ("Address", student.address); Sqlite.update ("Student", CV, "name =?",Newstring[] {student.name}); }    //Delete a person aged 22 years     Public voidDelete (view view) {Student Student=NewStudent (); Student=NewStudent (); Student.age= 22; Sqlite.delete ("Student", "Age =?",                Newstring[] {string.valueof (student.age)}); }    //Search All information     Public voidquery (view view) {Student Student=NewStudent (); Cursor C= Sqlite.rawquery ("SELECT * FROM Student",NULL); ArrayList<Student> list =NewArraylist<student>();  while(C.movetonext ()) {Student=NewStudent (); student._id= C.getint (C.getcolumnindex ("_id")); Student.name= C.getstring (C.getcolumnindex ("name")); Student.address= C.getstring (C.getcolumnindex ("Address")); Student.age= C.getint (C.getcolumnindex ("Age"));        List.add (student); } ArrayList<map<string, string>> list2 =NewArraylist<map<string, string>>();  for(Student stu:list) {HashMap<string, string> map =NewHashmap<string, string>(); Map.put ("Name", Stu.name); Map.put ("Address", "-----" +stu.address + "-----" + stu.age + "years old");        List2.add (map);        } c.close (); Simpleadapter Adapter=NewSimpleadapter ( This, List2, Android. R.layout.simple_list_item_2,NewString[] {"Name",                        "Address"},New int[] {Android. R.id.text1, Android.        R.ID.TEXT2});    Listview.setadapter (adapter); }}

Databasehelper.java

 PackageCom.xiaozhang.sqltest1;ImportAndroid.content.Context;Importandroid.database.sqlite.SQLiteDatabase;ImportAndroid.database.sqlite.SQLiteOpenHelper; Public classDatabasehelperextendsSqliteopenhelper {Private Static FinalString database_name = "study"; Private Static Final intDatabase_version = 1;  PublicDatabasehelper (Context context) {Super(Context, database_name,NULL, database_version); } @Override Public voidonCreate (Sqlitedatabase db) {Db.execsql ("CREATE TABLE IF not EXISTS student" + "(_id integer PRIMARY KEY autoincrement, name VARCHAR, age INTEGER, Address TEXT) "); } @Override Public voidOnupgrade (Sqlitedatabase db,intOldversion,intnewversion) {Db.execsql ("ALTER TABLE student ADD COLUMN other STRING"); }}

Activity_main.xml

<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "vertical" >    <ButtonAndroid:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:onclick= "Add"Android:text= "Add Data" />    <ButtonAndroid:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:onclick= "Update"Android:text= "Update Data" />    <ButtonAndroid:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:onclick= "Delete"Android:text= "Delete Data" />    <ButtonAndroid:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:onclick= "Query"Android:text= "Query data" />    <ListViewAndroid:id= "@+id/listview"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content" /></LinearLayout>

If necessary, you can download the code: http://download.csdn.net/detail/u012724379/8239741

About Android SQLite

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.