Basic usage Summary of Android SQLite (eight)

Source: Internet
Author: User

Sharedpreferences is only suitable for storing relatively simple data and key-value pairs, supporting different data types

File storage key value pairs are not, no format processing, storing simple binary or text data

SQLite can handle data that is large in size and complex in structure.

Manage SQLite Sqlitehelper: Abstract class, you need to create your own helper class to inherit it, and rewrite OnCreate and Onupgrade,

There are also two instance methods that can be called: Getreadabledatabase () getwritabledatabase () can either create or open a database, However, Getreadabledatabase can continue to open as read-only when the database is not writable, but another method will produce an exception

Overriding constructors: General use of simple parameters this * * (context, database name, cursor, version number)

Using Android adb to see if the creation was successful, you need to configure the ADB environment variable ADB environment variable path D:\andriod\adt-bundle-windows-x86-20140702\ Adt-bundle-windows-x86-20140702\sdk\platform-tools environment variable%java_home%\bin of JAVA;

To create a database:

Create a database//first define a class Mydatabasehelper Public classMydatabasehelper extends sqliteopenhelper{ Public StaticFinal String create_book="CREATE TABLE book ("+"ID Integer PRIMARY key autoincrement,"+"tuthor text,"+"Price Real,"+"pages Integer,"+"Name text)"; //Create a new table upgrade database     Public StaticFinal String create_category="CREATE TABLE Category ("+"ID Integer PRIMARY key autoincrement,"+"catagory_name text,"+"categoty_code Integer)"; PrivateContext Mcontext;  PublicMydatabasehelper (Context context,string name,cursorfactory Factory,intversion)        {Super (context, name, Factory, version); Mcontext=context; }     Public voidonCreate (Sqlitedatabase db) {db.execsql (Create_book); Db.execsql (create_category);//See table statements for new table categoryToast.maketext (Mcontext,"Create secceed", Toast.length_short). Show (); }     Public voidOnupgrade (Sqlitedatabase db,intOldversion,intnewversion) {        Switch(oldversion) {////Upgrade Database when the old version is 1, only the newly added tables in version 2 are created, and the two tables are created when you install them directly .         Case 1:d B.execsql (create_category);//The break is not used here to ensure that all upgraded databases are created at the time of the cross-program upgrade         Case 2: Sb.execsql (create_category); default:        }    }}//creating a database in the main function Public classMainactivity extends Activity {PrivateMydatabasehelper DBHelper; @Overrideprotected voidonCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main); DBHelper=NewMydatabasehelper ( This,"boolstore.db",NULL,2);//The number here determines whether the update operation is performedButton createdatabase=(Button) Findviewbyid (r.id.create_database); Createdatabase.setonclicklistener (NewOnclicklistener () { Public voidOnClick (View v) {dbhelper.getwritabledatabase ();//Check if there is a library, do not create and electrophoresis oncreate see table, there is no create            }        }); Button AddData=(Button) Findviewbyid (r.id.adddata); Adddata.setonclicklistener (NewOnclicklistener () { Public voidOnClick (View v) {sqlitedatabase db=dbhelper.getwritabledatabase ();//Getwritabledatabase will return an object that can be manipulatedContentvalues values=Newcontentvalues (); Values.put ("name","The Da Vinci Code"); Values.put ("author","Dan Brown"); Values.put ("pages", the); Values.put (" Price", -); Db.insert (" Book",NULL, values);                Values.clear (); //start inserting the second barValues.put ("name","The lost symbol");                ..                .. Db.inset (" Book",NULL, values); //start inserting to another tableValues.put ("Categoty_code","12465");                ..                . Db.insert ("Category",NULL, values); //ID We set it to self-increment so we don't have to assign ID alone.            }        }); //updating data in a tableButton Updatedata=(Button) Findviewbyid (r.id.updatedata); Updatedata.setonclicklistener (Newonclicklistener{ Public voidOnClick (View v) {sqlitedatabase db=dbhelper.getwritabledatabase (); Contentvalues Values=Newcontentvalues (); Values.put (" Price",Ten); Db.update (" Book", Values,"name=?",Newstring[]{"The DaVinci Code"});//This specifies the title of the DaVinci Code and the price in the Book table is modified to                }        }); //Delete DataButton Deletedata=(Button) Findviewbyid (r.id.deletedata); Deletedata.setonclicklistener (Newonclicklistener{ Public voidOnClick (View v) {sqlitedatabase db=dbhelper.getwritabledatabase (); Db.delete (" Book","pages>?","New string[]{" -"}")//This specifies that books with pages greater than 500 are deleted                }        }); Button Querybutton=(Button) Findviewbyid (R.id.querubutton); Querybutton.setonclicklistener (NewOnclicklistener () { Public voidOnClick (View v) {sqlitedatabase db=dbhelper.getwritabledatabase (); Cursor Cursor=db.query (" Book",NULL,NULL,NULL,NULL,NULL,NULL);//after the query is finished, a cursor object is obtained, followed by a call to Movetofirst () traversal                if(Cursor.movetofirst ()) { Do{String name=cursor.getstring (Cursor.getcolumnindex ("name")); String author=cursor.getstring (Cursor.getcolumnindex ("author"));                    .. } while(Cursor.movetonext ());//Take out all the data in the book} cursor.close ();            }        }); }}

In order to operate a series of actions in a coherent sequence, it is either complete or complete.
Using transactions:

.. Public voidOnClick (View v) {sqlitedatabase db=dbhelper.getwritabledatabase ();    Db.begintransaction (); Try{db.delete (" Book",NULL,NULL); if(true){        Throw NewNullpointexception ();//Throwing Exceptions manually} contentvalues Values=Newcontentvalues (); Values.put ("name","BookName"); Values.put ("author","Bookauthor"); ... db.insert (" Book",NULL, values); Db.settransactionsuccessful ();//Transaction Execution succeeded}Catch(Exception e) {e.printstacktrace (); }finally{db.endtransaction ();//End Transaction    }}

Basic usage Summary of Android SQLite (eight)

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.