Android database optimization and Android database Optimization
1. Optimize database insertion through one compilation and transaction, and optimize database query by querying only specified fields.
/*** <Ol> <li> open database * <li> Create sentence (avoid String + String) * <li> compile (avoid multiple compilations) * <li> run * <li> close database </ol> * @ author shixin */public class MainActivity extends Activity {List <String> list = new category List <String> (); arrayAdapter <String> arrayAdapter; SQLiteDatabase db; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); ListView listVi Ew = (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 will be destroyed when the database is closeddb = SQLiteDatabase. create (null); // Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns datadb. ExecSQL ("create table life (plant text, animal text)") ;}@ Overrideprotected void onDestroy () {super. onDestroy (); db. 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.exe cuteInsert ();} db. setTransactionSuccessful ();} catch (Exception e) {} finally {db. endTransaction ();} break; case R. id. btn_query: // only query the required fields more efficiently. Cursor c = db. query ("life", new String [] {"plant"}, null, null); while (c. moveToNext () {list. add (c. getString (c. getColumnIndex ("plant");} c. close (); // make the ListView update display arrayAdapter. notifyDataSetChanged ();}}}