Android threading and database locking

后端 未结 7 1656
夕颜
夕颜 2020-12-07 10:31

We are using AsyncTasks to access database tables and cursors.

Unfortunately we are seeing occasional exceptions regarding the database being locked.

相关标签:
7条回答
  • 2020-12-07 11:25

    We could not share Db connection with multiple thread to perform read and write operation in database simultaniously.We will have to make single object of DB using syncronization concept and we will perform one task at a time .We will use singleton pattern to make the DB object and it will be share within multiple threads.At a time will perform single task . then we will start other task or any operation on DB . Content provider is not the solution of DB locking issue .

    import java.util.concurrent.atomic.AtomicInteger;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    import android.util.Log;
    
    public class DatabaseManager {
    
    private AtomicInteger mOpenCounter = new AtomicInteger();
    
    private static DatabaseManager instance;
    private static SQLiteOpenHelper mDatabaseHelper;
    private SQLiteDatabase mDatabase;
    //private static String DB_PATH = "";
    //  private static String DB_NAME = "xyz.db";// Database name
    private static String dbPathh;
    
    public static synchronized void initializeInstance(SQLiteOpenHelper helper,
            String dbPath) {
        if (instance == null) {
            instance = new DatabaseManager();
            mDatabaseHelper = helper;
            dbPathh=dbPath;
        }
      }
    
    public static synchronized DatabaseManager getInstance() {
        if (instance == null) {
            throw new IllegalStateException(DatabaseManager.class.getSimpleName() +
                    " is not initialized, call initializeInstance(..) method first.");
        }
    
        return instance;
     }
    
      public synchronized SQLiteDatabase openDatabase(String thread) {
    
        if(mOpenCounter.get() == 0) {
            // Opening new database
            // mDatabase = mDatabaseHelper.getWritableDatabase();
            MyLog.e("Path Of DataBase", dbPathh);
            //  mDatabase=mDatabaseHelper.getWritableDatabase();
            mOpenCounter.incrementAndGet();
            mDatabase=SQLiteDatabase.openDatabase(dbPathh, null,   
     SQLiteDatabase.  CREATE_IF_NECESSARY|SQLiteDatabase.OPEN_READWRITE);   
            MyLog.e("Open Data Base", " New Connection created" +thread);
        }
        else{
            MyLog.e("Open Data Base", " Old Connection given " +thread);
        }
        //  Toast.makeText(NNacres.getConfig(), "open conn: present connection = 
       "   +mOpenCounter.get(), Toast.LENGTH_LONG).show();
        return mDatabase;
       }
    
        public synchronized void closeDatabase() {
        MyLog.e("Close db connection", ""+mOpenCounter.get());
    
        if(mOpenCounter.get() == 1) {
            // Closing database
    
            mDatabase.close();
            mOpenCounter.decrementAndGet();
    
            Log.e("DB CLOSED", "DONE");
        }
        //Toast.makeText(NNacres.getConfig(), "close conn: after close =   
     " +mOpenCounter.get(), Toast.LENGTH_LONG).show();
        }
    
        }
    

    and write this method in your YourSQLiteDataABse helper class which extends SQLiteOpenHelper Class

         public SQLiteDatabase getWritableDatabase() {
    DatabaseManager.initializeInstance(this,"data/data/your packgae name/databases/xyz");
        return DatabaseManager.getInstance().openDatabase(getClass().getSimpleName());
    
    }
    
    
    
    public static String getMyDbPath(String DB_NAME, Context context) {
    
        String myDbPath = context.getDatabasePath(DB_NAME).getPath();
        MyLog.e("DB Path: "+myDbPath);
        return myDbPath;
    }
    
    0 讨论(0)
提交回复
热议问题