2

In my Android app, the user can receive notifications than contain a serial number that I want to store in my SQLite database. However, I saw that it may be unsafe to write in the database within the Service, as it can compete with others instances of it in the current Activity.

Is it really unsafe to write in the database within a Service? Is there any workaround for that?

Gannicus
  • 169
  • 2
  • 10

3 Answers3

1

No, it is not unsafe if you use the same DB connection instance.

Reference

Community
  • 1
  • 1
m0skit0
  • 25,268
  • 11
  • 79
  • 127
1

I dont know what you exactly mean with "as it can compete with others instances of it" . Just create a service with a method that updates your database and start it (and stop it after the job is done) whenever you need it.

Quark
  • 402
  • 4
  • 15
0

Implement your SQLiteOpenHelper as a singleton.

public class MyDatabaseHelper extends SQLiteOpenHelper {

    private static MyDatabaseHelper instance;

    public static MyDatabaseHelper getInstance(Context context){
        if ( instance == null ){
            instance = new MyDatabaseHelper(context);
        }
        return instance;
    }

}

Look into SQLite Write-Ahead Logging

There are advantages and disadvantages to using WAL instead of a rollback journal. Advantages include:

  1. WAL is significantly faster in most scenarios.
  2. WAL provides more concurrency as readers do not block writers and a writer does not block readers. Reading and writing can proceed concurrently.
  3. Disk I/O operations tends to be more sequential using WAL.
  4. WAL uses many fewer fsync() operations and is thus less vulnerable to problems on systems where the fsync() system call is broken.

Source: https://www.sqlite.org/wal.html

Android (API level 11+):

The best way to enable write-ahead logging is to pass the ENABLE_WRITE_AHEAD_LOGGING flag to openDatabase(String, SQLiteDatabase.CursorFactory, int). This is more efficient than calling enableWriteAheadLogging().

SQLiteDatabase db = SQLiteDatabase.openDatabase("db_filename", cursorFactory,
    SQLiteDatabase.CREATE_IF_NECESSARY |
    SQLiteDatabase.ENABLE_WRITE_AHEAD_LOGGING,
    myDatabaseErrorHandler);

db.enableWriteAheadLogging();

Source http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#enableWriteAheadLogging()

ejohansson
  • 2,832
  • 1
  • 23
  • 30