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