Optimization of Android Database

Source: Internet
Author: User

1. Optimize database insertions with a single compilation and transaction to optimize database queries by querying only the specified fields.

/** * <ol><li> Open Database * <li> create sentences (avoid string+string) * <li> compile (avoid multiple compilations) * <li> Execute * <li> Close Database </ol> * @author shixin */public class Mainactivity extends Activity {list<string> List = new LINKEDLIST&L T String> (); Arrayadapter<string> Arrayadapter; Sqlitedatabase db; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); ListView ListView = (ListView) Findviewbyid (R.id.listview); arrayadapter = new Arrayadapter<string> (This, Android . R.layout.simple_list_item_1, list); Listview.setadapter (arrayadapter);//create a memory backed SQLite database. Its contents would be destroyed if the database is CLOSEDDB = Sqlitedatabase.create (null);//execute a single SQL statemen T that's not a SELECT or any other SQL statement this returns DATADB.EXECSQL ("CREATE Table life (plant text, animal text) ");} @Overrideprotected void OnDestroy () {Super.ondestroy ();d b.close ();} Public VOID OnClick (View v) {switch (V.getid ()) {case R.id.btn_insert:try {db.begintransaction (); String[][] Lifes = {{"potato", "tomato", "apple"}, {"Rat", "cat", "Dog"}}; Sqlitestatement stmt = db.compilestatement ("INSERT into life values (?,?)"); for (int i=0;i<lifes[0].length;i++) {stmt.clearbindings (); stmt.bindstring (1, lifes[0][i]); stmt.bindstring (1, Lifes[1][i]); Stmt.executeinsert ();} Db.settransactionsuccessful ();} catch (Exception e) {}finally{db.endtransaction ();} Break;case r.id.btn_query://only queries needed fields more efficiently cursor c = db.query ("Life", new string[]{"Plant"}, NULL, NULL, NULL, NULL, NULL); while (C.movetonext ()) {List.add (c.getstring (C.getcolumnindex ("Plant"));} C.close ();//Let ListView Update Show Arrayadapter.notifydatasetchanged ();}}}

Optimization of Android 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.