使用 csv 文件填充 Room 数据库 [英] Populate Room database using csv file

查看:36
本文介绍了使用 csv 文件填充 Room 数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将 9000 个城市保存在数据库中,以便用户按城市进行搜索.

I have 9000 cities that i need to save on database to allow the users to search by cities.

我的房间桌子是:

@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 文件包含类似的行

The .csv file contains rows like

1;AC;Acrelandia
2;AC;Assis Brasil

其中的行是:ID、状态和名称.

where the rows are: ID, state and name.

我的 DatabaseModule 是下一个:

And my DatabaseModule is the next:

@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?

I found that we can set an "addCallback" option to the database builder, to setup data when the DB is initialized.. but, how can i access the dao there?

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();

任何想法如何做到这一点?

Any ideas how to do this?

任何帮助将不胜感激!

推荐答案

我最近不得不对 JSON 做一些类似的事情,而您已经非常接近解决您的问题了.我将创建一个静态帮助器类来将 CSV 文件读入 City 对象列表,假设该方法具有类似 public List 的签名;CsvUtils 类中的 getCityList().然后在您的 .addCallBack 中,您将执行以下操作:

I had to do something similar with JSON recently and you're pretty close to solving your problem. I would create a static helper class to read the CSV files into a List of City objects, let's say that method has a signature like public List<City> getCityList() in a CsvUtils class. Then in your .addCallBack you would do something like:

@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());
        }
    });
}

这篇关于使用 csv 文件填充 Room 数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆