-1

I am creating a Service in which there are three Threads :

  • GPS location tracker that will write location values into a database.
  • Sender Thread that both reads and writes into the database.
  • Receiver thread that too reads and writes to the database.

Now I have seen posts like these in which it is said that only one Helper class should be available as well as only on DB connection. I have tried to implement only one instance of the Helper class by using the Singleton pattern however I am utterly confused about how to go about creating only one DB connection that can achieve the three tasks I mentioned earlier. Here's my implementation of the Helper class.

package com.example.userpc.roadtracker;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
  * Created by USER PC on 5/21/2016.
*/
public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME="location_service.db";
    private static final int VERSION=1;
    private static final String DB_CREATE="CREATE TABLE `location_service`.`location` ( `id` INT NOT NULL AUTO_INCREMENT , `longitude` DOUBLE NOT NULL , `latitude` DOUBLE NOT NULL , PRIMARY KEY (`id`), UNIQUE (`longitude`, `latitude`)) ENGINE = MyISAM;";

    private static SQLiteDatabase mDatabase=null;
    private static DatabaseHelper mDatabaseHelper=null;

    private DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, VERSION);
    }

    public static DatabaseHelper getInstance(Context context)
    {
        if(mDatabaseHelper==null)
             return new DatabaseHelper(context);
        else
             return mDatabaseHelper;
    }

    public SQLiteDatabase getUsableDataBase()
    {
        if(mDatabase==null)
            return this.getWritableDatabase();
        else
            return mDatabase;
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL(DB_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}

Thanks in advance.

Community
  • 1
  • 1
Sourav Kanta
  • 2,727
  • 1
  • 18
  • 29

1 Answers1

1

No, you still need to synchronize the blocks of your code in which you are accessing your SQLiteOpenHelper instance.

It will be a single instance with a Singleton, but that doesn't mean 2 threads are not going to be able to access the same instance.

John Roberts
  • 467
  • 3
  • 5