1

我有一个实体(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
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()方法中触发选择查询时,ClientActivity它没有返回插入的实体。以下是代码:

private void displayClients()
    {
        Intent intent = getIntent();
        boolean shouldRefreshData = intent.getBooleanExtra(IntentKeysKt.getShouldRefreshData(),false);
        Toast.makeText(this, "shouldRefreshData="+shouldRefreshData, Toast.LENGTH_SHORT).show();
        if (shouldRefreshData) {
            //Load data from clients table
            intent.putExtra(IntentKeysKt.getShouldRefreshData(), false);
            ClientsRetrievalTask clientsRetrievalTask = new ClientsRetrievalTask(this);
            clientsRetrievalTask.execute(agentGUID);
        }
    }

@Override
    public void clientsRetrieved(@NotNull List<Client> clients) {
        clientsAdapter.refresh(new ArrayList<>(clients));
        recyclerViewClients.setVisibility(View.VISIBLE);
        frameLayoutPlaceholderFragment.setVisibility(View.INVISIBLE);
    } 

令人惊讶的是,在下次启动应用程序时,它会显示插入的记录。我一无所知请指导我。

4

1 回答 1

1

你应该使用;

  1. Database.beginTransaction()在插入操作之前。
  2. Database.setTransactionSuccessful()插入操作后。
  3. 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();
    }
}

示例参考

于 2017-06-08T05:58:02.420 回答