I am really confused how I should be using threads in my Android applications for database interaction. There are too many resources and I don't know which to choose from. So I'm hoping to get more specific and focused advice on my particular situation so I have a starting point.
This is my database class structure, which works great so far:
public class DatabaseHelper extends SQLiteOpenHelper {
private static volatile SQLiteDatabase mDatabase;
private static DatabaseHelper mInstance = null;
private static Context mContext;
private static final String DB_NAME = "database.db";
private static final int DB_VERSION = 1;
private static final DB_CREATE_THINGY_TABLE = "CREATE TABLE blahblahblah...";
//other various fields here, omitted
public static synchronized DatabaseHelper getInstance(Context context) {
if (mInstance == null) {
mInstance = new DatabaseHelper(context.getApplicationContext());
try {
mInstance.open();
}
catch (SQLException e) {
e.printStackTrace();
}
}
return mInstance;
}
private DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
mContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DB_CREATE_THINGY_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
#Override
public void onConfigure(SQLiteDatabase db){
super.onConfigure(db);
db.setForeignKeyConstraintsEnabled(true);
}
public void open() throws SQLException {
mDatabase = getWritableDatabase();
}
public void close() {
mDatabase.close();
}
public long addNewThingy(String name) {
ContentValues values = new ContentValues();
values.put(DatabaseHelper.THINGY_COLUMN_NAME, name);
return mDatabase.insertWithOnConflict(DatabaseHelper.THINGY_TABLE, null, values, SQLiteDatabase.CONFLICT_IGNORE);
}
public Thingy getThingyById(long id) {
Cursor cursor = mDatabase.query(
DatabaseHelper.THINGY_TABLE, // table
new String[]{DatabaseHelper.THINGY_COLUMN_ID, DatabaseHelper.THINGY_COLUMN_NAME}, // column names
DatabaseHelper.THINGY_COLUMN_ID + " = ?", // where clause
new String[]{id + ""}, // where params
null, // groupby
null, // having
null); // orderby
cursor.moveToFirst();
Thingy thingy = null;
if (!cursor.isAfterLast()) {
String name = getStringFromColumnName(cursor, DatabaseHelper.THINGY_COLUMN_NAME);
thingy = new Thingy(id, name);
cursor.moveToNext();
}
cursor.close();
return thingy;
}
}
So any time I want access to the database I do mDatabaseHelper = DatabaseHelper.getInstance(context); and I am good to go. I don't make any explicit calls to open() or close() or anything like that. However right now I am making all my database calls on the UI thread, I believe (either in my onCreate or onCreateView methods or separate methods which don't invoke any new threads or anything).
How would I correctly make this threaded so that I am not performing database operations on the UI thread?
I figure I have to change all my database calls to basically do this:
Make any necessary edits to my database class first to ensure it will work properly in the event that multiple threads are trying to perform operations at the same time. I already tried by making my class a singleton (I think it's a singleton, anyway?) and using keywords like "volatile" and "synchronized" but maybe I am missing something somewhere.
Perform database operation in its own thread.
Somehow trigger additional code back in the appropriate function/activity/fragment that will execute once the database operation has completed.
Make this whole process versatile enough to where I can do it anywhere.
Am I making sense? Is this the right way to be going about all this? Is there a simple example you can make that can show me how to, for example, correctly do something like mThingy = mDatabaseHelper.getThingyById(id); or mDatabaseHelper.addNewThingy(someName); from a sample activity/fragment/etc using proper threading?
Simple solution using Threads
public class DatabaseHelper extends SQLiteOpenHelper {
//...
public void addNewThingyAsync(final String name, final Callback<Long> cb) {
new Thread(new Runnable(){
#Override
public void run(){
cb.callback(addNewThingy(name));
}
}).start();
}
private synchronized long addNewThingy(String name){
//implementation...
}
public void getThingyByIdAsync(final long id, final Callback<Thingy> cb) {
new Thread(new Runnable(){
#Override
public void run(){
cb.callback(getThingyById(id));
}
}).start();
}
private synchronized Thingy getThingyById(long id) {
//implementation...
}
public interface Callback<T> {
public void callback(T t);
}
}
Solution using AsyncTasks
Same as above with the following changes:
public class DatabaseHelper extends SQLiteOpenHelper {
//...
public void addNewThingyAsync(final String name, final Callback<Long> cb) {
new AsyncTask<Void, Void, Long>(){
#Override
protected Long doInBackground(Void... ignoredParams) {
return addNewThingy(name);
}
#Override
protected void onPostExecute(Long result) {
cb.callback(result);
}
}.execute();
}
//...
public void getThingyByIdAsync(final long id, final Callback<Thingy> cb) {
new AsyncTask<Void, Void, Thingy>(){
#Override
protected Thingy doInBackground(Void... ignoredParams) {
return getThingyById(id);
}
#Override
protected void onPostExecute(Thingy result) {
cb.callback(result);
}
}.execute();
}
//...
}
Calling (works with both approaches)
long mId = ...;
mDatabaseHelper = DatabaseHelper.getInstance(context);
mDatabaseHelper.getThingyByIdAsync(mId, new Callback<Thingy>{
#Override
public void callback(Thingy thingy){
//do whatever you want to do with thingy
}
});
How would I correctly make this threaded so that I am not performing
database operations on the UI thread?
Simply perform any database operations off the UI thread. A common technique involves an AsyncTask. For example:
public class GetThingyTask extends AsyncTask<Long, Void, Thingy> {
private Context context;
public AddTask(Context context){
this.context = context;
}
#Override
protected Thingy doInBackground(Long... ids) {
final long id = ids[0];
Cursor cursor = DatabaseHelper.getInstance(context).query(
DatabaseHelper.THINGY_TABLE,
new String[]{
DatabaseHelper.THINGY_COLUMN_ID,
DatabaseHelper.THINGY_COLUMN_NAME
},
DatabaseHelper.THINGY_COLUMN_ID + "=?",
new String[]{String.valueOf(id)},
null, null, null);
String name = null;
if (cursor.moveToFirst() && (cursor.getCount() > 0)) {
name = getStringFromColumnName(cursor, DatabaseHelper.THINGY_COLUMN_NAME);
}
cursor.close();
return new Thingy(id, name);
}
#Override
protected void onPostExecute(Thingy thingy) {
//Broadcast the Thingy somehow. EventBus is a good choice.
}
}
And to use it (inside, for example, an Activity):
new GetThingyTask(this).execute(id);
Related
I have created a screen that show a TextView and a ProgressBar. The ProgressBar represent to database creation and adding 1000++ data into SQLite using GSON. In order to achieve this, I have created three different files, LocalDBHelper (which is my db setup), GSONHandler (convert my JSON file into SQLite) and Loading (for my AsyncTask).
My problem is, that my ProgressBar is static, and it didn't show the progress of adding the data. I'm new to android development and clueless in proceeding with my code.
MainActivity.java
public class MainActivity extends AppCompatActivity implements Loading.LoadingTaskFinishedListener {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setupdb_delete);
LocalDBHelper mydb = LocalDBHelper.newInstance(this);
//check if db exist, delete db if exist
if (doesDatabaseExist(mydb.getDatabaseName()))
this.deleteDatabase(mydb.getDatabaseName());
ProgressBar progressBar = findViewById(R.id.progressBar);
new Loading(progressBar, this, this).execute("");
}
#Override
public void onTaskFinished() {
finish();
}
public boolean doesDatabaseExist(String databaseName) {
File dbFile = this.getDatabasePath(databaseName);
return dbFile.exists();
}
}
Loading.java
public class Loading extends AsyncTask<String, Integer, Integer> {
public interface LoadingTaskFinishedListener {
void onTaskFinished();
}
private LocalDBHelper mydb = null;
private final ProgressBar progressBar;
private Context mContext;
private final LoadingTaskFinishedListener finishedListener;
public Loading(ProgressBar progressBar, LoadingTaskFinishedListener finishedListener, Context context) {
this.progressBar = progressBar;
this.finishedListener = finishedListener;
this.mydb = LocalDBHelper.newInstance(context);
mContext = context;
}
#Override
protected Integer doInBackground(String... params) {
SQLiteDatabase sqLiteDatabase = mydb.getWritableDatabase();
GSONHandler.newInstance(mContext, sqLiteDatabase);
return 1234;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressBar.setProgress(values[0]);
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
finishedListener.onTaskFinished();
}
}
GSONHandler.java
public class GSONHandler {
static final String TAG = GSONHandler.class.getSimpleName();
private Context context;
private LocalDBHelper mydb;
private SQLiteDatabase sqLiteDatabase;
private static GSONHandler mGsonHandler = null;
public static GSONHandler newInstance(Context context, SQLiteDatabase sqLiteDatabase){
if (mGsonHandler == null){
mGsonHandler = new GSONHandler(context.getApplicationContext(), sqLiteDatabase);
}
return mGsonHandler;
}
private GSONHandler(Context context, SQLiteDatabase sqLiteDatabase) {
this.context = context;
this.sqLiteDatabase = sqLiteDatabase;
onCreate();
}
//assign json data to tables
private void onCreate() {
//get local json and save it to db
premiseCategoryMasterSetup();
premiseCategorySetup();
inspcTypeSetup();
inspcStatusSetup();
stateSetup();
areaSetup();
districtSetup();
analysisGroupSetup();
analysisSubGroup();
parameterSetup();
subParameterSetup();
identificationSetup();
premiseCertliSetup();
txn_premiseSetup();
prosecutionOtherSetup();
txn_layoutSectionSetup();
txn_layoutCardSetup();
txn_layoutInputFieldSetup();
}
private void areaSetup() {
Log.d(TAG, "areaSetup");
InputStream inputStream = context.getResources().openRawResource(R.raw.ref_area);
String jsonString = readJsonFile(inputStream);
Gson gson = new Gson();
List<Area> areaList = Arrays.asList(gson.fromJson(jsonString, Area[].class));
for (Area area : areaList)
{
if(sqLiteDatabase != null) {
ContentValues values = new ContentValues();
values.put(Constants.COLUMN_AREA_ID, area.getAreaId());
values.put(Constants.COLUMN_AREA_CODE, area.getAreaCode());
values.put(Constants.COLUMN_AREA_NAME, area.getAreaName());
values.put(Constants.COLUMN_ACTIVE, area.getActive());
values.put(Constants.COLUMN_FK_STATE_ID, area.getFk_stateId());
long id = sqLiteDatabase.insertOrThrow(Constants.REF_AREA_TABLE,
null, values);
}
}
}
....
private String readJsonFile(InputStream inputStream) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte bufferByte[] = new byte[1024];
int length;
try {
while ((length = inputStream.read(bufferByte)) != -1) {
outputStream.write(bufferByte, 0 , length);
}
outputStream.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return outputStream.toString();
}
}
You are setting the progress of the progress bar inside onProgressUpdate method but it is never called. To call onProgressUpdate method, you need to call publishProgress method inside doInBackground method. The onProgressUpdate method is invoked on the UI thread after the call to publishProgress method.
In doInBackground() call publishProgress(); method to display and update progressbar. Hope this will Help.
This is my situation:
I have a GridLayout (wich has some textviews in some cells of it right at the begining of the activity, but i will change it to generate those textviews dynamically later) and I want to place some textViews in a few cells of it.
The problem: I don't know how many textViews I will need. It depends of the information of the database. Besides, I don't know how to add the textViews generated to the gridLayout from an AsyncTask.
So, i've been looking for some answers but I couldn't make it work. I tried something like this, but is not exactly what i'm looking for (i create a new TextView, but can't add it to the gridLayout from that thread).
This is the workflow of my app:
1º I start the activity with the gridLayout. It has some textViews:
This is the main Activity:
public class MostrarProyectos extends AppCompatActivity {
private final String TAG = "MostrarProyectos";
//Para obtener de un hilo no principal los proyectos:
public static ArrayList<Proyecto> listaDeProyectos = new ArrayList<>();
public GridLayout grid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mostrar_proyectos);
grid = (GridLayout) findViewById(R.id.grid);
EstrategiaObtenerObjetoDB e = FabricaEstrategiaObtenerDB.getInstance().construirEstrategia("proyecto", this); //This is a Fabric, wich obtains a Strategy
e.execute(this.getApplicationContext(), "proyecto", this, this.grid);//I sended a lot of things to test if something gives result
}
}
2º In that main class, I started a new Thread with AsyncTask, to get data from a SQLite DB.
This is the Fabric:
public class FabricaEstrategiaObtenerDB {
private static final FabricaEstrategiaObtenerDB ourInstance = new FabricaEstrategiaObtenerDB();
public static FabricaEstrategiaObtenerDB getInstance() {
return ourInstance;
}
private FabricaEstrategiaObtenerDB() {}
public EstrategiaObtenerObjetoDB construirEstrategia(String tabla, Activity acti){
switch(tabla){
//Some other cases
case "proyecto":
EstrategiaObtenerObjetoDBProyecto p = new EstrategiaObtenerObjetoDBProyecto(acti, new onTextViewCreatedListener() {
#Override
public void onTextViewCreated(TextView tv) {
//I don't know what to do here
}
}); //This code I tried from the other stackOverflow answer
return p;
default:
return null;
}
}
}
This an abstract class to obtain objects from the DB:
public abstract class EstrategiaObtenerObjetoDB extends AsyncTask<Object, Void, ArrayList<Object>> {
protected onTextViewCreatedListener onTextViewCreatedListener; //part of the code from the other StackOverflow user.
Activity miActividad;
public EstrategiaObtenerObjetoDB(Activity act, onTextViewCreatedListener onTextViewCreatedListener){
this.onTextViewCreatedListener = onTextViewCreatedListener; //This is too code from the other user.
this.miActividad = act;
}
#Override
protected ArrayList<Object> doInBackground(Object... params) {
AppDbHelper mDbHelper = new AppDbHelper(miActividad.getApplicationContext());
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String[] projection = obtenerSelect();
Cursor c = armarQuery(db, (String)params[1], projection); //params[1] is the name of the table in the DB
ArrayList<Object> arrayDeObjetos = new ArrayList<>();
try{
arrayDeObjetos.add(miActividad.getApplicationContext());//add the context
arrayDeObjetos.add(miActividad.findViewById(R.id.grid));//add the grid
armarObjetos(c);
return arrayDeObjetos;
}catch (Exception e){
String b = e.getMessage();
return null;
}
}
#Override
protected abstract void onPostExecute(ArrayList<Object> objects);
protected abstract String[] obtenerSelect();
protected abstract Cursor armarQuery(SQLiteDatabase db, String tabla, String[] projection);
protected abstract void armarObjetos(Cursor c);
}
And this is the specific Strategy:
public class EstrategiaObtenerObjetoDBProyecto extends EstrategiaObtenerObjetoDB {
public EstrategiaObtenerObjetoDBProyecto(Activity act,onTextViewCreatedListener onTextViewCreatedListener) {
super(act,onTextViewCreatedListener);
}
#Override
protected String[] obtenerSelect() {
String[] projection = {
AppContract.Proyecto._ID,
AppContract.Proyecto.COLUMN_NOMBRE,
AppContract.Proyecto.COLUMN_DESCRIPCION,
AppContract.Proyecto.COLUMN_PRIORIDAD,
AppContract.Proyecto.COLUMN_ANIO,
AppContract.Proyecto.COLUMN_MES,
AppContract.Proyecto.COLUMN_SEMANA,
AppContract.Proyecto.COLUMN_DURACION,
};
return projection;
}
#Override
protected Cursor armarQuery(SQLiteDatabase db, String tabla, String[] projection) {
Cursor cursor = db.query(
tabla,
projection,
null,
null,
null,
null,
null
);
return cursor;
}
#Override
protected void armarObjetos(Cursor c) {
c.moveToFirst();
ArrayList<Object> proyectos = new ArrayList<>();
do {
try{
String nombre = c.getString(c.getColumnIndex(AppContract.Proyecto.COLUMN_NOMBRE));
String descripcion = c.getString(c.getColumnIndex(AppContract.Proyecto.COLUMN_DESCRIPCION));
String prioridad = c.getString(c.getColumnIndex(AppContract.Proyecto.COLUMN_PRIORIDAD));
String anio = c.getString(c.getColumnIndex(AppContract.Proyecto.COLUMN_ANIO));
String mes = c.getString(c.getColumnIndex(AppContract.Proyecto.COLUMN_MES));
String semana = c.getString(c.getColumnIndex(AppContract.Proyecto.COLUMN_SEMANA));
String duracion = c.getString(c.getColumnIndex(AppContract.Proyecto.COLUMN_DURACION));
Proyecto p = new Proyecto(nombre,descripcion, prioridad, anio, mes, semana, duracion);
MostrarProyectos.listaDeProyectos.add(p);
proyectos.add(p);
}catch(Exception e){
Log.d("EstrategiaObtenerPr",e.getMessage());
}
} while (c.moveToNext());
}
#Override
protected void onPostExecute(ArrayList<Object> objects) {
MostrarProyectos.listaDeProyectos.add((Proyecto)objects.get(i));
GridLayout grid = (GridLayout) miActividad.findViewById(R.id.grid);
if(!MostrarProyectos.listaDeProyectos.isEmpty()){
for(int numeroTemporal = 0; numeroTemporal<MostrarProyectos.listaDeProyectos.size();numeroTemporal++){
Proyecto j = MostrarProyectos.listaDeProyectos.get(numeroTemporal);
TextView text = new TextView(miActividad.getApplicationContext());
text.setText(j.getNombre());
int numFila = MostrarProyectos.contarFilas(j.getMes(), j.getSemana());
GridLayout.LayoutParams params3 = new GridLayout.LayoutParams();
params3.rowSpec = GridLayout.spec(numFila);//,Integer.parseInt(j.getDuracion())
Log.d("MostrarProyecto", numFila+","+Integer.parseInt(j.getDuracion()));
params3.columnSpec = GridLayout.spec(3);
text.setLayoutParams(params3);
try{
if(onTextViewCreatedListener!=null){
onTextViewCreatedListener.onTextViewCreated(text);//from the other user
}
}catch (Exception excepcion){
Log.d("MostrarProyecto", excepcion.getMessage());
}
}
}
else{
Toast.makeText(miActividad.getApplicationContext(),"No hay proyectos",Toast.LENGTH_LONG);
}
MostrarProyectos.terminoCargaDatos = true;
}
}
3º After I get the data, I want to generate as many TextViews as objects i've got from the DB, so I use a 'for' to see how many objects i have inside a temporal list i created. For heach object, I want to create a TextView, and add it to the gridLayout (that is on the main thread).
And finally, an interface from the other answer:
public interface onTextViewCreatedListener {
public void onTextViewCreated(TextView tv);
}
I hope you can help me. Thank you.
EDIT_1: I need to use other thread different from the UI thread because i need to search in the DB the data.
You have to split your logic, search data in the DB in AsyncTask or simple new Thread() and then create UI elements and attach them in UI thread.
mActivity
.runOnUiThread(
new Runnable() {
#Override
public void run() {
//create a TextView, and add it to the gridLayout
}
});
I am a little confused how to do this properly. Here is my DatabaseHelper class:
public class DatabaseHelper extends SQLiteOpenHelper {
private static DatabaseHelper mInstance = null;
private static final String DB_NAME = "database.db";
private static final int DB_VERSION = 1;
private Context mContext;
public static DatabaseHelper getInstance(Context context) {
if (mInstance == null) {
mInstance = new DatabaseHelper(context.getApplicationContext());
}
return mInstance;
}
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
mContext = context;
}
...
Assuming this is right, is this the correct way to handle the querying class:
public class DatabaseProcessor {
private SQLiteDatabase mDatabase;
private DatabaseHelper mSQLHelper;
private Context mContext;
public DatabaseProcessor(Context context) {
mContext = context;
mSQLHelper = new DatabaseHelper(mContext);
}
private void open() throws SQLException {
mDatabase = mSQLHelper.getWritableDatabase();
}
private void close() {
mDatabase.close();
}
public void insertSomethingIntoDb(String key) {
ContentValues values = new ContentValues();
values.put("some_column_name", name);
open();
mDatabase.insert("some_table_name", null, values);
close();
}
...
And if this is right, how do I properly invoke a db method from somewhere else in the code such as an Activity, Fragment, etc, anywhere.
You should make the DatabaseHelper constructor private and create instances of this class by using the getInstance method. eg: mSQLHelper = DatamabseHelper.getInstance(context).
To call a method of this class, you can do something like this.
DatabaseHelper.getInstance(context).someFunction(...);
And to use any of the DatabaseProcessor functions, you can do this:
new DatabaseProcessor(context).insertSomethingIntoDb(...);
Keep in mind that this singleton approach has some problems, for starters, it doesn't support multithreading, there is no mechanism in place to assure that if two threads ask for an instance at the same time, only one instance will be created.
I have no idea how to do proper concurrent operations, so I just tried to adjust my code.
And totally lost in concurrency in constructor and concurrency with static, final fields...
public static class Connection {
private final CustomerDatabaseOpenHelper mHelper;
private SQLiteDatabase mDatabase;
private String mUserId;
private AtomicInteger mOpenCounter;
public Connection(Context context, String userId) {
mHelper = CustomerDatabaseOpenHelper.getInstance(context, DB_NAME, null, DB_VERSION);
mOpenCounter = mHelper.mOpenCounter;
mUserId = userId;
}
public void open() throws SQLException {
// open database in reading/writing mode
int value = mOpenCounter.incrementAndGet();
if(value == 1 || mDatabase==null || mUserId ==null) {
// Opening new database
Log.v("tugce","open new customer db");
mDatabase = mHelper.getWritableDatabase();
}
};
public void close() {
int value = mOpenCounter.decrementAndGet();
if(value == 0) {
// Closing database
if (mDatabase != null) {
try {
Log.v("tugce","close customer db");
mDatabase.close();
mDatabase = null;
mUserId = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
//my openhelper class
public class CustomerDatabaseOpenHelper extends SQLiteOpenHelper{
public AtomicInteger mOpenCounter = new AtomicInteger();
public static CustomerDatabaseOpenHelper mInstance;
public static synchronized CustomerDatabaseOpenHelper getInstance(Context context, String name,
CursorFactory factory, int version) {
if (mInstance == null) {
mInstance = new CustomerDatabaseOpenHelper(context, name, factory, version);
}
return mInstance;
}
private CustomerDatabaseOpenHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
}
This is how I am using in threads:
class MyGetPlanedCallList extends
AsyncTask<Object, Object, List<MyPlannedCallListItem>> {
CustomerDatabase.Connection mDbCon = new CustomerDatabase.Connection(InstanceActivity.this, mUserId);
#Override
protected void onPreExecute() {
mDbCon.open();
}
#Override
protected List<MyPlannedCallListItem> doInBackground(Object... params) {
mDbCon.doSomeStuff();
}
#Override
protected void onPostExecute(List<MyPlannedCallListItem> result) {
mDbCon.close();
}
#Override
protected void onCancelled() {
if (mDbCon != null)
mDbCon.close();
}
}
What I want is, exactly same db shouldn't be closed if some other instance is working on it.
Any help would be appreciated.
I want to make my Database operation in a spread thread, so first I make a ThreadLooper, which will be used to post Runnables, that are starting DB operations.
It looks like this:
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.HandlerThread;
import android.os.Message;
/**
* #author
* #version 1.0 This class is used as ThreadLooper to make the database
* operation CRUD , this looper is singlton across the app
*
*/
public class DBThreadLooper extends HandlerThread {
public Handler mHandler;
private DBThreadLooper(String name) {
super(name);
}
private static DBThreadLooper mInstance;
public static DBThreadLooper newInstance() {
if (mInstance == null) {
mInstance = new DBThreadLooper("DATA BASE THREAD LOOPER ");
mInstance.start();
}
return mInstance;
}
#Override
public synchronized void start() {
super.start();
waitUntilReady();
}
private void waitUntilReady() {
mHandler = new Handler(getLooper(), new Callback() {
public boolean handleMessage(Message msg) {
return true;
}
});
}
#Override
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}
Now I have this method that will make a DB operation
private void handleFavButton() {
int index = viewPager.getCurrentItem();
Cursor c = mAdapter.getAdapterCursor();
c.moveToPosition(index);
final String quote_id = c.getString(c.getColumnIndex(QuoteTableMetaData._ID));
final int is_fav = c.getInt(c.getColumnIndex(QuoteTableMetaData.C_IS_FAVORITE));
if(is_fav == 0){
DBThreadLooper looper = DBThreadLooper.newInstance();
looper.mHandler.post(new Runnable() {
public void run() {
//1. make it 1
QuoteTableMetaData qTable = QuoteTableMetaData
.getInstance();
ContentValues values = new ContentValues();
values.put(QuoteTableMetaData.C_IS_FAVORITE, new Integer(1));
qTable.update(DBUtils.getDBHelper(getApplicationContext())
.getWritableDatabase(), values,
QuoteTableMetaData._ID + "= ?",
new String[] { quote_id });
//2. insert a new record in Fav Table with the id
FavouriteQuoteTable fTable = FavouriteQuoteTable
.getInstance();
values.clear();
values.put(FavouriteQuoteTable.C_QUOTE_ID, quote_id);
fTable.insert(DBUtils.getDBHelper(getApplicationContext())
.getWritableDatabase(), null, values);
}
});
}
else{
DBThreadLooper looper = DBThreadLooper.newInstance();
looper.mHandler.post(new Runnable() {
public void run() {
//1.make it 0
QuoteTableMetaData qTable = QuoteTableMetaData
.getInstance();
ContentValues values = new ContentValues();
values.put(QuoteTableMetaData.C_IS_FAVORITE, new Integer(0));
qTable.update(DBUtils.getDBHelper(getApplicationContext())
.getWritableDatabase(), values,
QuoteTableMetaData._ID + "=?",
new String[] { quote_id });
// 2. delete record with id from fav Table
FavouriteQuoteTable fTable = FavouriteQuoteTable
.getInstance();
fTable.delete(DBUtils.getDBHelper(getApplicationContext())
.getWritableDatabase(),
FavouriteQuoteTable.C_QUOTE_ID + "=?",
new String[] { quote_id });
}
});
}
Do I need to make quote_id and is_favin the method volatile, so that my method will not run into synchronization problems.
No mutlithread problem with them: they are local variables (furthermore final). This means that every call to the method handleFavButton will have separate instances of them and the different calls accessing the variables will not interfere.