Error at runtime: caused by android.database.sqlite.sqliteexception error code 5 database is locked
 
I have encountered the above mentioned error, when I am calling asyncTask  constructor from my activity again and again for saving the image in external database. In the asyncTask, I am opening the  database and after doing some stuff, I am closing the database.Parallely, I am  running a service from activity which is also doing some database work.
My Code is like this:

Class MyActivity extends Activity{
CommunicationWithDBCls communic=new CommunicationWithDBCls();

call(){

imgAsynTask = new ImageShowAsyncTask(this, imgUrlAryLi, count,
                    this, progress);
            imgAsynTask.execute();
}
}

And

public class ImageShowAsyncTask extends AsyncTask<Void, String, Bitmap> {
CommunicationWithDBCls communic=new CommunicationWithDBCls(); 
public ImageShowAsyncTask(CallBackInterFace callBackInterface,
            ArrayList<String> arryLisUrl, int count, Context cont,
            ProgressBar progress) {

// some stuff
}

@Override
    protected Bitmap doInBackground(Void… paramArrayOfParams) {

try{
//some stuff related to getting image from server n saving it to DB
}catch(Exception e){

}finally{
communic.close();
}

}
        
}

Sometimes, the code is giving the error as:
caused by android.database.sqlite.sqliteexception error code 5 database is locked
 
I broke my head in getting rid of this problem but finally I solved it. 🙂
 
I got rid off the above problem when I did a little change in my code. Instead of opening and closing the database
inside the asyncTask, I just passed the reference of my database class while calling the constructor of asyncTask from 
the activity.

the correct Code is like this:

Class MyActivity extends Activity{
CommunicationWithDBCls communic=new CommunicationWithDBCls(); 
call(){

imgAsynTask = new ImageShowAsyncTask(this, imgUrlAryLi, count,
                    this, progress,communic);
            imgAsynTask.execute();
}
}

And

public class ImageShowAsyncTask extends AsyncTask<Void, String, Bitmap> {

CommunicationWithDBCls communic;
public ImageShowAsyncTask(CallBackInterFace callBackInterface,
            ArrayList<String> arryLisUrl, int count, Context cont,
            ProgressBar progress, CommunicationWithDBCls communic2) {

//some stuff
}

@Override
    protected Bitmap doInBackground(Void… paramArrayOfParams) {

try{
//some stuff related to getting image from server n saving it to DB
}catch(Exception e){

}

}
        
}

Now, it’s working good and I am enjoying with my work 🙂 …
Hope it will work for others too…
 
-By Arvind Kaushal
Android Developer