2011-04-26 3 views
5

SQLite 구현을 향상시킬 계획입니다. 현재 관련 데이터가 필요할 때마다 SQLite DB가 열리고 활동이 닫힙니다. 예외를 피하려면 DB 닫기가 중요합니다.스레드 안전 읽기/쓰기 액세스를위한 SQLite Manager를 구현하려면?

내 설계 목표 : 나는 내가 할 것이라고 생각 무엇 응용 프로그램의 SQLite는 DB

  • 동기 운전

    1. 스레드 안전하게 접근은 어떤 종류의 구현입니다 기본 "SQLhelper"클래스 대신 "Manager"클래스. 동기 동작을 원하여 메시지로 서비스로 구현하는 것을 배제해야합니다.

      이 "SQLiteManager"를 구현하는 가장 좋은 방법은 싱글 톤이라고 생각합니다.

      더 좋은 구현이 있습니까?

    +0

    은 [컨텐트 프로] (http://developer.android.com/reference/android/content/ContentProvider.html는) – Selvin

    +0

    컨텐트 프로는 겉으로는 과잉이다 이 앱은 다른 앱과 공유 할 필요가 없으므로 나는 내 솔루션을 만들기 위해 다음과 같은 영감을 받았다. (나는 곧 솔루션의 해골을 게시 할 것이다) http://stackoverflow.com/questions/987072/using-application-context-everywhere –

    답변

    10

    1 단계 - 확장 Application 클래스

    import android.app.Application; 
    import android.content.Context; 
    
    /** 
    * This class is created automatically when the app launches. 
    * It is used to provide an application-level context for the SQLiteOpenHelper 
    */ 
    public class ApplicationContext extends Application 
    { 
    
        private static ApplicationContext instance; 
    
        public ApplicationContext() 
        { 
         instance = this; 
        } 
    
        public static Context getContext() 
        { 
         return instance; 
        } 
    
    } 
    

    2 단계 -이 응용 프로그램 클래스가를 사용되도록 매니페스트를 업데이트

    <application android:name="ApplicationContext" 
          android:icon="@drawable/icon" 
          android:label="@string/app_name" 
          android:debuggable="true"> 
    

    3 단계 - 싱글을 구축 SQLdataHelper 앱에

    0 개

    예제 삽입 작업이 하나만 포함되었습니다. 필요한만큼 추가하고 단순히 '동기화 된'방법인지 확인하십시오.

    4 단계 - 활동에 SQLdataHelper을 사용

    SQLdataHelper mDataHelper = SQLdataHelper.getInstance(); 
        mDataHelper.insertTableA("Someone", 100); 
    
    +0

    메소드는 동기화되어야한다 ? 나는 데이터베이스가 쓰레드 안전하다고 생각했다. – JonWells

    +1

    SQLite DB가 스레드 안전하다고 읽었지만 synchronized를 사용하지 않고 문제가 발생했습니다. –

    +0

    이 메서드를 SQLdataHelper 클래스에 추가하는 것이 맞습니까? 보호 된 void finalize() throws Throwable { 시도하십시오 { mDatabaseHelper.close(); } 마지막으로 { super.finalize(); } } – petrnohejl