Android SQLite Database

Source: Internet
Author: User
Tags gettext sqlite database

SQLite database

Sqlitedatabase//Management operations database
Management
OpenDatabase//Open
Openorcreatedatabase//Open or create
Operations and additions and changes to check
EXECSQL//Execute SQL statement
Insert//Increment
Update//change
Delete//delete
Query//Check
Rawquery//sql Statement Check
Things
BeginTransaction//Start
Endtransaction//End
Cursor//Query Results
Move

Sqliteopenhelper//Management database and version updates
OnCreate//CREATE database callback for the first time
Onupgrade//callback when database version is updated
Getreadabledatabase//Read the way Open
Getwritabledatabase//write the way Open
Close//Turn off all open sqlitedatabase

Demo1 Inserting and querying data

 Public classDBTestextendsActivity {sqlitedatabase db; Button Bn=NULL;    ListView ListView; @Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.main);        Inittitle ();        InitData ();    Initview (); }     Public voidInittitle () {} Public voidInitData () {db= Sqlitedatabase.openorcreatedatabase ( This. Getfilesdir (). toString () + "/MY.DB3",NULL); Try{db.execsql ("CREATE Table News_inf (_id integer" + "PRIMARY key AutoIncrement," + "news_title varchar ()," + "NE Ws_content varchar (255)) "); } Catch(Exception e) {log.i ("TAG", "E---" +e); }    }     Public voidInitview () {ListView=(ListView) Findviewbyid (r.id.show); Bn=(Button) Findviewbyid (R.id.ok);        Querydata (); Bn.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View source) {String title=((EditText) Findviewbyid (R.id.title)). GetText (). toString (); String content=((EditText) Findviewbyid (r.id.content)). GetText (). toString (); Try {                    //Inserting Datainsertdata (DB, title, content);                Querydata (); } Catch(sqliteexception se) {}}}); }    //Inserting Data    Private voidInsertData (sqlitedatabase db, string title, string content) {//Execute INSERT statementDb.execsql ("INSERT into news_inf values (null,?,?)",Newstring[] {title, content}); }    //Querying Data    Private voidQuerydata () {cursor cursor= Db.rawquery ("SELECT * from News_inf",NULL); Simplecursoradapter Adapter=NewSimplecursoradapter (DBTest. This, R.layout.line, Cursor,Newstring[] {"News_title", "News_content"},New int[] {r.id.my_title, r.id.my_content}, Cursoradapter.flag_register_content_observer);    Listview.setadapter (adapter); } @Override Public voidOnDestroy () {Super. OnDestroy (); //Close Sqlitedatabase When exiting the program        if(db! =NULL&&Db.isopen ())        {Db.close (); }    }}

Demo2 Word Book

 Public classDictextendsActivityImplementsview.onclicklistener{Mydatabasehelper DBHelper; Button Insert=NULL; Button Search=NULL; @Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);                Setcontentview (R.layout.main);        Inittitle ();        InitData ();            Initview (); }         Public voidInittitle () {} Public voidInitData () {//Create a Mydatabasehelper object that specifies a database version of 1, where relative paths are used.//The database files are automatically saved in the databases directory of the program's Data folder. DBHelper =NewMydatabasehelper ( This, "Mydict.db3", 1); }     Public voidInitview () {Insert=(Button) Findviewbyid (R.id.insert); Search=(Button) Findviewbyid (R.id.search); Insert.setonclicklistener ( This); Search.setonclicklistener ( This); } @Override Public voidOnClick (View v) {Switch(V.getid ()) { CaseR.id.insert://InsertString Word =((EditText) Findviewbyid (R.id.word)). GetText (). toString (); String Detail=((EditText) Findviewbyid (R.id.detail)). GetText (). toString ();                        InsertData (Dbhelper.getreadabledatabase (), Word, detail);  Break;  CaseR.id.search://Search//Get user InputString key =((EditText) Findviewbyid (R.id.key)). GetText (). toString (); //Execute Querycursor cursor =dbhelper.getreadabledatabase (). Rawquery ("SELECT * from Dict where is word like?" Or detail like? ",                    Newstring[] {"%" + key + "%", "%" + key + "%" }); Bundle Data=NewBundle (); Data.putserializable ("Data", convercursortolist (cursor)); Intent Intent=NewIntent (Dict. This, Resultactivity.class);            Intent.putextras (data);            StartActivity (Intent);  Break; default:             Break; }    }    //Insert    Private voidInsertData (sqlitedatabase db, String Word, string detail) {Db.execsql ("INSERT into dict values (null,?,?)",Newstring[] {word, detail}); Toast.maketext (Dict. This, "Add new words to success!" ", 8000). Show (); }        //Query result Goto collection    protectedArraylist<map<string, string>>convercursortolist (cursor cursor) {ArrayList<map<string, string>> result =NewArraylist<map<string, string>>(); //traversing the cursor result set         while(Cursor.movetonext ()) {//storing data in a result set in ArrayListmap<string, string> map =NewHashmap<string, string>(); //Remove values from column 2nd, column 3rd in the query recordMap.put ("word", cursor.getstring (1)); Map.put ("Detail", cursor.getstring (2));        Result.add (map); }        returnresult; } @Override Public voidOnDestroy () {Super. OnDestroy (); //close sqlitedatabase in Mydatabasehelper when exiting the program        if(DBHelper! =NULL) {dbhelper.close (); }    }}
 Public classMydatabasehelperextendsSqliteopenhelper {FinalString create_table_sql = "CREATE TABLE dict (_id integer primary" + "key autoincrement, Word, detail)";  PublicMydatabasehelper (context context, String name,intversion) {        Super(Context, Name,NULL, version); } @Override Public voidonCreate (Sqlitedatabase db) {//automatically create tables when using the database for the first timeDb.execsql (Create_table_sql); } @Override Public voidOnupgrade (Sqlitedatabase db,intOldversion,intnewversion) {System.out.println ("--------OnUpdate called--------" + oldversion + "--->" +newversion); }}
 Public classResultactivityextendsActivity {List<map<string, string>>list; @Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);                Setcontentview (R.layout.popup);        Inittitle ();        InitData ();            Initview (); }         Public voidInittitle () {} Public voidInitData () {list= (list<map<string, string>>) getintent (). Getextras (). getserializable ("Data")); }     Public voidInitview () {ListView ListView=(ListView) Findviewbyid (r.id.show); Simpleadapter Adapter=NewSimpleadapter (resultactivity. This, List, R.layout.line,NewString[] {"word",        "Detail"},New int[] {r.id.word, r.id.detail});    Listview.setadapter (adapter); }        }

Code See https://github.com/huanyi0723/SQLiteDemo/

Android SQLite Database

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.