我有一个实体(Kotlin代码):
@Entity(foreignKeys = arrayOf(ForeignKey(entity = Agent::class, parentColumns = arrayOf("guid"), childColumns = arrayOf("agentGuid"), onDelete = ForeignKey.CASCADE)))
data class Client (@PrimaryKey
var guid: String = "",
var name: String = "",
var email: String = "",
var phone: String = "",
var address: String = "",
var agentGuid: String = "")
以下是Dao Class:
@Dao
public interface ClientDao {
@Query("SELECT * FROM Client where guid = :clientGUID LIMIT 1")
Client getClient(String clientGUID);
@Query("SELECT * FROM Client where agentGuid = :agentGUID")
List<Client> getClients(String agentGUID);
@Insert
void insertClient(Client client);
}
以下是我正在执行插入操作的后台任务:
interface UpdateClientTaskResponseHandler {
fun clientUpdated(client: Client)
fun clientUpdateFailed()
}
data class ClientData(var client: Client, var documents: ArrayList<Document>)
class UpdateClientDataTask(val responseHandler: UpdateClientTaskResponseHandler): AsyncTask<ClientData, Void, Client?>() {
override fun doInBackground(vararg params: ClientData?): Client? {
params[0]?.let {
val clientDao = MyApp.database!!.clientDao()
//1: Check if client exists or not
val client = clientDao.getClient(it.client.guid)
if (client != null) {
//TODO: to be handled
// Update functionality
} else {
//2. Insert client
clientDao.insertClient(it.client)
//3. Insert all documents
if (it.documents.size > 0) {
val documentDao = MyApp.database!!.documentDao()
documentDao.insertDocuments(it.documents)
}
return it.client
}
return null
}
return null
}
override fun onPostExecute(result: Client?) {
result?.let {
responseHandler.clientUpdated(it)
} ?: responseHandler.clientUpdateFailed()
}
}
我使用下面的代码插入实体:
public void confirmClient(View view) {
// Creating client object
Client client = new Client(clientGuid, name, email, phone, address, agentGuid);
// Creating client data object
ClientData clientData = new ClientData(client, documentsAdapter.documents);
UpdateClientDataTask updateClientDataTask = new UpdateClientDataTask(this);
updateClientDataTask.execute(clientData);
}
成功后我调用下面的代码跳回ClientActivity
:
@Override
public void clientUpdated(@NotNull Client client) {
Intent clientsActivity = new Intent(this,ClientActivity.class);
clientsActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP );
clientsActivity.putExtra(IntentKeysKt.getShouldRefreshData(), true);
startActivity(clientsActivity);
}
我的问题是 - 当我在onResume()
的{{1}}方法中触发选择查询时,它没有返回插入的实体。
以下是代码:
ClientActivity
令人惊讶的是,在下次应用启动时,它会显示插入的记录。我无能为力,请指教我。
答案 0 :(得分:1)
你应该使用;
Database.beginTransaction()
。Database.setTransactionSuccessful()
。Database.endTransaction()
终于。示例代码:
private static void insertData(AppDatabase db, List<ProductEntity> products, List<CommentEntity> comments) {
db.beginTransaction();
try {
db.productDao().insertAll(products);
db.commentDao().insertAll(comments);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}