Android: SQLite one-to-many design

前端 未结 3 861
情歌与酒
情歌与酒 2020-12-13 22:49

Anyone has good advise on how to implement one-to-many mapping for SQLite using ContentProvider? If you look at Uri ContentProvider#insert(Ur

3条回答
  •  臣服心动
    2020-12-13 23:12

    So I'm going to answer my own question. I was on the right track with having two tables and two model objects. What was missing and what confused me was that I wanted directly insert complex data through ContentProvider#insert in a single call. This is wrong. ContentProvider should create and maintain these two tables but decision on which table to use should be dictated by Uri parameter of ContentProvider#insert. It is very convenient to use ContentResolver and add methods such as "addFoo" to the model object. Such method would take ContentResolver parameter and at the end here are the sequence to insert a complex record:

    1. Insert parent record through ContentProvider#insert and obtain record id
    2. Per each child provide parent ID (foregn key) and use ContentProvider#insert with different Uri to insert child records

    So the only remaining question is how to envelope the above code in transaction?

提交回复
热议问题