Android-sqlite Database _ Open an existing database operation demo

Source: Internet
Author: User

Code

 Packagecom.lxt008;ImportCOM.LXT008.R;Importandroid.app.Activity;Importandroid.content.ContentValues;ImportAndroid.database.Cursor;Importandroid.database.sqlite.SQLiteDatabase;ImportAndroid.graphics.Color;ImportAndroid.os.Bundle;Importandroid.view.KeyEvent;Importandroid.widget.LinearLayout;ImportAndroid.widget.ListAdapter;ImportAndroid.widget.ListView;ImportAndroid.widget.SimpleCursorAdapter; Public classActivity01extendsactivity{Private Static intMicount = 0; /*database Objects*/    PrivateSqlitedatabase msqlitedatabase =NULL; /*Database name*/    Private Final StaticString database_name = "Examples_06_05.db"; /*Table name*/    Private Final StaticString table_name = "Table1"; /*fields in the table*/    Private Final StaticString table_id = "_id"; Private Final StaticString table_num = "NUM"; Private Final StaticString table_data = "DATA"; /*to create a table's SQL statement*/    Private Final StaticString create_table = "CREATE TABLE" + table_name + "(" + table_id + "INTEGER PRIMARY KEY," + Table_num + "INTER GER, "+ Table_data +" TEXT) "; /*Linear Layout*/LinearLayout m_linearlayout=NULL; /*List View-display data in a database*/ListView M_listview=NULL; /**Called when the activity is first created.*/@Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); /*creating a LinearLayout Layout object*/M_linearlayout=NewLinearLayout ( This); /*to set the properties of a layout linearlayout*/m_linearlayout.setorientation (linearlayout.vertical);        M_linearlayout.setbackgroundcolor (Android.graphics.Color.BLACK); /*Create a ListView object*/M_listview=NewListView ( This); Linearlayout.layoutparams param=Newlinearlayout.layoutparams (LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);        M_listview.setbackgroundcolor (Color.Black); /*add M_listview to M_linearlayout layout*/M_linearlayout.addview (M_listview, param); /*Setting the display m_linearlayout layout*/Setcontentview (m_linearlayout); //open a database that already existsMsqlitedatabase = This. openorcreatedatabase (database_name, mode_private,NULL); //gets the cursor of the database phones        Try        {            /*Create a table in the database Msqlitedatabase*/Msqlitedatabase.execsql (create_table); }        Catch(Exception e) {updataadapter (); }    }     Public BooleanOnKeyUp (intKeyCode, KeyEvent event) {        Switch(keycode) { CaseKeyEvent.KEYCODE_DPAD_LEFT:AddData ();  Break;  CaseKeyEvent.KEYCODE_DPAD_RIGHT:DeleteData ();  Break;  CaseKeyEvent.KEYCODE_1:UpData ();  Break;  CaseKeyEvent.KEYCODE_2:DeleteTable ();  Break;  CaseKeyEvent.KEYCODE_3:DeleteDataBase ();  Break; }        return true; }
    /*Deleting a database*/     Public voidDeleteDatabase () { This. DeleteDatabase (database_name);  This. Finish (); }    /*Delete a table*/     Public voiddeletetable () {Msqlitedatabase.execsql ("DROP TABLE" +table_name);  This. Finish (); }    /*update One piece of data*/     Public voidUpdata () {contentvalues CV=Newcontentvalues ();        Cv.put (Table_num, Micount); Cv.put (Table_data,"Modified data" +micount); /*Update Data*/msqlitedatabase.update (TABLE_NAME, CV, Table_num+ "=" + integer.tostring (miCount-1),NULL);    Updataadapter (); }    /*add a piece of data to a table*/     Public voidAddData () {contentvalues CV=Newcontentvalues ();        Cv.put (Table_num, Micount); Cv.put (Table_data,"Test database Data" +micount); /*Inserting Data*/Msqlitedatabase.insert (table_name,NULL, CV); Micount++;    Updataadapter (); }    /*deletes a specified piece of data from a table*/     Public voidDeleteData () {/*Delete Data*/Msqlitedatabase.execsql ("DELETE from" + table_name + "WHERE _id=" +integer.tostring (Micount)); Micount--; if(Micount < 0) {Micount= 0;    } updataadapter (); }    /*more rows try to show*/     Public voidUpdataadapter () {//gets the cursor of the database phonesCursor cur = msqlitedatabase.query (table_name,NewString[] {table_id, table_num, Table_data},NULL,NULL,NULL,NULL,NULL); Micount=Cur.getcount (); if(cur! =NULL&& cur.getcount () >= 0)        {            //ListAdapter is a bridge between the ListView and background dataListAdapter adapter =NewSimplecursoradapter ( This,            //define a display template for each row in the list//indicates that each row contains two items of dataAndroid. R.layout.simple_list_item_2,//cursor Object for databasecur,//fetching data from Table_num and table_data two columns in the database                Newstring[] {table_num, table_data},//Views corresponding to name and number                New int[] {Android. R.id.text1, Android.            R.ID.TEXT2}); /*Add adapter to M_listview*/M_listview.setadapter (adapter); }    }    /*Key Event Handling*/     Public BooleanOnKeyDown (intKeyCode, KeyEvent event) {        if(KeyCode = =keyevent.keycode_back) {            /*when exiting, don't forget to close*/Msqlitedatabase.close ();  This. Finish (); return true; }        return Super. OnKeyDown (KeyCode, event); }}

Layout file

<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"android:orientation= "vertical"Android:layout_width= "Fill_parent"Android:layout_height= "Fill_parent"    ><TextViewAndroid:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:text= "@string/hello"    /></LinearLayout>

Android-sqlite Database _ Open an existing database operation demo

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.