Hello,
I have two parts of a program (the actual app and a BroadcastReceiver) that could possibly try to connect to and modify a SQLite database and a SharedPreferences file.
1) I know you can make multiple connections to a single SQLite database. I also read that SQLite can "lock" the database when it attempts to modify or read from a database (UPDATE, INSERT, etc), so how do I properly handle the case where 2 threads try to modify/read a single SQLite database at the same time?
Right now, I have have this code snippet in my database connection code/class:
private SQLiteDatabase myDatabase;
public boolean insert(ContentValues columnValueMap) throws Exception
{
long result = 0;
int attempt =0;
do
{
if(!myDatabase.isDbLockedByOtherThreads() && !myDatabase.isDbLockedByCurrentThread())
{
synchronized (myDatabase)
{
result=myDatabase.insertOrThrow(TABLE_NAME, TEXT, columnValueMap);
if(result ==0 || result == -1)
{
return false;
}
return true;
}
}
else
{
Thread.sleep(50);
}
attempt++;
}while(attempt<=5);
throw new Exception("Database Locked!");
}
2) Do I also have to worry about simultaneous access for a SharedPreferences file (It doesn't matter which thread gets access first, I'm just worried about errors being thrown)?
Thanks.
[EDIT] Proposed change
public boolean insert(ContentValues columnValueMap) throws Exception
{
long result = 0;
synchronized (myDatabase)
{
result=myDatabase.insertOrThrow(TABLE_NAME, SMS_TEXT, columnValueMap);
if(result ==0 || result == -1)
{
return false;
}
return true;
}
}