Android Sqlite多线程使用DBFlow + Retrofit保存数据

时间:2016-03-18 09:44:38

标签: android multithreading sqlite retrofit2 dbflow

我使用DBFlow保存到数据库中并使用Retrofit来调用我的Web服务。我的改造类与我的数据库表是同一个类。但是,当同时启动2个或更多线程以将我的数据保存到表中时,我遇到了问题。插入到我的表中会复制我的数据,主键也会重复。然后我的线程被停止,因为它崩溃了。

你有解决方案吗?

Retrofit和DBFlow类

@Table(database = LocalDB.class)
@Root(name = "picture_infos")
public class PictureInfos extends BaseModel {

@PrimaryKey
@Element(name = "id_picture")
private int idPicture;

@Column
@Element(name = "id_account")
private String idAccount;

@Column
@Element(name = "folder_path")
private String folderPath;

@Column
@Element(name = "filename")
private String filename;

@Column
@Element(name = "legend", required = false)
private String legend;

public int getIdPicture() {
    return idPicture;
}

public void setIdPicture(int idPicture) {
    this.idPicture = idPicture;
}

public String getIdAccount() {
    return idAccount;
}

public void setIdAccount(String idAccount) {
    this.idAccount = idAccount;
}

public String getFolderPath() {
    return folderPath;
}

public void setFolderPath(String folderPath) {
    this.folderPath = folderPath;
}

public String getFilename() {
    return filename;
}

public void setFilename(String filename) {
    this.filename = filename;
}

public String getLegend() {
    return legend;
}

public void setLegend(String legend) {
    this.legend = legend;
}
}

改进响应中的线程

public void onResponse(Call<AdminPictures> call, Response<AdminPictures> response) {
            AdminPictures apResponse = response.body();
            final List<PictureInfos> pictureInfos = apResponse.getPicturesList();
            new Thread(new Runnable() {
                @Override
                    public void run() {
                        try {
                            for (PictureInfos infos : pictureInfos) {
                    // This save duplicate when I've 2 or more threads
                              synchronized (infos){
                                if(!infos.exists()){
                                   infos.save();
                                 }
                              }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();

堆栈跟踪

    03-18 12:01:18.950 15696-19086/com.vigizen.client.kiosqueadmin E/SQLiteLog: (1555) abort at 12 in [INSERT INTO `PictureInfos`(`idPicture`,`idAccount`,`folderPath`,`filename`,`legend`) VALUES (?,?,?,?,?)]: UNIQUE constraint failed: PictureInfos.idPicture
    03-18 12:01:18.951 15696-19086/com.vigizen.client.kiosqueadmin W/System.err: android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: PictureInfos.idPicture (code 1555)
    03-18 12:01:18.951 15696-19086/com.vigizen.client.kiosqueadmin W/System.err:     at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
    03-18 12:01:18.951 15696-19086/com.vigizen.client.kiosqueadmin W/System.err:     at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:788)
    03-18 12:01:18.951 15696-19086/com.vigizen.client.kiosqueadmin W/System.err:     at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
    03-18 12:01:18.951 15696-19086/com.vigizen.client.kiosqueadmin W/System.err:     at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
    03-18 12:01:18.951 15696-19086/com.vigizen.client.kiosqueadmin W/System.err:     at com.raizlabs.android.dbflow.structure.database.AndroidDatabaseStatement.executeInsert(AndroidDatabaseStatement.java:77)
    03-18 12:01:18.951 15696-19086/com.vigizen.client.kiosqueadmin W/System.err:     at com.raizlabs.android.dbflow.sql.SqlUtils.insert(SqlUtils.java:370)
    03-18 12:01:18.951 15696-19086/com.vigizen.client.kiosqueadmin W/System.err:     at com.raizlabs.android.dbflow.sql.SqlUtils.save(SqlUtils.java:327)
    03-18 12:01:18.951 15696-19086/com.vigizen.client.kiosqueadmin W/System.err:     at com.raizlabs.android.dbflow.structure.ModelAdapter.save(ModelAdapter.java:60)
    03-18 12:01:18.951 15696-19086/com.vigizen.client.kiosqueadmin W/System.err:     at com.raizlabs.android.dbflow.structure.BaseModel.save(BaseModel.java:52)
    03-18 12:01:18.951 15696-19086/com.vigizen.client.kiosqueadmin W/System.err:     at com.vigizen.client.kiosqueadmin.GalleryActivity$1$1.run(GalleryActivity.java:188)
    03-18 12:01:18.951 15696-19086/com.vigizen.client.kiosqueadmin W/System.err:     at java.lang.Thread.run(Thread.java:818)

2 个答案:

答案 0 :(得分:0)

你在这里做的是docs of DBFlow中的第一个“不做”。您应该在这里使用的是存储数据的事务。这会锁定数据库以进行独占批处理操作,并且应该比迭代所有模型快得多,并逐个保存。

基本上,您希望在FastStoreModelTransaction.saveBuilder()使用基本上INSERT OR UPDATE的{​​{1}}。

用法就是这样:

public void onResponse(Call<AdminPictures> call, Response<AdminPictures> response) {
    AdminPictures apResponse = response.body();
    final List<PictureInfos> pictureInfos = apResponse.getPicturesList();

    FastStoreModelTransaction transaction = FastStoreModelTransaction.saveBuilder(FlowManager.getModelAdapter(PictureInfos.class))
        .addAll(pictureInfos)
        .build();

    database.executeTransaction(transaction);
}

请注意,这会自动在后台运行,因此无需将其包装在额外的线程中。如果您需要在存储过程中使用监听器,请改用ProcessModelTransaction

答案 1 :(得分:-2)

读取数据库可以并行完成而不会互相干扰,但如果你有密钥,应该以同步的方式写入数据库。

您应该在同步方法中编写save。同步只允许一个线程一次进行更改。

注意: 默认情况下,android SQLiteDatabase Object对于多线程是安全的。 DBFlow也是。确保在多个线程中使用相同的帮助程序实例。

Details