Android SQLite database application (i)

Source: Internet
Author: User

First a small program, the specific analysis of the introduction will be in the future of the article in detail, has been 0:40, I am really sleepy, can only move to tomorrow. Paste the code first today.

: (data is stored in the database, and then the data is read out)

Main.xml

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:orientation=" vertical "    android:layout_width=" Fill_parent "     Android:layout_height= "Fill_parent"    ><TextView      android:layout_width= "Fill_parent"      android:layout_height= "Wrap_content"     android:id= "@+id/textview"    /></ Linearlayout>

Activity's Code

 PackageCn.com.SQLite;Importjava.util.ArrayList;Importandroid.app.Activity;Importandroid.content.ContentValues;ImportAndroid.content.Context;ImportAndroid.database.Cursor;Importandroid.database.sqlite.SQLiteDatabase;ImportAndroid.database.sqlite.SQLiteOpenHelper;Importandroid.database.sqlite.SQLiteDatabase.CursorFactory;ImportAndroid.os.Bundle;ImportAndroid.util.Log;ImportAndroid.widget.TextView;/** *  * @authorChenzheng_java * @description the application of SQLite database in Android *@since2011/03/05 **/ Public classSqliteactivityextendsActivity {PrivateString result = "Result:/n"; PrivateString tableName = "Chenzheng_java";  Public Static Final intversion_1 = 1; @Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.main);        Run (); TextView TextView=(TextView) Findviewbyid (R.id.textview);    Textview.settext (result); }    /*** @description The data to be increased and censored*/    Private voidRun () {clear ();        Save ();    Read (); }    /*** Read the record from the data table*/    Private voidRead () {Mysqliteopenhandler handler=NewMysqliteopenhandler ( This, TableName,NULL, version_1); Sqlitedatabase Database=handler.getwritabledatabase (); Cursor Cursor= Database.query (TableName,NULL,NULL,NULL,NULL,NULL,                NULL); intCount =Cursor.getcount (); LOG.I ("Notifications", "Total records" +count); intindex = cursor.getcolumnindex ("name"); LOG.I ("Notification", "Nameindex" +index); intIndexofage = Cursor.getcolumnindex ("Age");        Cursor.movetofirst ();  while(!Cursor.isafterlast ()) {LOG.I ("Notifications", "here"); String name=cursor.getstring (index); Result+ = "/N Name:" +name; intAge =Cursor.getint (indexofage); Result+ = "Age:" +Age ;        Cursor.movetonext ();    } database.close (); }    /*** Save some data to the table*/    Private voidSave () {ArrayList<Beauty> beautylist =GetData (); Mysqliteopenhandler Handler=NewMysqliteopenhandler (sqliteactivity. This, TableName,NULL, version_1); Sqlitedatabase Database=handler.getwritabledatabase ();  for(Beauty beauty:beautylist) {//Start thingsdatabase.begintransaction (); //An object that stores column names and values as key-value pairsContentvalues contentvalues =Newcontentvalues (); Contentvalues.put ("Name", Beauty.getname ()); Contentvalues.put ("Age", Beauty.getage ()); LongFlag = Database.insertorthrow (TableName, "age", contentvalues); LOG.I (Notification, beauty.tostring ()); if(Flag = =-1) {log.i ("Notification", "insert operation failed"); } Else{database.settransactionsuccessful (); }            //End Thingsdatabase.endtransaction ();    } database.close (); }    /*** Clear records from the table*/    Private voidClear () {Mysqliteopenhandler handler=NewMysqliteopenhandler (sqliteactivity. This, TableName,NULL, version_1); Sqlitedatabase Database=handler.getwritabledatabase (); Database.delete (TableName,NULL,NULL);    Database.close (); }    /**     *      * @returnInitializing Data*/    PrivateArraylist<beauty>GetData () {ArrayList<Beauty> beautylist =NewArraylist<beauty>(); Beauty Beauty=NULL; Beauty=NewBeauty ("Little Doctor Xian", 23);        Beautylist.add (Beauty); Beauty=NewBeauty ("Shang son", 21);        Beautylist.add (Beauty); Beauty=NewBeauty ("Queen Dumesha", 24);        Beautylist.add (Beauty); returnbeautylist; }    /**     * @authorChenzheng_java * @description achieve our own creation and update of SQLite help class *@since2011/03/05*/    Private classMysqliteopenhandlerextendsSqliteopenhelper { PublicMysqliteopenhandler (Context context, String name, Cursorfactory factory,intversion) {            Super(context, name, Factory, version); LOG.I ("Notification", "Mysqliteopenhandler instantiation Complete"); }        /*** The OnCreate method executes when a user-queried table is not present in the system, where we can implement the method and do some extra work*/@Override Public voidonCreate (Sqlitedatabase db) {Db.execsql ("DROP table if exists" +tableName); db. Execsql ("CREATE table if not exists '" +TableName+ "' (ID integer primary key,name varchar (), age INTEGER)"); LOG.I ("Notification", "CREATE TABLE successfully!" "); }        /*** The Onupgrade method executes when the application version changes in the system*/@Override Public voidOnupgrade (Sqlitedatabase db,intOldversion,intnewversion) {LOG.I ("Notification", "version upgrade succeeded!" "); }    }    /**     *      * @authorChenzheng_java * @description Beauty entity class*/    Private classBeauty {String name; intAge ;  PublicBeauty () {} PublicBeauty (String name,intAge ) {             This. Name =name;  This. Age =Age ; }         PublicString GetName () {returnname; }         Public voidsetName (String name) { This. Name =name; }         Public intGetage () {returnAge ; }         Public voidSetage (intAge ) {             This. Age =Age ; } @Override PublicString toString () {return"Beauty [age=" + Age + ", name=" + name + "]"; }    }}

Others are the default. Run, you can get the results as above.

------------------------------------------------------------------------

Notice here, Mysqliteopenhandler the constructor of the class, the second parameter, actually represents the database name, not the table name, here directly using the table name to build, is to let the code look a little less, also meet the author lazy desire, hehe. Remember to remember

Android SQLite database application (i)

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.