2016-11-02 2 views
0

처음으로 안드로이드 프로젝트에 GreenDAO를 사용하고 있는데 처음 사용자를 위해 데이터베이스를 시드하는 방법이 궁금합니다. 예를 들어 테이블이 있고 사용자를 대신하여 5 개의 행이 삽입되기를 원한다고 가정 해보십시오.시드의 GreenDao 데이터베이스가

또한 향후 업데이트에서 새 테이블을 추가하고 해당 테이블에 데이터를 시드 할 수 있지만 사용자가 새로운 버전의 스키마를 설치하더라도 다섯 번째 행이 첫 번째 테이블에 삽입되도록하려는 경우가 있습니다.

내 초기 생각은 내 App.onCreate() 메서드에서 수행 한 다음 시드가 이미 만들어 졌는지 여부와 같이 SharedPreferences에 플래그를 설정했지만 버그에 대한보다 실용적인 접근법을 찾을 수 없다는 버그가 있습니다. .

도움을 주시면 감사하겠습니다.

답변

1

나는 동일한 문제가 있었으며 웹 및 GreenDAO의 문서를 검색했지만 신뢰할만한 것을 찾지 못했습니다.

그래서 첫 번째 앱 실행에서 코드를 작성했습니다. 이렇게하려면 내 앱이 처음 시작되었는지 확인해야했습니다. 그 일을 위해 나는 this 답을 추천한다.

public static void checkFirstRun(Context context) { 

    final String PREFS_NAME = "TickTockPrefs"; 
    final String PREF_VERSION_CODE_KEY = "version_code"; 
    final int DOESNT_EXIST = -1; 

    // Get current version code 
    int currentVersionCode = 0; 

    try { 
     currentVersionCode = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode; 
    } catch (android.content.pm.PackageManager.NameNotFoundException e) { 
     // handle exception 
     e.printStackTrace(); 
     return; 
    } 

    // Get saved version code 
    SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); 
    int savedVersionCode = prefs.getInt(PREF_VERSION_CODE_KEY, DOESNT_EXIST); 

    // Check for first run or upgrade 
    if (currentVersionCode == savedVersionCode) { 

     // This is just a normal run 
     return; 

    } else if (savedVersionCode == DOESNT_EXIST) { 

     // TODO This is a new install (or the user cleared the shared preferences) 
     seed(context); 

    } else if (currentVersionCode > savedVersionCode) { 

     // TODO This is an upgrade 

    } 

    // Update the shared preferences with the current version code 
    prefs.edit().putInt(PREF_VERSION_CODE_KEY, currentVersionCode).apply(); 

} 

을 그리고 종자 방법 안에 당신은 당신이 삽입 원하는대로 쓸 수 있습니다 : 당신은 여기에 대답에서 코드를 볼 수 있습니다. 당신이 개체의 목록을 삽입 할 경우 insertInTx() 메소드 대신 삽입()를 사용하는 것이

public static void seed(Context context) { 

    DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "your-db", null); 
    SQLiteDatabase db = helper.getWritableDatabase(); 
    DaoMaster daoMaster = new DaoMaster(db); 
    DaoSession daoSession = daoMaster.newSession(); 

    Person person = new Person(); 
    person.setName("Jason"); 
    person.setFamily("Bourne"); 

    PersonDao personDao = daoSession.getPersonDao(); 
    personDao.insert(person); 
} 

참고 : 예를 들어 내가 데이터를 미리 채울하고자하는 "사람"실체를 말한다. 차이점은 here입니다.

나는 이것이 ORM seed 메소드와 다르다는 것을 알고 있지만 greenDAO 코드를 직접 조작하는 것을 제외하고는 다른 대안이 없다고 생각합니다.