Android Multi-threaded Operation SQLite (SQLite solves database locked problem)

Source: Internet
Author: User

Reference http://blog.csdn.net/sdsxleon/article/details/18259973 very good

https://github.com/2point0/Android-Database-Locking-Collisions-Example Example

http://www.eoeandroid.com/forum.php?mod=viewthread&tid=333473

Http://bbs.51cto.com/thread-990260-1.html

With transactions, the speed will be very

Scenario 1:

SQLiteis essentially writing the data to a file, typically found under the app's package namexxx.dbthe file that hasRootpermission of the phone, which can be passedadb Shell, seedata/data/PackageName/databases/xxx.dbsuch a file.

we can learnSQLiteis a file-level lock: Multiple threads can read at the same time, but only one thread is written at a time. Androidprovides aSqliteopenhelperclass, addingJavalock mechanism in order to invoke.

if multithreading is read and written at the same time (this refers to different threads using differentHelperinstance), you will encounter the followingAndroid.database.sqlite.SQLiteException:database is lockedsuch an exception.
for such a problem, the solution isKeep single SQLite connection,Keep a singleSqliteopenhelperinstance, while adding a method to all database operationssynchronizedkey word.

Perfect solution to SQLite database locked or error 5:database locked problem

/** * @FileName: Databasehelper.java * @ProjectName: Sqlitepractice * @PakageName: Com.sqlitepractice.database * @Autho R:brant * @CreateDate: 2012-12-16 */package com.sqlitepractice.database;import Android.content.contentvalues;import Android.content.context;import Android.database.cursor;import Android.database.sqlite.sqlitedatabase;import Android.database.sqlite.sqliteopenhelper;import Android.provider.basecolumns;import android.util.Log;/** * @Module : Name of the Membership module * @Comments: Description * @Author: Brant * @CreateDate: 2012-12-16 * @ModifiedBy: Brant * @ModifiedDate: 2012-12-16 * @Modified: * 2012-12-16: Implement basic functions */public class Databasehelper extends Sqliteopenhelper {public static final String TAG = " Databasehelper ";p rivate static final String db_name =" Practice.db ";p rivate final static string Db_table_app =" APP ";p Riva Te static final int db_version = 1;private static final String Db_create_table_app = "CREATE TABLE" + Db_table_app + "(" + app_columns._id + "INTEGER PRIMARY KEY AutoinCrement, "+ app_columns. Package_name+ "NTEXT not NULL," + app_columns. App_name + "NTEXT not NULL," + app_columns. App_name_pinyin + "NTEXT," + app_columns. Class_name + "NTEXT not NULL);"; private static Databasehelper minstance;protected Databasehelper (context context) {Super (context, db_name, NULL, db_ VERSION);} Public synchronized static Databasehelper getinstance (context context) {if (minstance = = null) {minstance = new Databasehe Lper (context);} return minstance;} Public synchronized static void Destoryinstance () {if (minstance! = null) {Minstance.close ();}} @Overridepublic void OnCreate (Sqlitedatabase db) {db.execsql (Db_create_table_app);} @Overridepublic void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {//TODO auto-generated method Stub}publ IC synchronized int getcount () {LOG.D (TAG, "GetCount"); int count =-1; Cursor C = getreadabledatabase (). query (Db_table_app, NULL, NULL, NULL, NULL, NULL, NULL), if (C.movetofirst ()) {count = C.G Etcount ();} C.close (); c = Null;return COunt;} Public synchronized void Insert (String packagename, String applabel, string pinyin, String className) {log.d (TAG, "Insert" ); Contentvalues values = new Contentvalues (4); Values.put (App_columns. Package_name, PackageName); Values.put (App_columns. App_name, Applabel); Values.put (App_columns. App_name_pinyin, PINYIN); Values.put (App_columns. Class_name, ClassName); Getwritabledatabase (). Insert (Db_table_app, NULL, values);} public static class App_columns implements Basecolumns {public static final String package_name = "Package_name";p Ublic St  Atic final String app_name = "App_name";p ublic static final String app_name_pinyin = "App_name_pinyin";p ublic static final String class_name = "class_name";p ublic static final int id_index = 0;public static final int package_name_index = 1;publ IC static final int app_name_index = 2;public static final int app_name_pinyin_index = 3;public static final int Class_nam E_index = 4;}}

  

Package Com.sqlitepractice;import Java.util.arraylist;import Java.util.list;import android.app.activity;import Android.os.bundle;import Android.util.log;import Android.view.menu;import Com.sqlitepractice.database.databasehelper;public class Mainactivity extends Activity {private static final String TAG = "Mainactivity";p rivate static int sthreadcounter = 0; @Overridepublic void onCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); final int threadcount = 8;final List< thread> allthreads = new Arraylist<thread> (threadcount);D atabasehelper helper = databasehelper.getinstance ( This): for (int i = 0; i < ThreadCount; i++) {Allthreads.add (New Dbinsertthread (Helper, sthreadcounter++));} for (int i = 0; i < ThreadCount; i++) {Allthreads.add (New Fastselectthread (helper, sthreadcounter++, 50));} for (Thread thread:allthreads) {Thread.Start ();} Wait for all threads to complete before runningfor (Thread Thread:allthreaDS) {try {thread.join (); LOG.I (Thread.getname (), "collected");} catch (Interruptedexception e) {log.e (TAG, "interrupted", e);}} LOG.I (TAG, "All Threads finished!");} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (R.menu.activity_main, menu); return true;} Class Dbinsertthread extends Thread {private final String TAG = DbInsertThread.class.getSimpleName ();p rivate final Databa Sehelper mdbhelper;private int Mruncount;dbinsertthread (databasehelper helper, int runcount, int id) {SetName ( String.Format ("%1$s-%2$d", TAG, id)); mdbhelper = Helper;mruncount = Runcount; LOG.I (GetName (), helper.tostring ());} @Overridepublic void Run () {for (int i = 0; i < Mruncount; i++) {try {Mdbhelper.insert ("com.xx.xxxx", "Test", "Ceshi", "M Ainactivity ");} catch (Exception e) {log.e (GetName (), "Insert failed!!!, stopping writes", e); break;}} LOG.I (GetName (), "finished!");}} Class Fastselectthread extends Thread {private final String TAG = FastSelectThread.class.getSimpleName ();p rivateFinal databasehelper mhelper;private final int mCount; Fastselectthread (databasehelper helper, int id, int selectcount) {setName (String.Format ("%1$s-%2$d", TAG, id)); mhelper = Helper;mcount = selectcount > 0? selectcount:50; LOG.I (GetName (), helper.tostring ());} @Overridepublic void Run () {int count = 0;while (Count < MCount) {mhelper.getcount (); LOG.I (GetName (), "Start Wait"), try {thread.sleep ($);} catch (Interruptedexception e) {e.printstacktrace ();} LOG.I (GetName (), "End Wait"); count++;} LOG.I (GetName (), "finished!");}}}

  

Android Multi-threaded Operation SQLite (SQLite solves database locked problem)

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.