我有9000个城市需要保存在数据库中,以允许用户按城市搜索。
我的房间表是:
@Entity
public class City extends Model{
@PrimaryKey
@NonNull
private String id = UUID.randomUUID().toString();
private String name;
private String state;
public City(@NonNull String id, String name, String state) {
this.id = id;
this.name = name;
this.state = state;
}
@Ignore
public City() {
}
@Ignore
public City(String name, String state) {
this.name = name;
this.state = state;
}
@NonNull
public String getId() {
return id;
}
public void setId(@NonNull String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
@Override
public String toString() {
return name + " - " + state;
}
}
我的DAO是
@Dao
public interface CityDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertAll(List<City> cities);
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(City city);
@Update
void update(City city);
@Delete
void delete(City city);
@Query("DELETE FROM City WHERE id = :id")
void delete(String id);
@Query("SELECT * FROM City")
List<City> getAll();
@Query("SELECT * FROM City WHERE id = :id LIMIT 1")
City findById(String id);
@Query("DELETE FROM City")
void removeAll();
}
.csv文件包含类似
的行1;AC;Acrelandia
2;AC;Assis Brasil
其中的行是:ID,状态和名称。
下一个是我的DatabaseModule:
@Module
public class DatabaseModule {
@Singleton
@Provides
SontraDB provideDb(Application app) {
return Room.databaseBuilder(app, MyDB.class, "mydb.db")
.build();
}
@Singleton
@Provides
CityDao provideCityDao(MyDB db) {
return db.cityDao();
}
我发现我们可以为数据库构建器设置一个“ addCallback”选项,以便在初始化数据库时设置数据。.但是,我如何在那访问dao?
return Room.databaseBuilder(context,
MyDB.class,
"mydb.db")
.addCallback(new Callback() {
@Override
public void onCreate(@NonNull SupportSQLiteDatabase db) {
super.onCreate(db);
Executors.newSingleThreadScheduledExecutor().execute(new Runnable() {
@Override
public void run() {
// insert data using DAO
}
});
}
})
.build();
任何想法如何做到这一点?
任何帮助将不胜感激!
答案 0 :(得分:2)
最近我不得不对JSON做类似的事情,您已经很接近解决问题了。我将创建一个静态帮助程序类,以将CSV文件读取到City对象的列表中,假设该方法在CsvUtils
类中具有类似.addCallBack
的签名。然后,在您的@Override
public void onCreate(@NonNull SupportSQLiteDatabase db) {
super.onCreate(db);
Executors.newSingleThreadScheduledExecutor().execute(new Runnable() {
@Override
public void run() {
// insert data using DAO
provideCityDao(db).insertAll(CsvUtils.getCityList());
}
});
}
中,您将执行以下操作:
incident[components][component_id] - Map of status changes to apply to affected components.