我已經實施了SQliteOpenHelper與單例模式,並且它工作良好,直到現在。但考慮到以下順序:數據隔離與服務和Singleton SQliteOpenHelper
- 片段開始交易,以更新記錄
- 服務被觸發,讀取更新的數據由於某種原因
- 交易失敗和被回滾
該服務將處理稍後回滾的未提交數據。所以看起來單身模式與服務耦合導致數據隔離問題。然而,我已經閱讀了很多推薦單身人士的帖子。在使用單例時如何處理這種情況?
public class MyApplication extends Application{
private static MyApplication instance;
public MyApplication(){
instance = this;
}
public static Context getContext(){
return instance;
}
}
public class LocalDBHelper extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "MyDB";
private static final String LOG_TAG = "LocalDBHelper";
private static LocalDBHelper instance = null;
/*private constructor to avoid direct instantiation by other classes*/
private LocalDBHelper(){
super(MyApplication.getContext(), DATABASE_NAME, null, DATABASE_VERSION);
}
/*synchronized method to ensure only 1 instance of LocalDBHelper exists*/
public static synchronized LocalDBHelper getInstance(){
if(instance == null){
instance = new LocalDBHelper();
}
return instance;
}
...
...
}
使用與交易:
SQLiteDatabase db = LocalDBHelper.getInstance().getWritableDatabase();
db.beginTransaction();
try{
....
...
db.setTransactionSuccessful();
}catch(Exception e){
e.printStackTrace();
}
finally{
db.endTransaction();
}
你應該檢查了這一點:http://blog.lemberg.co.uk/concurrent-database-access – 2014-11-04 09:28:59
@ user2247689謝謝我已閱讀同一文章在3個不同的網站:)但它不處理交易或隔離,所以與問題無關。 – faizal 2014-11-04 09:31:28
對不起,我沒有正確地閱讀這個問題。處理服務有點棘手,特別是當它們必須併發時。基本上我猜你會不得不使用'消息'?請參閱http://developer.android.com/guide/components/bound-services.html#Messenger – 2014-11-04 09:39:51